PackageManagerService.java revision 8558ec7dbe7733a36b621b24309e7a9dd9deec8c
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.TimingsTraceLog;
231import android.util.DisplayMetrics;
232import android.util.EventLog;
233import android.util.ExceptionUtils;
234import android.util.Log;
235import android.util.LogPrinter;
236import android.util.MathUtils;
237import android.util.PackageUtils;
238import android.util.Pair;
239import android.util.PrintStreamPrinter;
240import android.util.Slog;
241import android.util.SparseArray;
242import android.util.SparseBooleanArray;
243import android.util.SparseIntArray;
244import android.util.Xml;
245import android.util.jar.StrictJarFile;
246import android.util.proto.ProtoOutputStream;
247import android.view.Display;
248
249import com.android.internal.R;
250import com.android.internal.annotations.GuardedBy;
251import com.android.internal.app.IMediaContainerService;
252import com.android.internal.app.ResolverActivity;
253import com.android.internal.content.NativeLibraryHelper;
254import com.android.internal.content.PackageHelper;
255import com.android.internal.logging.MetricsLogger;
256import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
257import com.android.internal.os.IParcelFileDescriptorFactory;
258import com.android.internal.os.RoSystemProperties;
259import com.android.internal.os.SomeArgs;
260import com.android.internal.os.Zygote;
261import com.android.internal.telephony.CarrierAppUtils;
262import com.android.internal.util.ArrayUtils;
263import com.android.internal.util.ConcurrentUtils;
264import com.android.internal.util.DumpUtils;
265import com.android.internal.util.FastPrintWriter;
266import com.android.internal.util.FastXmlSerializer;
267import com.android.internal.util.IndentingPrintWriter;
268import com.android.internal.util.Preconditions;
269import com.android.internal.util.XmlUtils;
270import com.android.server.AttributeCache;
271import com.android.server.DeviceIdleController;
272import com.android.server.EventLogTags;
273import com.android.server.FgThread;
274import com.android.server.IntentResolver;
275import com.android.server.LocalServices;
276import com.android.server.LockGuard;
277import com.android.server.ServiceThread;
278import com.android.server.SystemConfig;
279import com.android.server.SystemServerInitThreadPool;
280import com.android.server.Watchdog;
281import com.android.server.net.NetworkPolicyManagerInternal;
282import com.android.server.pm.Installer.InstallerException;
283import com.android.server.pm.PermissionsState.PermissionState;
284import com.android.server.pm.Settings.DatabaseVersion;
285import com.android.server.pm.Settings.VersionInfo;
286import com.android.server.pm.dex.DexManager;
287import com.android.server.pm.dex.DexoptOptions;
288import com.android.server.pm.dex.PackageDexUsage;
289import com.android.server.storage.DeviceStorageMonitorInternal;
290
291import dalvik.system.CloseGuard;
292import dalvik.system.DexFile;
293import dalvik.system.VMRuntime;
294
295import libcore.io.IoUtils;
296import libcore.io.Streams;
297import libcore.util.EmptyArray;
298
299import org.xmlpull.v1.XmlPullParser;
300import org.xmlpull.v1.XmlPullParserException;
301import org.xmlpull.v1.XmlSerializer;
302
303import java.io.BufferedOutputStream;
304import java.io.BufferedReader;
305import java.io.ByteArrayInputStream;
306import java.io.ByteArrayOutputStream;
307import java.io.File;
308import java.io.FileDescriptor;
309import java.io.FileInputStream;
310import java.io.FileOutputStream;
311import java.io.FileReader;
312import java.io.FilenameFilter;
313import java.io.IOException;
314import java.io.InputStream;
315import java.io.OutputStream;
316import java.io.PrintWriter;
317import java.lang.annotation.Retention;
318import java.lang.annotation.RetentionPolicy;
319import java.nio.charset.StandardCharsets;
320import java.security.DigestInputStream;
321import java.security.MessageDigest;
322import java.security.NoSuchAlgorithmException;
323import java.security.PublicKey;
324import java.security.SecureRandom;
325import java.security.cert.Certificate;
326import java.security.cert.CertificateEncodingException;
327import java.security.cert.CertificateException;
328import java.text.SimpleDateFormat;
329import java.util.ArrayList;
330import java.util.Arrays;
331import java.util.Collection;
332import java.util.Collections;
333import java.util.Comparator;
334import java.util.Date;
335import java.util.HashMap;
336import java.util.HashSet;
337import java.util.Iterator;
338import java.util.List;
339import java.util.Map;
340import java.util.Objects;
341import java.util.Set;
342import java.util.concurrent.CountDownLatch;
343import java.util.concurrent.Future;
344import java.util.concurrent.TimeUnit;
345import java.util.concurrent.atomic.AtomicBoolean;
346import java.util.concurrent.atomic.AtomicInteger;
347import java.util.zip.GZIPInputStream;
348
349/**
350 * Keep track of all those APKs everywhere.
351 * <p>
352 * Internally there are two important locks:
353 * <ul>
354 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
355 * and other related state. It is a fine-grained lock that should only be held
356 * momentarily, as it's one of the most contended locks in the system.
357 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
358 * operations typically involve heavy lifting of application data on disk. Since
359 * {@code installd} is single-threaded, and it's operations can often be slow,
360 * this lock should never be acquired while already holding {@link #mPackages}.
361 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
362 * holding {@link #mInstallLock}.
363 * </ul>
364 * Many internal methods rely on the caller to hold the appropriate locks, and
365 * this contract is expressed through method name suffixes:
366 * <ul>
367 * <li>fooLI(): the caller must hold {@link #mInstallLock}
368 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
369 * being modified must be frozen
370 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
371 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
372 * </ul>
373 * <p>
374 * Because this class is very central to the platform's security; please run all
375 * CTS and unit tests whenever making modifications:
376 *
377 * <pre>
378 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
379 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
380 * </pre>
381 */
382public class PackageManagerService extends IPackageManager.Stub
383        implements PackageSender {
384    static final String TAG = "PackageManager";
385    static final boolean DEBUG_SETTINGS = false;
386    static final boolean DEBUG_PREFERRED = false;
387    static final boolean DEBUG_UPGRADE = false;
388    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
389    private static final boolean DEBUG_BACKUP = false;
390    private static final boolean DEBUG_INSTALL = false;
391    private static final boolean DEBUG_REMOVE = false;
392    private static final boolean DEBUG_BROADCASTS = false;
393    private static final boolean DEBUG_SHOW_INFO = false;
394    private static final boolean DEBUG_PACKAGE_INFO = false;
395    private static final boolean DEBUG_INTENT_MATCHING = false;
396    private static final boolean DEBUG_PACKAGE_SCANNING = false;
397    private static final boolean DEBUG_VERIFY = false;
398    private static final boolean DEBUG_FILTERS = false;
399    private static final boolean DEBUG_PERMISSIONS = false;
400    private static final boolean DEBUG_SHARED_LIBRARIES = false;
401    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
402
403    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
404    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
405    // user, but by default initialize to this.
406    public static final boolean DEBUG_DEXOPT = false;
407
408    private static final boolean DEBUG_ABI_SELECTION = false;
409    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
410    private static final boolean DEBUG_TRIAGED_MISSING = false;
411    private static final boolean DEBUG_APP_DATA = false;
412
413    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
414    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
415
416    private static final boolean HIDE_EPHEMERAL_APIS = false;
417
418    private static final boolean ENABLE_FREE_CACHE_V2 =
419            SystemProperties.getBoolean("fw.free_cache_v2", true);
420
421    private static final int RADIO_UID = Process.PHONE_UID;
422    private static final int LOG_UID = Process.LOG_UID;
423    private static final int NFC_UID = Process.NFC_UID;
424    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
425    private static final int SHELL_UID = Process.SHELL_UID;
426
427    // Cap the size of permission trees that 3rd party apps can define
428    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
429
430    // Suffix used during package installation when copying/moving
431    // package apks to install directory.
432    private static final String INSTALL_PACKAGE_SUFFIX = "-";
433
434    static final int SCAN_NO_DEX = 1<<1;
435    static final int SCAN_FORCE_DEX = 1<<2;
436    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
437    static final int SCAN_NEW_INSTALL = 1<<4;
438    static final int SCAN_UPDATE_TIME = 1<<5;
439    static final int SCAN_BOOTING = 1<<6;
440    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
441    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
442    static final int SCAN_REPLACING = 1<<9;
443    static final int SCAN_REQUIRE_KNOWN = 1<<10;
444    static final int SCAN_MOVE = 1<<11;
445    static final int SCAN_INITIAL = 1<<12;
446    static final int SCAN_CHECK_ONLY = 1<<13;
447    static final int SCAN_DONT_KILL_APP = 1<<14;
448    static final int SCAN_IGNORE_FROZEN = 1<<15;
449    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
450    static final int SCAN_AS_INSTANT_APP = 1<<17;
451    static final int SCAN_AS_FULL_APP = 1<<18;
452    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
453    /** Should not be with the scan flags */
454    static final int FLAGS_REMOVE_CHATTY = 1<<31;
455
456    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
457    /** Extension of the compressed packages */
458    private final static String COMPRESSED_EXTENSION = ".gz";
459    /** Suffix of stub packages on the system partition */
460    private final static String STUB_SUFFIX = "-Stub";
461
462    private static final int[] EMPTY_INT_ARRAY = new int[0];
463
464    private static final int TYPE_UNKNOWN = 0;
465    private static final int TYPE_ACTIVITY = 1;
466    private static final int TYPE_RECEIVER = 2;
467    private static final int TYPE_SERVICE = 3;
468    private static final int TYPE_PROVIDER = 4;
469    @IntDef(prefix = { "TYPE_" }, value = {
470            TYPE_UNKNOWN,
471            TYPE_ACTIVITY,
472            TYPE_RECEIVER,
473            TYPE_SERVICE,
474            TYPE_PROVIDER,
475    })
476    @Retention(RetentionPolicy.SOURCE)
477    public @interface ComponentType {}
478
479    /**
480     * Timeout (in milliseconds) after which the watchdog should declare that
481     * our handler thread is wedged.  The usual default for such things is one
482     * minute but we sometimes do very lengthy I/O operations on this thread,
483     * such as installing multi-gigabyte applications, so ours needs to be longer.
484     */
485    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
486
487    /**
488     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
489     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
490     * settings entry if available, otherwise we use the hardcoded default.  If it's been
491     * more than this long since the last fstrim, we force one during the boot sequence.
492     *
493     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
494     * one gets run at the next available charging+idle time.  This final mandatory
495     * no-fstrim check kicks in only of the other scheduling criteria is never met.
496     */
497    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
498
499    /**
500     * Whether verification is enabled by default.
501     */
502    private static final boolean DEFAULT_VERIFY_ENABLE = true;
503
504    /**
505     * The default maximum time to wait for the verification agent to return in
506     * milliseconds.
507     */
508    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
509
510    /**
511     * The default response for package verification timeout.
512     *
513     * This can be either PackageManager.VERIFICATION_ALLOW or
514     * PackageManager.VERIFICATION_REJECT.
515     */
516    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
517
518    static final String PLATFORM_PACKAGE_NAME = "android";
519
520    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
521
522    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
523            DEFAULT_CONTAINER_PACKAGE,
524            "com.android.defcontainer.DefaultContainerService");
525
526    private static final String KILL_APP_REASON_GIDS_CHANGED =
527            "permission grant or revoke changed gids";
528
529    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
530            "permissions revoked";
531
532    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
533
534    private static final String PACKAGE_SCHEME = "package";
535
536    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
537
538    /** Permission grant: not grant the permission. */
539    private static final int GRANT_DENIED = 1;
540
541    /** Permission grant: grant the permission as an install permission. */
542    private static final int GRANT_INSTALL = 2;
543
544    /** Permission grant: grant the permission as a runtime one. */
545    private static final int GRANT_RUNTIME = 3;
546
547    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
548    private static final int GRANT_UPGRADE = 4;
549
550    /** Canonical intent used to identify what counts as a "web browser" app */
551    private static final Intent sBrowserIntent;
552    static {
553        sBrowserIntent = new Intent();
554        sBrowserIntent.setAction(Intent.ACTION_VIEW);
555        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
556        sBrowserIntent.setData(Uri.parse("http:"));
557    }
558
559    /**
560     * The set of all protected actions [i.e. those actions for which a high priority
561     * intent filter is disallowed].
562     */
563    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
564    static {
565        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
566        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
568        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
569    }
570
571    // Compilation reasons.
572    public static final int REASON_FIRST_BOOT = 0;
573    public static final int REASON_BOOT = 1;
574    public static final int REASON_INSTALL = 2;
575    public static final int REASON_BACKGROUND_DEXOPT = 3;
576    public static final int REASON_AB_OTA = 4;
577    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
578
579    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
580
581    /** All dangerous permission names in the same order as the events in MetricsEvent */
582    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
583            Manifest.permission.READ_CALENDAR,
584            Manifest.permission.WRITE_CALENDAR,
585            Manifest.permission.CAMERA,
586            Manifest.permission.READ_CONTACTS,
587            Manifest.permission.WRITE_CONTACTS,
588            Manifest.permission.GET_ACCOUNTS,
589            Manifest.permission.ACCESS_FINE_LOCATION,
590            Manifest.permission.ACCESS_COARSE_LOCATION,
591            Manifest.permission.RECORD_AUDIO,
592            Manifest.permission.READ_PHONE_STATE,
593            Manifest.permission.CALL_PHONE,
594            Manifest.permission.READ_CALL_LOG,
595            Manifest.permission.WRITE_CALL_LOG,
596            Manifest.permission.ADD_VOICEMAIL,
597            Manifest.permission.USE_SIP,
598            Manifest.permission.PROCESS_OUTGOING_CALLS,
599            Manifest.permission.READ_CELL_BROADCASTS,
600            Manifest.permission.BODY_SENSORS,
601            Manifest.permission.SEND_SMS,
602            Manifest.permission.RECEIVE_SMS,
603            Manifest.permission.READ_SMS,
604            Manifest.permission.RECEIVE_WAP_PUSH,
605            Manifest.permission.RECEIVE_MMS,
606            Manifest.permission.READ_EXTERNAL_STORAGE,
607            Manifest.permission.WRITE_EXTERNAL_STORAGE,
608            Manifest.permission.READ_PHONE_NUMBERS,
609            Manifest.permission.ANSWER_PHONE_CALLS);
610
611
612    /**
613     * Version number for the package parser cache. Increment this whenever the format or
614     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
615     */
616    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
617
618    /**
619     * Whether the package parser cache is enabled.
620     */
621    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
622
623    final ServiceThread mHandlerThread;
624
625    final PackageHandler mHandler;
626
627    private final ProcessLoggingHandler mProcessLoggingHandler;
628
629    /**
630     * Messages for {@link #mHandler} that need to wait for system ready before
631     * being dispatched.
632     */
633    private ArrayList<Message> mPostSystemReadyMessages;
634
635    final int mSdkVersion = Build.VERSION.SDK_INT;
636
637    final Context mContext;
638    final boolean mFactoryTest;
639    final boolean mOnlyCore;
640    final DisplayMetrics mMetrics;
641    final int mDefParseFlags;
642    final String[] mSeparateProcesses;
643    final boolean mIsUpgrade;
644    final boolean mIsPreNUpgrade;
645    final boolean mIsPreNMR1Upgrade;
646
647    // Have we told the Activity Manager to whitelist the default container service by uid yet?
648    @GuardedBy("mPackages")
649    boolean mDefaultContainerWhitelisted = false;
650
651    @GuardedBy("mPackages")
652    private boolean mDexOptDialogShown;
653
654    /** The location for ASEC container files on internal storage. */
655    final String mAsecInternalPath;
656
657    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
658    // LOCK HELD.  Can be called with mInstallLock held.
659    @GuardedBy("mInstallLock")
660    final Installer mInstaller;
661
662    /** Directory where installed third-party apps stored */
663    final File mAppInstallDir;
664
665    /**
666     * Directory to which applications installed internally have their
667     * 32 bit native libraries copied.
668     */
669    private File mAppLib32InstallDir;
670
671    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
672    // apps.
673    final File mDrmAppPrivateInstallDir;
674
675    // ----------------------------------------------------------------
676
677    // Lock for state used when installing and doing other long running
678    // operations.  Methods that must be called with this lock held have
679    // the suffix "LI".
680    final Object mInstallLock = new Object();
681
682    // ----------------------------------------------------------------
683
684    // Keys are String (package name), values are Package.  This also serves
685    // as the lock for the global state.  Methods that must be called with
686    // this lock held have the prefix "LP".
687    @GuardedBy("mPackages")
688    final ArrayMap<String, PackageParser.Package> mPackages =
689            new ArrayMap<String, PackageParser.Package>();
690
691    final ArrayMap<String, Set<String>> mKnownCodebase =
692            new ArrayMap<String, Set<String>>();
693
694    // Keys are isolated uids and values are the uid of the application
695    // that created the isolated proccess.
696    @GuardedBy("mPackages")
697    final SparseIntArray mIsolatedOwners = new SparseIntArray();
698
699    /**
700     * Tracks new system packages [received in an OTA] that we expect to
701     * find updated user-installed versions. Keys are package name, values
702     * are package location.
703     */
704    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
705    /**
706     * Tracks high priority intent filters for protected actions. During boot, certain
707     * filter actions are protected and should never be allowed to have a high priority
708     * intent filter for them. However, there is one, and only one exception -- the
709     * setup wizard. It must be able to define a high priority intent filter for these
710     * actions to ensure there are no escapes from the wizard. We need to delay processing
711     * of these during boot as we need to look at all of the system packages in order
712     * to know which component is the setup wizard.
713     */
714    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
715    /**
716     * Whether or not processing protected filters should be deferred.
717     */
718    private boolean mDeferProtectedFilters = true;
719
720    /**
721     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
722     */
723    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
724    /**
725     * Whether or not system app permissions should be promoted from install to runtime.
726     */
727    boolean mPromoteSystemApps;
728
729    @GuardedBy("mPackages")
730    final Settings mSettings;
731
732    /**
733     * Set of package names that are currently "frozen", which means active
734     * surgery is being done on the code/data for that package. The platform
735     * will refuse to launch frozen packages to avoid race conditions.
736     *
737     * @see PackageFreezer
738     */
739    @GuardedBy("mPackages")
740    final ArraySet<String> mFrozenPackages = new ArraySet<>();
741
742    final ProtectedPackages mProtectedPackages;
743
744    @GuardedBy("mLoadedVolumes")
745    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
746
747    boolean mFirstBoot;
748
749    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
750
751    // System configuration read by SystemConfig.
752    final int[] mGlobalGids;
753    final SparseArray<ArraySet<String>> mSystemPermissions;
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    // If mac_permissions.xml was found for seinfo labeling.
758    boolean mFoundPolicyFile;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            List<PackageParser.Package> overlayPackages = null;
785            for (PackageParser.Package p : allPackages) {
786                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
787                    if (overlayPackages == null) {
788                        overlayPackages = new ArrayList<PackageParser.Package>();
789                    }
790                    overlayPackages.add(p);
791                }
792            }
793            if (overlayPackages != null) {
794                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
795                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
796                        return p1.mOverlayPriority - p2.mOverlayPriority;
797                    }
798                };
799                Collections.sort(overlayPackages, cmp);
800            }
801            return overlayPackages;
802        }
803
804        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
805                String targetPackageName, String targetPath) {
806            if ("android".equals(targetPackageName)) {
807                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
808                // native AssetManager.
809                return null;
810            }
811            List<PackageParser.Package> overlayPackages =
812                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            synchronized (mPackages) {
849                return getStaticOverlayPathsLocked(
850                        mPackages.values(), targetPackageName, targetPath);
851            }
852        }
853
854        @Override public final String[] getOverlayApks(String targetPackageName) {
855            return getStaticOverlayPaths(targetPackageName, null);
856        }
857
858        @Override public final String[] getOverlayPaths(String targetPackageName,
859                String targetPath) {
860            return getStaticOverlayPaths(targetPackageName, targetPath);
861        }
862    };
863
864    class ParallelPackageParserCallback extends PackageParserCallback {
865        List<PackageParser.Package> mOverlayPackages = null;
866
867        void findStaticOverlayPackages() {
868            synchronized (mPackages) {
869                for (PackageParser.Package p : mPackages.values()) {
870                    if (p.mIsStaticOverlay) {
871                        if (mOverlayPackages == null) {
872                            mOverlayPackages = new ArrayList<PackageParser.Package>();
873                        }
874                        mOverlayPackages.add(p);
875                    }
876                }
877            }
878        }
879
880        @Override
881        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
882            // We can trust mOverlayPackages without holding mPackages because package uninstall
883            // can't happen while running parallel parsing.
884            // Moreover holding mPackages on each parsing thread causes dead-lock.
885            return mOverlayPackages == null ? null :
886                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
887        }
888    }
889
890    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
891    final ParallelPackageParserCallback mParallelPackageParserCallback =
892            new ParallelPackageParserCallback();
893
894    public static final class SharedLibraryEntry {
895        public final @Nullable String path;
896        public final @Nullable String apk;
897        public final @NonNull SharedLibraryInfo info;
898
899        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
900                String declaringPackageName, int declaringPackageVersionCode) {
901            path = _path;
902            apk = _apk;
903            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
904                    declaringPackageName, declaringPackageVersionCode), null);
905        }
906    }
907
908    // Currently known shared libraries.
909    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
910    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
911            new ArrayMap<>();
912
913    // All available activities, for your resolving pleasure.
914    final ActivityIntentResolver mActivities =
915            new ActivityIntentResolver();
916
917    // All available receivers, for your resolving pleasure.
918    final ActivityIntentResolver mReceivers =
919            new ActivityIntentResolver();
920
921    // All available services, for your resolving pleasure.
922    final ServiceIntentResolver mServices = new ServiceIntentResolver();
923
924    // All available providers, for your resolving pleasure.
925    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
926
927    // Mapping from provider base names (first directory in content URI codePath)
928    // to the provider information.
929    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
930            new ArrayMap<String, PackageParser.Provider>();
931
932    // Mapping from instrumentation class names to info about them.
933    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
934            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
935
936    // Mapping from permission names to info about them.
937    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
938            new ArrayMap<String, PackageParser.PermissionGroup>();
939
940    // Packages whose data we have transfered into another package, thus
941    // should no longer exist.
942    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
943
944    // Broadcast actions that are only available to the system.
945    @GuardedBy("mProtectedBroadcasts")
946    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
947
948    /** List of packages waiting for verification. */
949    final SparseArray<PackageVerificationState> mPendingVerification
950            = new SparseArray<PackageVerificationState>();
951
952    /** Set of packages associated with each app op permission. */
953    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
954
955    final PackageInstallerService mInstallerService;
956
957    private final PackageDexOptimizer mPackageDexOptimizer;
958    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
959    // is used by other apps).
960    private final DexManager mDexManager;
961
962    private AtomicInteger mNextMoveId = new AtomicInteger();
963    private final MoveCallbacks mMoveCallbacks;
964
965    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
966
967    // Cache of users who need badging.
968    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
969
970    /** Token for keys in mPendingVerification. */
971    private int mPendingVerificationToken = 0;
972
973    volatile boolean mSystemReady;
974    volatile boolean mSafeMode;
975    volatile boolean mHasSystemUidErrors;
976    private volatile boolean mEphemeralAppsDisabled;
977
978    ApplicationInfo mAndroidApplication;
979    final ActivityInfo mResolveActivity = new ActivityInfo();
980    final ResolveInfo mResolveInfo = new ResolveInfo();
981    ComponentName mResolveComponentName;
982    PackageParser.Package mPlatformPackage;
983    ComponentName mCustomResolverComponentName;
984
985    boolean mResolverReplaced = false;
986
987    private final @Nullable ComponentName mIntentFilterVerifierComponent;
988    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
989
990    private int mIntentFilterVerificationToken = 0;
991
992    /** The service connection to the ephemeral resolver */
993    final EphemeralResolverConnection mInstantAppResolverConnection;
994    /** Component used to show resolver settings for Instant Apps */
995    final ComponentName mInstantAppResolverSettingsComponent;
996
997    /** Activity used to install instant applications */
998    ActivityInfo mInstantAppInstallerActivity;
999    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1000
1001    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1002            = new SparseArray<IntentFilterVerificationState>();
1003
1004    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1005
1006    // List of packages names to keep cached, even if they are uninstalled for all users
1007    private List<String> mKeepUninstalledPackages;
1008
1009    private UserManagerInternal mUserManagerInternal;
1010
1011    private DeviceIdleController.LocalService mDeviceIdleController;
1012
1013    private File mCacheDir;
1014
1015    private ArraySet<String> mPrivappPermissionsViolations;
1016
1017    private Future<?> mPrepareAppDataFuture;
1018
1019    private static class IFVerificationParams {
1020        PackageParser.Package pkg;
1021        boolean replacing;
1022        int userId;
1023        int verifierUid;
1024
1025        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1026                int _userId, int _verifierUid) {
1027            pkg = _pkg;
1028            replacing = _replacing;
1029            userId = _userId;
1030            replacing = _replacing;
1031            verifierUid = _verifierUid;
1032        }
1033    }
1034
1035    private interface IntentFilterVerifier<T extends IntentFilter> {
1036        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1037                                               T filter, String packageName);
1038        void startVerifications(int userId);
1039        void receiveVerificationResponse(int verificationId);
1040    }
1041
1042    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1043        private Context mContext;
1044        private ComponentName mIntentFilterVerifierComponent;
1045        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1046
1047        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1048            mContext = context;
1049            mIntentFilterVerifierComponent = verifierComponent;
1050        }
1051
1052        private String getDefaultScheme() {
1053            return IntentFilter.SCHEME_HTTPS;
1054        }
1055
1056        @Override
1057        public void startVerifications(int userId) {
1058            // Launch verifications requests
1059            int count = mCurrentIntentFilterVerifications.size();
1060            for (int n=0; n<count; n++) {
1061                int verificationId = mCurrentIntentFilterVerifications.get(n);
1062                final IntentFilterVerificationState ivs =
1063                        mIntentFilterVerificationStates.get(verificationId);
1064
1065                String packageName = ivs.getPackageName();
1066
1067                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1068                final int filterCount = filters.size();
1069                ArraySet<String> domainsSet = new ArraySet<>();
1070                for (int m=0; m<filterCount; m++) {
1071                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1072                    domainsSet.addAll(filter.getHostsList());
1073                }
1074                synchronized (mPackages) {
1075                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1076                            packageName, domainsSet) != null) {
1077                        scheduleWriteSettingsLocked();
1078                    }
1079                }
1080                sendVerificationRequest(verificationId, ivs);
1081            }
1082            mCurrentIntentFilterVerifications.clear();
1083        }
1084
1085        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1086            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1089                    verificationId);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1092                    getDefaultScheme());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1095                    ivs.getHostsString());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1098                    ivs.getPackageName());
1099            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1100            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1101
1102            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1103            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1104                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1105                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1106
1107            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1108            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1109                    "Sending IntentFilter verification broadcast");
1110        }
1111
1112        public void receiveVerificationResponse(int verificationId) {
1113            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1114
1115            final boolean verified = ivs.isVerified();
1116
1117            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1118            final int count = filters.size();
1119            if (DEBUG_DOMAIN_VERIFICATION) {
1120                Slog.i(TAG, "Received verification response " + verificationId
1121                        + " for " + count + " filters, verified=" + verified);
1122            }
1123            for (int n=0; n<count; n++) {
1124                PackageParser.ActivityIntentInfo filter = filters.get(n);
1125                filter.setVerified(verified);
1126
1127                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1128                        + " verified with result:" + verified + " and hosts:"
1129                        + ivs.getHostsString());
1130            }
1131
1132            mIntentFilterVerificationStates.remove(verificationId);
1133
1134            final String packageName = ivs.getPackageName();
1135            IntentFilterVerificationInfo ivi = null;
1136
1137            synchronized (mPackages) {
1138                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1139            }
1140            if (ivi == null) {
1141                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1142                        + verificationId + " packageName:" + packageName);
1143                return;
1144            }
1145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1146                    "Updating IntentFilterVerificationInfo for package " + packageName
1147                            +" verificationId:" + verificationId);
1148
1149            synchronized (mPackages) {
1150                if (verified) {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1152                } else {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1154                }
1155                scheduleWriteSettingsLocked();
1156
1157                final int userId = ivs.getUserId();
1158                if (userId != UserHandle.USER_ALL) {
1159                    final int userStatus =
1160                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1161
1162                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1163                    boolean needUpdate = false;
1164
1165                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1166                    // already been set by the User thru the Disambiguation dialog
1167                    switch (userStatus) {
1168                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1169                            if (verified) {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1171                            } else {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1173                            }
1174                            needUpdate = true;
1175                            break;
1176
1177                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1178                            if (verified) {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1180                                needUpdate = true;
1181                            }
1182                            break;
1183
1184                        default:
1185                            // Nothing to do
1186                    }
1187
1188                    if (needUpdate) {
1189                        mSettings.updateIntentFilterVerificationStatusLPw(
1190                                packageName, updatedStatus, userId);
1191                        scheduleWritePackageRestrictionsLocked(userId);
1192                    }
1193                }
1194            }
1195        }
1196
1197        @Override
1198        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1199                    ActivityIntentInfo filter, String packageName) {
1200            if (!hasValidDomains(filter)) {
1201                return false;
1202            }
1203            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1204            if (ivs == null) {
1205                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1206                        packageName);
1207            }
1208            if (DEBUG_DOMAIN_VERIFICATION) {
1209                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1210            }
1211            ivs.addFilter(filter);
1212            return true;
1213        }
1214
1215        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1216                int userId, int verificationId, String packageName) {
1217            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1218                    verifierUid, userId, packageName);
1219            ivs.setPendingState();
1220            synchronized (mPackages) {
1221                mIntentFilterVerificationStates.append(verificationId, ivs);
1222                mCurrentIntentFilterVerifications.add(verificationId);
1223            }
1224            return ivs;
1225        }
1226    }
1227
1228    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1229        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1230                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1231                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1232    }
1233
1234    // Set of pending broadcasts for aggregating enable/disable of components.
1235    static class PendingPackageBroadcasts {
1236        // for each user id, a map of <package name -> components within that package>
1237        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1238
1239        public PendingPackageBroadcasts() {
1240            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1241        }
1242
1243        public ArrayList<String> get(int userId, String packageName) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            return packages.get(packageName);
1246        }
1247
1248        public void put(int userId, String packageName, ArrayList<String> components) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            packages.put(packageName, components);
1251        }
1252
1253        public void remove(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1255            if (packages != null) {
1256                packages.remove(packageName);
1257            }
1258        }
1259
1260        public void remove(int userId) {
1261            mUidMap.remove(userId);
1262        }
1263
1264        public int userIdCount() {
1265            return mUidMap.size();
1266        }
1267
1268        public int userIdAt(int n) {
1269            return mUidMap.keyAt(n);
1270        }
1271
1272        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1273            return mUidMap.get(userId);
1274        }
1275
1276        public int size() {
1277            // total number of pending broadcast entries across all userIds
1278            int num = 0;
1279            for (int i = 0; i< mUidMap.size(); i++) {
1280                num += mUidMap.valueAt(i).size();
1281            }
1282            return num;
1283        }
1284
1285        public void clear() {
1286            mUidMap.clear();
1287        }
1288
1289        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1290            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1291            if (map == null) {
1292                map = new ArrayMap<String, ArrayList<String>>();
1293                mUidMap.put(userId, map);
1294            }
1295            return map;
1296        }
1297    }
1298    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1299
1300    // Service Connection to remote media container service to copy
1301    // package uri's from external media onto secure containers
1302    // or internal storage.
1303    private IMediaContainerService mContainerService = null;
1304
1305    static final int SEND_PENDING_BROADCAST = 1;
1306    static final int MCS_BOUND = 3;
1307    static final int END_COPY = 4;
1308    static final int INIT_COPY = 5;
1309    static final int MCS_UNBIND = 6;
1310    static final int START_CLEANING_PACKAGE = 7;
1311    static final int FIND_INSTALL_LOC = 8;
1312    static final int POST_INSTALL = 9;
1313    static final int MCS_RECONNECT = 10;
1314    static final int MCS_GIVE_UP = 11;
1315    static final int UPDATED_MEDIA_STATUS = 12;
1316    static final int WRITE_SETTINGS = 13;
1317    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1318    static final int PACKAGE_VERIFIED = 15;
1319    static final int CHECK_PENDING_VERIFICATION = 16;
1320    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1321    static final int INTENT_FILTER_VERIFIED = 18;
1322    static final int WRITE_PACKAGE_LIST = 19;
1323    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1324
1325    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1326
1327    // Delay time in millisecs
1328    static final int BROADCAST_DELAY = 10 * 1000;
1329
1330    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1331            2 * 60 * 60 * 1000L; /* two hours */
1332
1333    static UserManagerService sUserManager;
1334
1335    // Stores a list of users whose package restrictions file needs to be updated
1336    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1337
1338    final private DefaultContainerConnection mDefContainerConn =
1339            new DefaultContainerConnection();
1340    class DefaultContainerConnection implements ServiceConnection {
1341        public void onServiceConnected(ComponentName name, IBinder service) {
1342            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1343            final IMediaContainerService imcs = IMediaContainerService.Stub
1344                    .asInterface(Binder.allowBlocking(service));
1345            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1346        }
1347
1348        public void onServiceDisconnected(ComponentName name) {
1349            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1350        }
1351    }
1352
1353    // Recordkeeping of restore-after-install operations that are currently in flight
1354    // between the Package Manager and the Backup Manager
1355    static class PostInstallData {
1356        public InstallArgs args;
1357        public PackageInstalledInfo res;
1358
1359        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1360            args = _a;
1361            res = _r;
1362        }
1363    }
1364
1365    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1366    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1367
1368    // XML tags for backup/restore of various bits of state
1369    private static final String TAG_PREFERRED_BACKUP = "pa";
1370    private static final String TAG_DEFAULT_APPS = "da";
1371    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1372
1373    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1374    private static final String TAG_ALL_GRANTS = "rt-grants";
1375    private static final String TAG_GRANT = "grant";
1376    private static final String ATTR_PACKAGE_NAME = "pkg";
1377
1378    private static final String TAG_PERMISSION = "perm";
1379    private static final String ATTR_PERMISSION_NAME = "name";
1380    private static final String ATTR_IS_GRANTED = "g";
1381    private static final String ATTR_USER_SET = "set";
1382    private static final String ATTR_USER_FIXED = "fixed";
1383    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1384
1385    // System/policy permission grants are not backed up
1386    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_POLICY_FIXED
1388            | FLAG_PERMISSION_SYSTEM_FIXED
1389            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1390
1391    // And we back up these user-adjusted states
1392    private static final int USER_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_USER_SET
1394            | FLAG_PERMISSION_USER_FIXED
1395            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1396
1397    final @Nullable String mRequiredVerifierPackage;
1398    final @NonNull String mRequiredInstallerPackage;
1399    final @NonNull String mRequiredUninstallerPackage;
1400    final @Nullable String mSetupWizardPackage;
1401    final @Nullable String mStorageManagerPackage;
1402    final @NonNull String mServicesSystemSharedLibraryPackageName;
1403    final @NonNull String mSharedSystemSharedLibraryPackageName;
1404
1405    final boolean mPermissionReviewRequired;
1406
1407    private final PackageUsage mPackageUsage = new PackageUsage();
1408    private final CompilerStats mCompilerStats = new CompilerStats();
1409
1410    class PackageHandler extends Handler {
1411        private boolean mBound = false;
1412        final ArrayList<HandlerParams> mPendingInstalls =
1413            new ArrayList<HandlerParams>();
1414
1415        private boolean connectToService() {
1416            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1417                    " DefaultContainerService");
1418            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1421                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1422                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423                mBound = true;
1424                return true;
1425            }
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            return false;
1428        }
1429
1430        private void disconnectService() {
1431            mContainerService = null;
1432            mBound = false;
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1434            mContext.unbindService(mDefContainerConn);
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436        }
1437
1438        PackageHandler(Looper looper) {
1439            super(looper);
1440        }
1441
1442        public void handleMessage(Message msg) {
1443            try {
1444                doHandleMessage(msg);
1445            } finally {
1446                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1447            }
1448        }
1449
1450        void doHandleMessage(Message msg) {
1451            switch (msg.what) {
1452                case INIT_COPY: {
1453                    HandlerParams params = (HandlerParams) msg.obj;
1454                    int idx = mPendingInstalls.size();
1455                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1456                    // If a bind was already initiated we dont really
1457                    // need to do anything. The pending install
1458                    // will be processed later on.
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        // If this is the only one pending we might
1463                        // have to bind to the service again.
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            params.serviceError();
1467                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1468                                    System.identityHashCode(mHandler));
1469                            if (params.traceMethod != null) {
1470                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1471                                        params.traceCookie);
1472                            }
1473                            return;
1474                        } else {
1475                            // Once we bind to the service, the first
1476                            // pending request will be processed.
1477                            mPendingInstalls.add(idx, params);
1478                        }
1479                    } else {
1480                        mPendingInstalls.add(idx, params);
1481                        // Already bound to the service. Just make
1482                        // sure we trigger off processing the first request.
1483                        if (idx == 0) {
1484                            mHandler.sendEmptyMessage(MCS_BOUND);
1485                        }
1486                    }
1487                    break;
1488                }
1489                case MCS_BOUND: {
1490                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1491                    if (msg.obj != null) {
1492                        mContainerService = (IMediaContainerService) msg.obj;
1493                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1494                                System.identityHashCode(mHandler));
1495                    }
1496                    if (mContainerService == null) {
1497                        if (!mBound) {
1498                            // Something seriously wrong since we are not bound and we are not
1499                            // waiting for connection. Bail out.
1500                            Slog.e(TAG, "Cannot bind to media container service");
1501                            for (HandlerParams params : mPendingInstalls) {
1502                                // Indicate service bind error
1503                                params.serviceError();
1504                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1505                                        System.identityHashCode(params));
1506                                if (params.traceMethod != null) {
1507                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1508                                            params.traceMethod, params.traceCookie);
1509                                }
1510                                return;
1511                            }
1512                            mPendingInstalls.clear();
1513                        } else {
1514                            Slog.w(TAG, "Waiting to connect to media container service");
1515                        }
1516                    } else if (mPendingInstalls.size() > 0) {
1517                        HandlerParams params = mPendingInstalls.get(0);
1518                        if (params != null) {
1519                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                    System.identityHashCode(params));
1521                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1522                            if (params.startCopy()) {
1523                                // We are done...  look for more work or to
1524                                // go idle.
1525                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                        "Checking for more work or unbind...");
1527                                // Delete pending install
1528                                if (mPendingInstalls.size() > 0) {
1529                                    mPendingInstalls.remove(0);
1530                                }
1531                                if (mPendingInstalls.size() == 0) {
1532                                    if (mBound) {
1533                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                                "Posting delayed MCS_UNBIND");
1535                                        removeMessages(MCS_UNBIND);
1536                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1537                                        // Unbind after a little delay, to avoid
1538                                        // continual thrashing.
1539                                        sendMessageDelayed(ubmsg, 10000);
1540                                    }
1541                                } else {
1542                                    // There are more pending requests in queue.
1543                                    // Just post MCS_BOUND message to trigger processing
1544                                    // of next pending install.
1545                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1546                                            "Posting MCS_BOUND for next work");
1547                                    mHandler.sendEmptyMessage(MCS_BOUND);
1548                                }
1549                            }
1550                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1551                        }
1552                    } else {
1553                        // Should never happen ideally.
1554                        Slog.w(TAG, "Empty queue");
1555                    }
1556                    break;
1557                }
1558                case MCS_RECONNECT: {
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1560                    if (mPendingInstalls.size() > 0) {
1561                        if (mBound) {
1562                            disconnectService();
1563                        }
1564                        if (!connectToService()) {
1565                            Slog.e(TAG, "Failed to bind to media container service");
1566                            for (HandlerParams params : mPendingInstalls) {
1567                                // Indicate service bind error
1568                                params.serviceError();
1569                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1570                                        System.identityHashCode(params));
1571                            }
1572                            mPendingInstalls.clear();
1573                        }
1574                    }
1575                    break;
1576                }
1577                case MCS_UNBIND: {
1578                    // If there is no actual work left, then time to unbind.
1579                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1580
1581                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1582                        if (mBound) {
1583                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1584
1585                            disconnectService();
1586                        }
1587                    } else if (mPendingInstalls.size() > 0) {
1588                        // There are more pending requests in queue.
1589                        // Just post MCS_BOUND message to trigger processing
1590                        // of next pending install.
1591                        mHandler.sendEmptyMessage(MCS_BOUND);
1592                    }
1593
1594                    break;
1595                }
1596                case MCS_GIVE_UP: {
1597                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1598                    HandlerParams params = mPendingInstalls.remove(0);
1599                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1600                            System.identityHashCode(params));
1601                    break;
1602                }
1603                case SEND_PENDING_BROADCAST: {
1604                    String packages[];
1605                    ArrayList<String> components[];
1606                    int size = 0;
1607                    int uids[];
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        if (mPendingBroadcasts == null) {
1611                            return;
1612                        }
1613                        size = mPendingBroadcasts.size();
1614                        if (size <= 0) {
1615                            // Nothing to be done. Just return
1616                            return;
1617                        }
1618                        packages = new String[size];
1619                        components = new ArrayList[size];
1620                        uids = new int[size];
1621                        int i = 0;  // filling out the above arrays
1622
1623                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1624                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1625                            Iterator<Map.Entry<String, ArrayList<String>>> it
1626                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1627                                            .entrySet().iterator();
1628                            while (it.hasNext() && i < size) {
1629                                Map.Entry<String, ArrayList<String>> ent = it.next();
1630                                packages[i] = ent.getKey();
1631                                components[i] = ent.getValue();
1632                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1633                                uids[i] = (ps != null)
1634                                        ? UserHandle.getUid(packageUserId, ps.appId)
1635                                        : -1;
1636                                i++;
1637                            }
1638                        }
1639                        size = i;
1640                        mPendingBroadcasts.clear();
1641                    }
1642                    // Send broadcasts
1643                    for (int i = 0; i < size; i++) {
1644                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    break;
1648                }
1649                case START_CLEANING_PACKAGE: {
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1651                    final String packageName = (String)msg.obj;
1652                    final int userId = msg.arg1;
1653                    final boolean andCode = msg.arg2 != 0;
1654                    synchronized (mPackages) {
1655                        if (userId == UserHandle.USER_ALL) {
1656                            int[] users = sUserManager.getUserIds();
1657                            for (int user : users) {
1658                                mSettings.addPackageToCleanLPw(
1659                                        new PackageCleanItem(user, packageName, andCode));
1660                            }
1661                        } else {
1662                            mSettings.addPackageToCleanLPw(
1663                                    new PackageCleanItem(userId, packageName, andCode));
1664                        }
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                    startCleaningPackages();
1668                } break;
1669                case POST_INSTALL: {
1670                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1671
1672                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1673                    final boolean didRestore = (msg.arg2 != 0);
1674                    mRunningInstalls.delete(msg.arg1);
1675
1676                    if (data != null) {
1677                        InstallArgs args = data.args;
1678                        PackageInstalledInfo parentRes = data.res;
1679
1680                        final boolean grantPermissions = (args.installFlags
1681                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1682                        final boolean killApp = (args.installFlags
1683                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1684                        final boolean virtualPreload = ((args.installFlags
1685                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1686                        final String[] grantedPermissions = args.installGrantPermissions;
1687
1688                        // Handle the parent package
1689                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1690                                virtualPreload, grantedPermissions, didRestore,
1691                                args.installerPackageName, args.observer);
1692
1693                        // Handle the child packages
1694                        final int childCount = (parentRes.addedChildPackages != null)
1695                                ? parentRes.addedChildPackages.size() : 0;
1696                        for (int i = 0; i < childCount; i++) {
1697                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1698                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1699                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1700                                    args.installerPackageName, args.observer);
1701                        }
1702
1703                        // Log tracing if needed
1704                        if (args.traceMethod != null) {
1705                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1706                                    args.traceCookie);
1707                        }
1708                    } else {
1709                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1710                    }
1711
1712                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1713                } break;
1714                case UPDATED_MEDIA_STATUS: {
1715                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1716                    boolean reportStatus = msg.arg1 == 1;
1717                    boolean doGc = msg.arg2 == 1;
1718                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1719                    if (doGc) {
1720                        // Force a gc to clear up stale containers.
1721                        Runtime.getRuntime().gc();
1722                    }
1723                    if (msg.obj != null) {
1724                        @SuppressWarnings("unchecked")
1725                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1726                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1727                        // Unload containers
1728                        unloadAllContainers(args);
1729                    }
1730                    if (reportStatus) {
1731                        try {
1732                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1733                                    "Invoking StorageManagerService call back");
1734                            PackageHelper.getStorageManager().finishMediaUpdate();
1735                        } catch (RemoteException e) {
1736                            Log.e(TAG, "StorageManagerService not running?");
1737                        }
1738                    }
1739                } break;
1740                case WRITE_SETTINGS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_SETTINGS);
1744                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1745                        mSettings.writeLPr();
1746                        mDirtyUsers.clear();
1747                    }
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1749                } break;
1750                case WRITE_PACKAGE_RESTRICTIONS: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1754                        for (int userId : mDirtyUsers) {
1755                            mSettings.writePackageRestrictionsLPr(userId);
1756                        }
1757                        mDirtyUsers.clear();
1758                    }
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1760                } break;
1761                case WRITE_PACKAGE_LIST: {
1762                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1763                    synchronized (mPackages) {
1764                        removeMessages(WRITE_PACKAGE_LIST);
1765                        mSettings.writePackageListLPr(msg.arg1);
1766                    }
1767                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1768                } break;
1769                case CHECK_PENDING_VERIFICATION: {
1770                    final int verificationId = msg.arg1;
1771                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1772
1773                    if ((state != null) && !state.timeoutExtended()) {
1774                        final InstallArgs args = state.getInstallArgs();
1775                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1776
1777                        Slog.i(TAG, "Verification timed out for " + originUri);
1778                        mPendingVerification.remove(verificationId);
1779
1780                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1781
1782                        final UserHandle user = args.getUser();
1783                        if (getDefaultVerificationResponse(user)
1784                                == PackageManager.VERIFICATION_ALLOW) {
1785                            Slog.i(TAG, "Continuing with installation of " + originUri);
1786                            state.setVerifierResponse(Binder.getCallingUid(),
1787                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1788                            broadcastPackageVerified(verificationId, originUri,
1789                                    PackageManager.VERIFICATION_ALLOW, user);
1790                            try {
1791                                ret = args.copyApk(mContainerService, true);
1792                            } catch (RemoteException e) {
1793                                Slog.e(TAG, "Could not contact the ContainerService");
1794                            }
1795                        } else {
1796                            broadcastPackageVerified(verificationId, originUri,
1797                                    PackageManager.VERIFICATION_REJECT, user);
1798                        }
1799
1800                        Trace.asyncTraceEnd(
1801                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1802
1803                        processPendingInstall(args, ret);
1804                        mHandler.sendEmptyMessage(MCS_UNBIND);
1805                    }
1806                    break;
1807                }
1808                case PACKAGE_VERIFIED: {
1809                    final int verificationId = msg.arg1;
1810
1811                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1812                    if (state == null) {
1813                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1814                        break;
1815                    }
1816
1817                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1818
1819                    state.setVerifierResponse(response.callerUid, response.code);
1820
1821                    if (state.isVerificationComplete()) {
1822                        mPendingVerification.remove(verificationId);
1823
1824                        final InstallArgs args = state.getInstallArgs();
1825                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1826
1827                        int ret;
1828                        if (state.isInstallAllowed()) {
1829                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1830                            broadcastPackageVerified(verificationId, originUri,
1831                                    response.code, state.getInstallArgs().getUser());
1832                            try {
1833                                ret = args.copyApk(mContainerService, true);
1834                            } catch (RemoteException e) {
1835                                Slog.e(TAG, "Could not contact the ContainerService");
1836                            }
1837                        } else {
1838                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1839                        }
1840
1841                        Trace.asyncTraceEnd(
1842                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1843
1844                        processPendingInstall(args, ret);
1845                        mHandler.sendEmptyMessage(MCS_UNBIND);
1846                    }
1847
1848                    break;
1849                }
1850                case START_INTENT_FILTER_VERIFICATIONS: {
1851                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1852                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1853                            params.replacing, params.pkg);
1854                    break;
1855                }
1856                case INTENT_FILTER_VERIFIED: {
1857                    final int verificationId = msg.arg1;
1858
1859                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1860                            verificationId);
1861                    if (state == null) {
1862                        Slog.w(TAG, "Invalid IntentFilter verification token "
1863                                + verificationId + " received");
1864                        break;
1865                    }
1866
1867                    final int userId = state.getUserId();
1868
1869                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1870                            "Processing IntentFilter verification with token:"
1871                            + verificationId + " and userId:" + userId);
1872
1873                    final IntentFilterVerificationResponse response =
1874                            (IntentFilterVerificationResponse) msg.obj;
1875
1876                    state.setVerifierResponse(response.callerUid, response.code);
1877
1878                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1879                            "IntentFilter verification with token:" + verificationId
1880                            + " and userId:" + userId
1881                            + " is settings verifier response with response code:"
1882                            + response.code);
1883
1884                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1885                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1886                                + response.getFailedDomainsString());
1887                    }
1888
1889                    if (state.isVerificationComplete()) {
1890                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1891                    } else {
1892                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1893                                "IntentFilter verification with token:" + verificationId
1894                                + " was not said to be complete");
1895                    }
1896
1897                    break;
1898                }
1899                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1900                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1901                            mInstantAppResolverConnection,
1902                            (InstantAppRequest) msg.obj,
1903                            mInstantAppInstallerActivity,
1904                            mHandler);
1905                }
1906            }
1907        }
1908    }
1909
1910    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1911            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1912            boolean launchedForRestore, String installerPackage,
1913            IPackageInstallObserver2 installObserver) {
1914        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1915            // Send the removed broadcasts
1916            if (res.removedInfo != null) {
1917                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1918            }
1919
1920            // Now that we successfully installed the package, grant runtime
1921            // permissions if requested before broadcasting the install. Also
1922            // for legacy apps in permission review mode we clear the permission
1923            // review flag which is used to emulate runtime permissions for
1924            // legacy apps.
1925            if (grantPermissions) {
1926                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1927            }
1928
1929            final boolean update = res.removedInfo != null
1930                    && res.removedInfo.removedPackage != null;
1931            final String origInstallerPackageName = res.removedInfo != null
1932                    ? res.removedInfo.installerPackageName : null;
1933
1934            // If this is the first time we have child packages for a disabled privileged
1935            // app that had no children, we grant requested runtime permissions to the new
1936            // children if the parent on the system image had them already granted.
1937            if (res.pkg.parentPackage != null) {
1938                synchronized (mPackages) {
1939                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1940                }
1941            }
1942
1943            synchronized (mPackages) {
1944                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1945            }
1946
1947            final String packageName = res.pkg.applicationInfo.packageName;
1948
1949            // Determine the set of users who are adding this package for
1950            // the first time vs. those who are seeing an update.
1951            int[] firstUsers = EMPTY_INT_ARRAY;
1952            int[] updateUsers = EMPTY_INT_ARRAY;
1953            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1954            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1955            for (int newUser : res.newUsers) {
1956                if (ps.getInstantApp(newUser)) {
1957                    continue;
1958                }
1959                if (allNewUsers) {
1960                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1961                    continue;
1962                }
1963                boolean isNew = true;
1964                for (int origUser : res.origUsers) {
1965                    if (origUser == newUser) {
1966                        isNew = false;
1967                        break;
1968                    }
1969                }
1970                if (isNew) {
1971                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1972                } else {
1973                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1974                }
1975            }
1976
1977            // Send installed broadcasts if the package is not a static shared lib.
1978            if (res.pkg.staticSharedLibName == null) {
1979                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1980
1981                // Send added for users that see the package for the first time
1982                // sendPackageAddedForNewUsers also deals with system apps
1983                int appId = UserHandle.getAppId(res.uid);
1984                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1985                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1986                        virtualPreload /*startReceiver*/, appId, firstUsers);
1987
1988                // Send added for users that don't see the package for the first time
1989                Bundle extras = new Bundle(1);
1990                extras.putInt(Intent.EXTRA_UID, res.uid);
1991                if (update) {
1992                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1993                }
1994                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1995                        extras, 0 /*flags*/,
1996                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1997                if (origInstallerPackageName != null) {
1998                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1999                            extras, 0 /*flags*/,
2000                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2001                }
2002
2003                // Send replaced for users that don't see the package for the first time
2004                if (update) {
2005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2006                            packageName, extras, 0 /*flags*/,
2007                            null /*targetPackage*/, null /*finishedReceiver*/,
2008                            updateUsers);
2009                    if (origInstallerPackageName != null) {
2010                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2011                                extras, 0 /*flags*/,
2012                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2013                    }
2014                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2015                            null /*package*/, null /*extras*/, 0 /*flags*/,
2016                            packageName /*targetPackage*/,
2017                            null /*finishedReceiver*/, updateUsers);
2018                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2019                    // First-install and we did a restore, so we're responsible for the
2020                    // first-launch broadcast.
2021                    if (DEBUG_BACKUP) {
2022                        Slog.i(TAG, "Post-restore of " + packageName
2023                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2024                    }
2025                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2026                }
2027
2028                // Send broadcast package appeared if forward locked/external for all users
2029                // treat asec-hosted packages like removable media on upgrade
2030                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2031                    if (DEBUG_INSTALL) {
2032                        Slog.i(TAG, "upgrading pkg " + res.pkg
2033                                + " is ASEC-hosted -> AVAILABLE");
2034                    }
2035                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2036                    ArrayList<String> pkgList = new ArrayList<>(1);
2037                    pkgList.add(packageName);
2038                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2039                }
2040            }
2041
2042            // Work that needs to happen on first install within each user
2043            if (firstUsers != null && firstUsers.length > 0) {
2044                synchronized (mPackages) {
2045                    for (int userId : firstUsers) {
2046                        // If this app is a browser and it's newly-installed for some
2047                        // users, clear any default-browser state in those users. The
2048                        // app's nature doesn't depend on the user, so we can just check
2049                        // its browser nature in any user and generalize.
2050                        if (packageIsBrowser(packageName, userId)) {
2051                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2052                        }
2053
2054                        // We may also need to apply pending (restored) runtime
2055                        // permission grants within these users.
2056                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2057                    }
2058                }
2059            }
2060
2061            // Log current value of "unknown sources" setting
2062            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2063                    getUnknownSourcesSettings());
2064
2065            // Remove the replaced package's older resources safely now
2066            // We delete after a gc for applications  on sdcard.
2067            if (res.removedInfo != null && res.removedInfo.args != null) {
2068                Runtime.getRuntime().gc();
2069                synchronized (mInstallLock) {
2070                    res.removedInfo.args.doPostDeleteLI(true);
2071                }
2072            } else {
2073                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2074                // and not block here.
2075                VMRuntime.getRuntime().requestConcurrentGC();
2076            }
2077
2078            // Notify DexManager that the package was installed for new users.
2079            // The updated users should already be indexed and the package code paths
2080            // should not change.
2081            // Don't notify the manager for ephemeral apps as they are not expected to
2082            // survive long enough to benefit of background optimizations.
2083            for (int userId : firstUsers) {
2084                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2085                // There's a race currently where some install events may interleave with an uninstall.
2086                // This can lead to package info being null (b/36642664).
2087                if (info != null) {
2088                    mDexManager.notifyPackageInstalled(info, userId);
2089                }
2090            }
2091        }
2092
2093        // If someone is watching installs - notify them
2094        if (installObserver != null) {
2095            try {
2096                Bundle extras = extrasForInstallResult(res);
2097                installObserver.onPackageInstalled(res.name, res.returnCode,
2098                        res.returnMsg, extras);
2099            } catch (RemoteException e) {
2100                Slog.i(TAG, "Observer no longer exists.");
2101            }
2102        }
2103    }
2104
2105    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2106            PackageParser.Package pkg) {
2107        if (pkg.parentPackage == null) {
2108            return;
2109        }
2110        if (pkg.requestedPermissions == null) {
2111            return;
2112        }
2113        final PackageSetting disabledSysParentPs = mSettings
2114                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2115        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2116                || !disabledSysParentPs.isPrivileged()
2117                || (disabledSysParentPs.childPackageNames != null
2118                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2119            return;
2120        }
2121        final int[] allUserIds = sUserManager.getUserIds();
2122        final int permCount = pkg.requestedPermissions.size();
2123        for (int i = 0; i < permCount; i++) {
2124            String permission = pkg.requestedPermissions.get(i);
2125            BasePermission bp = mSettings.mPermissions.get(permission);
2126            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2127                continue;
2128            }
2129            for (int userId : allUserIds) {
2130                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2131                        permission, userId)) {
2132                    grantRuntimePermission(pkg.packageName, permission, userId);
2133                }
2134            }
2135        }
2136    }
2137
2138    private StorageEventListener mStorageListener = new StorageEventListener() {
2139        @Override
2140        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2141            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2142                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2143                    final String volumeUuid = vol.getFsUuid();
2144
2145                    // Clean up any users or apps that were removed or recreated
2146                    // while this volume was missing
2147                    sUserManager.reconcileUsers(volumeUuid);
2148                    reconcileApps(volumeUuid);
2149
2150                    // Clean up any install sessions that expired or were
2151                    // cancelled while this volume was missing
2152                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2153
2154                    loadPrivatePackages(vol);
2155
2156                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2157                    unloadPrivatePackages(vol);
2158                }
2159            }
2160
2161            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2162                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2163                    updateExternalMediaStatus(true, false);
2164                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2165                    updateExternalMediaStatus(false, false);
2166                }
2167            }
2168        }
2169
2170        @Override
2171        public void onVolumeForgotten(String fsUuid) {
2172            if (TextUtils.isEmpty(fsUuid)) {
2173                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2174                return;
2175            }
2176
2177            // Remove any apps installed on the forgotten volume
2178            synchronized (mPackages) {
2179                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2180                for (PackageSetting ps : packages) {
2181                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2182                    deletePackageVersioned(new VersionedPackage(ps.name,
2183                            PackageManager.VERSION_CODE_HIGHEST),
2184                            new LegacyPackageDeleteObserver(null).getBinder(),
2185                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2186                    // Try very hard to release any references to this package
2187                    // so we don't risk the system server being killed due to
2188                    // open FDs
2189                    AttributeCache.instance().removePackage(ps.name);
2190                }
2191
2192                mSettings.onVolumeForgotten(fsUuid);
2193                mSettings.writeLPr();
2194            }
2195        }
2196    };
2197
2198    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2199            String[] grantedPermissions) {
2200        for (int userId : userIds) {
2201            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2202        }
2203    }
2204
2205    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2206            String[] grantedPermissions) {
2207        PackageSetting ps = (PackageSetting) pkg.mExtras;
2208        if (ps == null) {
2209            return;
2210        }
2211
2212        PermissionsState permissionsState = ps.getPermissionsState();
2213
2214        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2215                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2216
2217        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2218                >= Build.VERSION_CODES.M;
2219
2220        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2221
2222        for (String permission : pkg.requestedPermissions) {
2223            final BasePermission bp;
2224            synchronized (mPackages) {
2225                bp = mSettings.mPermissions.get(permission);
2226            }
2227            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2228                    && (!instantApp || bp.isInstant())
2229                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2230                    && (grantedPermissions == null
2231                           || ArrayUtils.contains(grantedPermissions, permission))) {
2232                final int flags = permissionsState.getPermissionFlags(permission, userId);
2233                if (supportsRuntimePermissions) {
2234                    // Installer cannot change immutable permissions.
2235                    if ((flags & immutableFlags) == 0) {
2236                        grantRuntimePermission(pkg.packageName, permission, userId);
2237                    }
2238                } else if (mPermissionReviewRequired) {
2239                    // In permission review mode we clear the review flag when we
2240                    // are asked to install the app with all permissions granted.
2241                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2242                        updatePermissionFlags(permission, pkg.packageName,
2243                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2244                    }
2245                }
2246            }
2247        }
2248    }
2249
2250    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2251        Bundle extras = null;
2252        switch (res.returnCode) {
2253            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2254                extras = new Bundle();
2255                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2256                        res.origPermission);
2257                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2258                        res.origPackage);
2259                break;
2260            }
2261            case PackageManager.INSTALL_SUCCEEDED: {
2262                extras = new Bundle();
2263                extras.putBoolean(Intent.EXTRA_REPLACING,
2264                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2265                break;
2266            }
2267        }
2268        return extras;
2269    }
2270
2271    void scheduleWriteSettingsLocked() {
2272        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2273            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2274        }
2275    }
2276
2277    void scheduleWritePackageListLocked(int userId) {
2278        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2279            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2280            msg.arg1 = userId;
2281            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2282        }
2283    }
2284
2285    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2286        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2287        scheduleWritePackageRestrictionsLocked(userId);
2288    }
2289
2290    void scheduleWritePackageRestrictionsLocked(int userId) {
2291        final int[] userIds = (userId == UserHandle.USER_ALL)
2292                ? sUserManager.getUserIds() : new int[]{userId};
2293        for (int nextUserId : userIds) {
2294            if (!sUserManager.exists(nextUserId)) return;
2295            mDirtyUsers.add(nextUserId);
2296            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2297                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2298            }
2299        }
2300    }
2301
2302    public static PackageManagerService main(Context context, Installer installer,
2303            boolean factoryTest, boolean onlyCore) {
2304        // Self-check for initial settings.
2305        PackageManagerServiceCompilerMapping.checkProperties();
2306
2307        PackageManagerService m = new PackageManagerService(context, installer,
2308                factoryTest, onlyCore);
2309        m.enableSystemUserPackages();
2310        ServiceManager.addService("package", m);
2311        final PackageManagerNative pmn = m.new PackageManagerNative();
2312        ServiceManager.addService("package_native", pmn);
2313        return m;
2314    }
2315
2316    private void enableSystemUserPackages() {
2317        if (!UserManager.isSplitSystemUser()) {
2318            return;
2319        }
2320        // For system user, enable apps based on the following conditions:
2321        // - app is whitelisted or belong to one of these groups:
2322        //   -- system app which has no launcher icons
2323        //   -- system app which has INTERACT_ACROSS_USERS permission
2324        //   -- system IME app
2325        // - app is not in the blacklist
2326        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2327        Set<String> enableApps = new ArraySet<>();
2328        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2329                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2330                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2331        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2332        enableApps.addAll(wlApps);
2333        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2334                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2335        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2336        enableApps.removeAll(blApps);
2337        Log.i(TAG, "Applications installed for system user: " + enableApps);
2338        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2339                UserHandle.SYSTEM);
2340        final int allAppsSize = allAps.size();
2341        synchronized (mPackages) {
2342            for (int i = 0; i < allAppsSize; i++) {
2343                String pName = allAps.get(i);
2344                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2345                // Should not happen, but we shouldn't be failing if it does
2346                if (pkgSetting == null) {
2347                    continue;
2348                }
2349                boolean install = enableApps.contains(pName);
2350                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2351                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2352                            + " for system user");
2353                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2354                }
2355            }
2356            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2357        }
2358    }
2359
2360    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2361        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2362                Context.DISPLAY_SERVICE);
2363        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2364    }
2365
2366    /**
2367     * Requests that files preopted on a secondary system partition be copied to the data partition
2368     * if possible.  Note that the actual copying of the files is accomplished by init for security
2369     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2370     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2371     */
2372    private static void requestCopyPreoptedFiles() {
2373        final int WAIT_TIME_MS = 100;
2374        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2375        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2376            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2377            // We will wait for up to 100 seconds.
2378            final long timeStart = SystemClock.uptimeMillis();
2379            final long timeEnd = timeStart + 100 * 1000;
2380            long timeNow = timeStart;
2381            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2382                try {
2383                    Thread.sleep(WAIT_TIME_MS);
2384                } catch (InterruptedException e) {
2385                    // Do nothing
2386                }
2387                timeNow = SystemClock.uptimeMillis();
2388                if (timeNow > timeEnd) {
2389                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2390                    Slog.wtf(TAG, "cppreopt did not finish!");
2391                    break;
2392                }
2393            }
2394
2395            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2396        }
2397    }
2398
2399    public PackageManagerService(Context context, Installer installer,
2400            boolean factoryTest, boolean onlyCore) {
2401        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2402        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2403        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2404                SystemClock.uptimeMillis());
2405
2406        if (mSdkVersion <= 0) {
2407            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2408        }
2409
2410        mContext = context;
2411
2412        mPermissionReviewRequired = context.getResources().getBoolean(
2413                R.bool.config_permissionReviewRequired);
2414
2415        mFactoryTest = factoryTest;
2416        mOnlyCore = onlyCore;
2417        mMetrics = new DisplayMetrics();
2418        mSettings = new Settings(mPackages);
2419        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431
2432        String separateProcesses = SystemProperties.get("debug.separate_processes");
2433        if (separateProcesses != null && separateProcesses.length() > 0) {
2434            if ("*".equals(separateProcesses)) {
2435                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2436                mSeparateProcesses = null;
2437                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2438            } else {
2439                mDefParseFlags = 0;
2440                mSeparateProcesses = separateProcesses.split(",");
2441                Slog.w(TAG, "Running with debug.separate_processes: "
2442                        + separateProcesses);
2443            }
2444        } else {
2445            mDefParseFlags = 0;
2446            mSeparateProcesses = null;
2447        }
2448
2449        mInstaller = installer;
2450        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2451                "*dexopt*");
2452        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2453        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2454
2455        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2456                FgThread.get().getLooper());
2457
2458        getDefaultDisplayMetrics(context, mMetrics);
2459
2460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2461        SystemConfig systemConfig = SystemConfig.getInstance();
2462        mGlobalGids = systemConfig.getGlobalGids();
2463        mSystemPermissions = systemConfig.getSystemPermissions();
2464        mAvailableFeatures = systemConfig.getAvailableFeatures();
2465        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2466
2467        mProtectedPackages = new ProtectedPackages(mContext);
2468
2469        synchronized (mInstallLock) {
2470        // writer
2471        synchronized (mPackages) {
2472            mHandlerThread = new ServiceThread(TAG,
2473                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2474            mHandlerThread.start();
2475            mHandler = new PackageHandler(mHandlerThread.getLooper());
2476            mProcessLoggingHandler = new ProcessLoggingHandler();
2477            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2478
2479            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2480            mInstantAppRegistry = new InstantAppRegistry(this);
2481
2482            File dataDir = Environment.getDataDirectory();
2483            mAppInstallDir = new File(dataDir, "app");
2484            mAppLib32InstallDir = new File(dataDir, "app-lib");
2485            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2486            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2487            sUserManager = new UserManagerService(context, this,
2488                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2489
2490            // Propagate permission configuration in to package manager.
2491            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2492                    = systemConfig.getPermissions();
2493            for (int i=0; i<permConfig.size(); i++) {
2494                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2495                BasePermission bp = mSettings.mPermissions.get(perm.name);
2496                if (bp == null) {
2497                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2498                    mSettings.mPermissions.put(perm.name, bp);
2499                }
2500                if (perm.gids != null) {
2501                    bp.setGids(perm.gids, perm.perUser);
2502                }
2503            }
2504
2505            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2506            final int builtInLibCount = libConfig.size();
2507            for (int i = 0; i < builtInLibCount; i++) {
2508                String name = libConfig.keyAt(i);
2509                String path = libConfig.valueAt(i);
2510                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2511                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2512            }
2513
2514            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2515
2516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2517            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2519
2520            // Clean up orphaned packages for which the code path doesn't exist
2521            // and they are an update to a system app - caused by bug/32321269
2522            final int packageSettingCount = mSettings.mPackages.size();
2523            for (int i = packageSettingCount - 1; i >= 0; i--) {
2524                PackageSetting ps = mSettings.mPackages.valueAt(i);
2525                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2526                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2527                    mSettings.mPackages.removeAt(i);
2528                    mSettings.enableSystemPackageLPw(ps.name);
2529                }
2530            }
2531
2532            if (mFirstBoot) {
2533                requestCopyPreoptedFiles();
2534            }
2535
2536            String customResolverActivity = Resources.getSystem().getString(
2537                    R.string.config_customResolverActivity);
2538            if (TextUtils.isEmpty(customResolverActivity)) {
2539                customResolverActivity = null;
2540            } else {
2541                mCustomResolverComponentName = ComponentName.unflattenFromString(
2542                        customResolverActivity);
2543            }
2544
2545            long startTime = SystemClock.uptimeMillis();
2546
2547            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2548                    startTime);
2549
2550            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2551            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2552
2553            if (bootClassPath == null) {
2554                Slog.w(TAG, "No BOOTCLASSPATH found!");
2555            }
2556
2557            if (systemServerClassPath == null) {
2558                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2559            }
2560
2561            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2562
2563            final VersionInfo ver = mSettings.getInternalVersion();
2564            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2565            if (mIsUpgrade) {
2566                logCriticalInfo(Log.INFO,
2567                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2568            }
2569
2570            // when upgrading from pre-M, promote system app permissions from install to runtime
2571            mPromoteSystemApps =
2572                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2573
2574            // When upgrading from pre-N, we need to handle package extraction like first boot,
2575            // as there is no profiling data available.
2576            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2577
2578            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2579
2580            // save off the names of pre-existing system packages prior to scanning; we don't
2581            // want to automatically grant runtime permissions for new system apps
2582            if (mPromoteSystemApps) {
2583                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2584                while (pkgSettingIter.hasNext()) {
2585                    PackageSetting ps = pkgSettingIter.next();
2586                    if (isSystemApp(ps)) {
2587                        mExistingSystemPackages.add(ps.name);
2588                    }
2589                }
2590            }
2591
2592            mCacheDir = preparePackageParserCache(mIsUpgrade);
2593
2594            // Set flag to monitor and not change apk file paths when
2595            // scanning install directories.
2596            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2597
2598            if (mIsUpgrade || mFirstBoot) {
2599                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2600            }
2601
2602            // Collect vendor overlay packages. (Do this before scanning any apps.)
2603            // For security and version matching reason, only consider
2604            // overlay packages if they reside in the right directory.
2605            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2609
2610            mParallelPackageParserCallback.findStaticOverlayPackages();
2611
2612            // Find base frameworks (resource packages without code).
2613            scanDirTracedLI(frameworkDir, mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                    | PackageParser.PARSE_IS_PRIVILEGED,
2617                    scanFlags | SCAN_NO_DEX, 0);
2618
2619            // Collected privileged system packages.
2620            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2621            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR
2624                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2625
2626            // Collect ordinary system packages.
2627            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2628            scanDirTracedLI(systemAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2631
2632            // Collect all vendor packages.
2633            File vendorAppDir = new File("/vendor/app");
2634            try {
2635                vendorAppDir = vendorAppDir.getCanonicalFile();
2636            } catch (IOException e) {
2637                // failed to look up canonical path, continue with original one
2638            }
2639            scanDirTracedLI(vendorAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Collect all OEM packages.
2644            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2645            scanDirTracedLI(oemAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Prune any system packages that no longer exist.
2650            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2651            // Stub packages must either be replaced with full versions in the /data
2652            // partition or be disabled.
2653            final List<String> stubSystemApps = new ArrayList<>();
2654            if (!mOnlyCore) {
2655                // do this first before mucking with mPackages for the "expecting better" case
2656                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2657                while (pkgIterator.hasNext()) {
2658                    final PackageParser.Package pkg = pkgIterator.next();
2659                    if (pkg.isStub) {
2660                        stubSystemApps.add(pkg.packageName);
2661                    }
2662                }
2663
2664                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2665                while (psit.hasNext()) {
2666                    PackageSetting ps = psit.next();
2667
2668                    /*
2669                     * If this is not a system app, it can't be a
2670                     * disable system app.
2671                     */
2672                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2673                        continue;
2674                    }
2675
2676                    /*
2677                     * If the package is scanned, it's not erased.
2678                     */
2679                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2680                    if (scannedPkg != null) {
2681                        /*
2682                         * If the system app is both scanned and in the
2683                         * disabled packages list, then it must have been
2684                         * added via OTA. Remove it from the currently
2685                         * scanned package so the previously user-installed
2686                         * application can be scanned.
2687                         */
2688                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2689                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2690                                    + ps.name + "; removing system app.  Last known codePath="
2691                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2692                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2693                                    + scannedPkg.mVersionCode);
2694                            removePackageLI(scannedPkg, true);
2695                            mExpectingBetter.put(ps.name, ps.codePath);
2696                        }
2697
2698                        continue;
2699                    }
2700
2701                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2702                        psit.remove();
2703                        logCriticalInfo(Log.WARN, "System package " + ps.name
2704                                + " no longer exists; it's data will be wiped");
2705                        // Actual deletion of code and data will be handled by later
2706                        // reconciliation step
2707                    } else {
2708                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2709                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2710                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2711                        }
2712                    }
2713                }
2714            }
2715
2716            //look for any incomplete package installations
2717            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2718            for (int i = 0; i < deletePkgsList.size(); i++) {
2719                // Actual deletion of code and data will be handled by later
2720                // reconciliation step
2721                final String packageName = deletePkgsList.get(i).name;
2722                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2723                synchronized (mPackages) {
2724                    mSettings.removePackageLPw(packageName);
2725                }
2726            }
2727
2728            //delete tmp files
2729            deleteTempPackageFiles();
2730
2731            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2732
2733            // Remove any shared userIDs that have no associated packages
2734            mSettings.pruneSharedUsersLPw();
2735            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2736            final int systemPackagesCount = mPackages.size();
2737            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2738                    + " ms, packageCount: " + systemPackagesCount
2739                    + " , timePerPackage: "
2740                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2741                    + " , cached: " + cachedSystemApps);
2742            if (mIsUpgrade && systemPackagesCount > 0) {
2743                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2744                        ((int) systemScanTime) / systemPackagesCount);
2745            }
2746            if (!mOnlyCore) {
2747                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2748                        SystemClock.uptimeMillis());
2749                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2750
2751                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2752                        | PackageParser.PARSE_FORWARD_LOCK,
2753                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2754
2755                // Remove disable package settings for updated system apps that were
2756                // removed via an OTA. If the update is no longer present, remove the
2757                // app completely. Otherwise, revoke their system privileges.
2758                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2759                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2760                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2761
2762                    final String msg;
2763                    if (deletedPkg == null) {
2764                        // should have found an update, but, we didn't; remove everything
2765                        msg = "Updated system package " + deletedAppName
2766                                + " no longer exists; removing its data";
2767                        // Actual deletion of code and data will be handled by later
2768                        // reconciliation step
2769                    } else {
2770                        // found an update; revoke system privileges
2771                        msg = "Updated system package + " + deletedAppName
2772                                + " no longer exists; revoking system privileges";
2773
2774                        // Don't do anything if a stub is removed from the system image. If
2775                        // we were to remove the uncompressed version from the /data partition,
2776                        // this is where it'd be done.
2777
2778                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2779                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2780                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2781                    }
2782                    logCriticalInfo(Log.WARN, msg);
2783                }
2784
2785                /*
2786                 * Make sure all system apps that we expected to appear on
2787                 * the userdata partition actually showed up. If they never
2788                 * appeared, crawl back and revive the system version.
2789                 */
2790                for (int i = 0; i < mExpectingBetter.size(); i++) {
2791                    final String packageName = mExpectingBetter.keyAt(i);
2792                    if (!mPackages.containsKey(packageName)) {
2793                        final File scanFile = mExpectingBetter.valueAt(i);
2794
2795                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2796                                + " but never showed up; reverting to system");
2797
2798                        int reparseFlags = mDefParseFlags;
2799                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2800                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2801                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2802                                    | PackageParser.PARSE_IS_PRIVILEGED;
2803                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2804                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2805                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2806                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2807                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2808                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2809                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2810                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2811                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2812                        } else {
2813                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2814                            continue;
2815                        }
2816
2817                        mSettings.enableSystemPackageLPw(packageName);
2818
2819                        try {
2820                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2821                        } catch (PackageManagerException e) {
2822                            Slog.e(TAG, "Failed to parse original system package: "
2823                                    + e.getMessage());
2824                        }
2825                    }
2826                }
2827
2828                // Uncompress and install any stubbed system applications.
2829                // This must be done last to ensure all stubs are replaced or disabled.
2830                decompressSystemApplications(stubSystemApps, scanFlags);
2831
2832                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2833                                - cachedSystemApps;
2834
2835                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2836                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2837                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2838                        + " ms, packageCount: " + dataPackagesCount
2839                        + " , timePerPackage: "
2840                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2841                        + " , cached: " + cachedNonSystemApps);
2842                if (mIsUpgrade && dataPackagesCount > 0) {
2843                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2844                            ((int) dataScanTime) / dataPackagesCount);
2845                }
2846            }
2847            mExpectingBetter.clear();
2848
2849            // Resolve the storage manager.
2850            mStorageManagerPackage = getStorageManagerPackageName();
2851
2852            // Resolve protected action filters. Only the setup wizard is allowed to
2853            // have a high priority filter for these actions.
2854            mSetupWizardPackage = getSetupWizardPackageName();
2855            if (mProtectedFilters.size() > 0) {
2856                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2857                    Slog.i(TAG, "No setup wizard;"
2858                        + " All protected intents capped to priority 0");
2859                }
2860                for (ActivityIntentInfo filter : mProtectedFilters) {
2861                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2862                        if (DEBUG_FILTERS) {
2863                            Slog.i(TAG, "Found setup wizard;"
2864                                + " allow priority " + filter.getPriority() + ";"
2865                                + " package: " + filter.activity.info.packageName
2866                                + " activity: " + filter.activity.className
2867                                + " priority: " + filter.getPriority());
2868                        }
2869                        // skip setup wizard; allow it to keep the high priority filter
2870                        continue;
2871                    }
2872                    if (DEBUG_FILTERS) {
2873                        Slog.i(TAG, "Protected action; cap priority to 0;"
2874                                + " package: " + filter.activity.info.packageName
2875                                + " activity: " + filter.activity.className
2876                                + " origPrio: " + filter.getPriority());
2877                    }
2878                    filter.setPriority(0);
2879                }
2880            }
2881            mDeferProtectedFilters = false;
2882            mProtectedFilters.clear();
2883
2884            // Now that we know all of the shared libraries, update all clients to have
2885            // the correct library paths.
2886            updateAllSharedLibrariesLPw(null);
2887
2888            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2889                // NOTE: We ignore potential failures here during a system scan (like
2890                // the rest of the commands above) because there's precious little we
2891                // can do about it. A settings error is reported, though.
2892                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2893            }
2894
2895            // Now that we know all the packages we are keeping,
2896            // read and update their last usage times.
2897            mPackageUsage.read(mPackages);
2898            mCompilerStats.read();
2899
2900            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2901                    SystemClock.uptimeMillis());
2902            Slog.i(TAG, "Time to scan packages: "
2903                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2904                    + " seconds");
2905
2906            // If the platform SDK has changed since the last time we booted,
2907            // we need to re-grant app permission to catch any new ones that
2908            // appear.  This is really a hack, and means that apps can in some
2909            // cases get permissions that the user didn't initially explicitly
2910            // allow...  it would be nice to have some better way to handle
2911            // this situation.
2912            int updateFlags = UPDATE_PERMISSIONS_ALL;
2913            if (ver.sdkVersion != mSdkVersion) {
2914                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2915                        + mSdkVersion + "; regranting permissions for internal storage");
2916                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2917            }
2918            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2919            ver.sdkVersion = mSdkVersion;
2920
2921            // If this is the first boot or an update from pre-M, and it is a normal
2922            // boot, then we need to initialize the default preferred apps across
2923            // all defined users.
2924            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2925                for (UserInfo user : sUserManager.getUsers(true)) {
2926                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2927                    applyFactoryDefaultBrowserLPw(user.id);
2928                    primeDomainVerificationsLPw(user.id);
2929                }
2930            }
2931
2932            // Prepare storage for system user really early during boot,
2933            // since core system apps like SettingsProvider and SystemUI
2934            // can't wait for user to start
2935            final int storageFlags;
2936            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2937                storageFlags = StorageManager.FLAG_STORAGE_DE;
2938            } else {
2939                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2940            }
2941            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2942                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2943                    true /* onlyCoreApps */);
2944            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2945                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2946                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2947                traceLog.traceBegin("AppDataFixup");
2948                try {
2949                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2950                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2951                } catch (InstallerException e) {
2952                    Slog.w(TAG, "Trouble fixing GIDs", e);
2953                }
2954                traceLog.traceEnd();
2955
2956                traceLog.traceBegin("AppDataPrepare");
2957                if (deferPackages == null || deferPackages.isEmpty()) {
2958                    return;
2959                }
2960                int count = 0;
2961                for (String pkgName : deferPackages) {
2962                    PackageParser.Package pkg = null;
2963                    synchronized (mPackages) {
2964                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2965                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2966                            pkg = ps.pkg;
2967                        }
2968                    }
2969                    if (pkg != null) {
2970                        synchronized (mInstallLock) {
2971                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2972                                    true /* maybeMigrateAppData */);
2973                        }
2974                        count++;
2975                    }
2976                }
2977                traceLog.traceEnd();
2978                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2979            }, "prepareAppData");
2980
2981            // If this is first boot after an OTA, and a normal boot, then
2982            // we need to clear code cache directories.
2983            // Note that we do *not* clear the application profiles. These remain valid
2984            // across OTAs and are used to drive profile verification (post OTA) and
2985            // profile compilation (without waiting to collect a fresh set of profiles).
2986            if (mIsUpgrade && !onlyCore) {
2987                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2988                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2989                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2990                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2991                        // No apps are running this early, so no need to freeze
2992                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2993                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2994                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2995                    }
2996                }
2997                ver.fingerprint = Build.FINGERPRINT;
2998            }
2999
3000            checkDefaultBrowser();
3001
3002            // clear only after permissions and other defaults have been updated
3003            mExistingSystemPackages.clear();
3004            mPromoteSystemApps = false;
3005
3006            // All the changes are done during package scanning.
3007            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3008
3009            // can downgrade to reader
3010            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3011            mSettings.writeLPr();
3012            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3013            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3014                    SystemClock.uptimeMillis());
3015
3016            if (!mOnlyCore) {
3017                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3018                mRequiredInstallerPackage = getRequiredInstallerLPr();
3019                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3020                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3021                if (mIntentFilterVerifierComponent != null) {
3022                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3023                            mIntentFilterVerifierComponent);
3024                } else {
3025                    mIntentFilterVerifier = null;
3026                }
3027                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3028                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3029                        SharedLibraryInfo.VERSION_UNDEFINED);
3030                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3031                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3032                        SharedLibraryInfo.VERSION_UNDEFINED);
3033            } else {
3034                mRequiredVerifierPackage = null;
3035                mRequiredInstallerPackage = null;
3036                mRequiredUninstallerPackage = null;
3037                mIntentFilterVerifierComponent = null;
3038                mIntentFilterVerifier = null;
3039                mServicesSystemSharedLibraryPackageName = null;
3040                mSharedSystemSharedLibraryPackageName = null;
3041            }
3042
3043            mInstallerService = new PackageInstallerService(context, this);
3044            final Pair<ComponentName, String> instantAppResolverComponent =
3045                    getInstantAppResolverLPr();
3046            if (instantAppResolverComponent != null) {
3047                if (DEBUG_EPHEMERAL) {
3048                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3049                }
3050                mInstantAppResolverConnection = new EphemeralResolverConnection(
3051                        mContext, instantAppResolverComponent.first,
3052                        instantAppResolverComponent.second);
3053                mInstantAppResolverSettingsComponent =
3054                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3055            } else {
3056                mInstantAppResolverConnection = null;
3057                mInstantAppResolverSettingsComponent = null;
3058            }
3059            updateInstantAppInstallerLocked(null);
3060
3061            // Read and update the usage of dex files.
3062            // Do this at the end of PM init so that all the packages have their
3063            // data directory reconciled.
3064            // At this point we know the code paths of the packages, so we can validate
3065            // the disk file and build the internal cache.
3066            // The usage file is expected to be small so loading and verifying it
3067            // should take a fairly small time compare to the other activities (e.g. package
3068            // scanning).
3069            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3070            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3071            for (int userId : currentUserIds) {
3072                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3073            }
3074            mDexManager.load(userPackages);
3075            if (mIsUpgrade) {
3076                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3077                        (int) (SystemClock.uptimeMillis() - startTime));
3078            }
3079        } // synchronized (mPackages)
3080        } // synchronized (mInstallLock)
3081
3082        // Now after opening every single application zip, make sure they
3083        // are all flushed.  Not really needed, but keeps things nice and
3084        // tidy.
3085        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3086        Runtime.getRuntime().gc();
3087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3088
3089        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3090        FallbackCategoryProvider.loadFallbacks();
3091        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3092
3093        // The initial scanning above does many calls into installd while
3094        // holding the mPackages lock, but we're mostly interested in yelling
3095        // once we have a booted system.
3096        mInstaller.setWarnIfHeld(mPackages);
3097
3098        // Expose private service for system components to use.
3099        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3101    }
3102
3103    /**
3104     * Uncompress and install stub applications.
3105     * <p>In order to save space on the system partition, some applications are shipped in a
3106     * compressed form. In addition the compressed bits for the full application, the
3107     * system image contains a tiny stub comprised of only the Android manifest.
3108     * <p>During the first boot, attempt to uncompress and install the full application. If
3109     * the application can't be installed for any reason, disable the stub and prevent
3110     * uncompressing the full application during future boots.
3111     * <p>In order to forcefully attempt an installation of a full application, go to app
3112     * settings and enable the application.
3113     */
3114    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3115        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3116            final String pkgName = stubSystemApps.get(i);
3117            // skip if the system package is already disabled
3118            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3119                stubSystemApps.remove(i);
3120                continue;
3121            }
3122            // skip if the package isn't installed (?!); this should never happen
3123            final PackageParser.Package pkg = mPackages.get(pkgName);
3124            if (pkg == null) {
3125                stubSystemApps.remove(i);
3126                continue;
3127            }
3128            // skip if the package has been disabled by the user
3129            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3130            if (ps != null) {
3131                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3132                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3133                    stubSystemApps.remove(i);
3134                    continue;
3135                }
3136            }
3137
3138            if (DEBUG_COMPRESSION) {
3139                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3140            }
3141
3142            // uncompress the binary to its eventual destination on /data
3143            final File scanFile = decompressPackage(pkg);
3144            if (scanFile == null) {
3145                continue;
3146            }
3147
3148            // install the package to replace the stub on /system
3149            try {
3150                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3151                removePackageLI(pkg, true /*chatty*/);
3152                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3153                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3154                        UserHandle.USER_SYSTEM, "android");
3155                stubSystemApps.remove(i);
3156                continue;
3157            } catch (PackageManagerException e) {
3158                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3159            }
3160
3161            // any failed attempt to install the package will be cleaned up later
3162        }
3163
3164        // disable any stub still left; these failed to install the full application
3165        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3166            final String pkgName = stubSystemApps.get(i);
3167            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3168            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3169                    UserHandle.USER_SYSTEM, "android");
3170            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3171        }
3172    }
3173
3174    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3175        if (DEBUG_COMPRESSION) {
3176            Slog.i(TAG, "Decompress file"
3177                    + "; src: " + srcFile.getAbsolutePath()
3178                    + ", dst: " + dstFile.getAbsolutePath());
3179        }
3180        try (
3181                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3182                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3183        ) {
3184            Streams.copy(fileIn, fileOut);
3185            Os.chmod(dstFile.getAbsolutePath(), 0644);
3186            return PackageManager.INSTALL_SUCCEEDED;
3187        } catch (IOException e) {
3188            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3189                    + "; src: " + srcFile.getAbsolutePath()
3190                    + ", dst: " + dstFile.getAbsolutePath());
3191        }
3192        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3193    }
3194
3195    private File[] getCompressedFiles(String codePath) {
3196        final File stubCodePath = new File(codePath);
3197        final String stubName = stubCodePath.getName();
3198
3199        // The layout of a compressed package on a given partition is as follows :
3200        //
3201        // Compressed artifacts:
3202        //
3203        // /partition/ModuleName/foo.gz
3204        // /partation/ModuleName/bar.gz
3205        //
3206        // Stub artifact:
3207        //
3208        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3209        //
3210        // In other words, stub is on the same partition as the compressed artifacts
3211        // and in a directory that's suffixed with "-Stub".
3212        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3213        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3214            return null;
3215        }
3216
3217        final File stubParentDir = stubCodePath.getParentFile();
3218        if (stubParentDir == null) {
3219            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3220            return null;
3221        }
3222
3223        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3224        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3225            @Override
3226            public boolean accept(File dir, String name) {
3227                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3228            }
3229        });
3230
3231        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3232            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3233        }
3234
3235        return files;
3236    }
3237
3238    private boolean compressedFileExists(String codePath) {
3239        final File[] compressedFiles = getCompressedFiles(codePath);
3240        return compressedFiles != null && compressedFiles.length > 0;
3241    }
3242
3243    /**
3244     * Decompresses the given package on the system image onto
3245     * the /data partition.
3246     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3247     */
3248    private File decompressPackage(PackageParser.Package pkg) {
3249        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3250        if (compressedFiles == null || compressedFiles.length == 0) {
3251            if (DEBUG_COMPRESSION) {
3252                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3253            }
3254            return null;
3255        }
3256        final File dstCodePath =
3257                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3258        int ret = PackageManager.INSTALL_SUCCEEDED;
3259        try {
3260            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3261            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3262            for (File srcFile : compressedFiles) {
3263                final String srcFileName = srcFile.getName();
3264                final String dstFileName = srcFileName.substring(
3265                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3266                final File dstFile = new File(dstCodePath, dstFileName);
3267                ret = decompressFile(srcFile, dstFile);
3268                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3269                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3270                            + "; pkg: " + pkg.packageName
3271                            + ", file: " + dstFileName);
3272                    break;
3273                }
3274            }
3275        } catch (ErrnoException e) {
3276            logCriticalInfo(Log.ERROR, "Failed to decompress"
3277                    + "; pkg: " + pkg.packageName
3278                    + ", err: " + e.errno);
3279        }
3280        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3281            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3282            NativeLibraryHelper.Handle handle = null;
3283            try {
3284                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3285                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3286                        null /*abiOverride*/);
3287            } catch (IOException e) {
3288                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3289                        + "; pkg: " + pkg.packageName);
3290                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3291            } finally {
3292                IoUtils.closeQuietly(handle);
3293            }
3294        }
3295        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3296            if (dstCodePath == null || !dstCodePath.exists()) {
3297                return null;
3298            }
3299            removeCodePathLI(dstCodePath);
3300            return null;
3301        }
3302        return dstCodePath;
3303    }
3304
3305    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3306        // we're only interested in updating the installer appliction when 1) it's not
3307        // already set or 2) the modified package is the installer
3308        if (mInstantAppInstallerActivity != null
3309                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3310                        .equals(modifiedPackage)) {
3311            return;
3312        }
3313        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3314    }
3315
3316    private static File preparePackageParserCache(boolean isUpgrade) {
3317        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3318            return null;
3319        }
3320
3321        // Disable package parsing on eng builds to allow for faster incremental development.
3322        if (Build.IS_ENG) {
3323            return null;
3324        }
3325
3326        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3327            Slog.i(TAG, "Disabling package parser cache due to system property.");
3328            return null;
3329        }
3330
3331        // The base directory for the package parser cache lives under /data/system/.
3332        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3333                "package_cache");
3334        if (cacheBaseDir == null) {
3335            return null;
3336        }
3337
3338        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3339        // This also serves to "GC" unused entries when the package cache version changes (which
3340        // can only happen during upgrades).
3341        if (isUpgrade) {
3342            FileUtils.deleteContents(cacheBaseDir);
3343        }
3344
3345
3346        // Return the versioned package cache directory. This is something like
3347        // "/data/system/package_cache/1"
3348        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3349
3350        // The following is a workaround to aid development on non-numbered userdebug
3351        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3352        // the system partition is newer.
3353        //
3354        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3355        // that starts with "eng." to signify that this is an engineering build and not
3356        // destined for release.
3357        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3358            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3359
3360            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3361            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3362            // in general and should not be used for production changes. In this specific case,
3363            // we know that they will work.
3364            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3365            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3366                FileUtils.deleteContents(cacheBaseDir);
3367                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3368            }
3369        }
3370
3371        return cacheDir;
3372    }
3373
3374    @Override
3375    public boolean isFirstBoot() {
3376        // allow instant applications
3377        return mFirstBoot;
3378    }
3379
3380    @Override
3381    public boolean isOnlyCoreApps() {
3382        // allow instant applications
3383        return mOnlyCore;
3384    }
3385
3386    @Override
3387    public boolean isUpgrade() {
3388        // allow instant applications
3389        return mIsUpgrade;
3390    }
3391
3392    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3393        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3394
3395        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3396                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3397                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3398        if (matches.size() == 1) {
3399            return matches.get(0).getComponentInfo().packageName;
3400        } else if (matches.size() == 0) {
3401            Log.e(TAG, "There should probably be a verifier, but, none were found");
3402            return null;
3403        }
3404        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3405    }
3406
3407    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3408        synchronized (mPackages) {
3409            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3410            if (libraryEntry == null) {
3411                throw new IllegalStateException("Missing required shared library:" + name);
3412            }
3413            return libraryEntry.apk;
3414        }
3415    }
3416
3417    private @NonNull String getRequiredInstallerLPr() {
3418        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3419        intent.addCategory(Intent.CATEGORY_DEFAULT);
3420        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3421
3422        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM);
3425        if (matches.size() == 1) {
3426            ResolveInfo resolveInfo = matches.get(0);
3427            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3428                throw new RuntimeException("The installer must be a privileged app");
3429            }
3430            return matches.get(0).getComponentInfo().packageName;
3431        } else {
3432            throw new RuntimeException("There must be exactly one installer; found " + matches);
3433        }
3434    }
3435
3436    private @NonNull String getRequiredUninstallerLPr() {
3437        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3438        intent.addCategory(Intent.CATEGORY_DEFAULT);
3439        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3440
3441        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3442                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3443                UserHandle.USER_SYSTEM);
3444        if (resolveInfo == null ||
3445                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3446            throw new RuntimeException("There must be exactly one uninstaller; found "
3447                    + resolveInfo);
3448        }
3449        return resolveInfo.getComponentInfo().packageName;
3450    }
3451
3452    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3453        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3454
3455        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3456                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3457                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3458        ResolveInfo best = null;
3459        final int N = matches.size();
3460        for (int i = 0; i < N; i++) {
3461            final ResolveInfo cur = matches.get(i);
3462            final String packageName = cur.getComponentInfo().packageName;
3463            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3464                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3465                continue;
3466            }
3467
3468            if (best == null || cur.priority > best.priority) {
3469                best = cur;
3470            }
3471        }
3472
3473        if (best != null) {
3474            return best.getComponentInfo().getComponentName();
3475        }
3476        Slog.w(TAG, "Intent filter verifier not found");
3477        return null;
3478    }
3479
3480    @Override
3481    public @Nullable ComponentName getInstantAppResolverComponent() {
3482        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3483            return null;
3484        }
3485        synchronized (mPackages) {
3486            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3487            if (instantAppResolver == null) {
3488                return null;
3489            }
3490            return instantAppResolver.first;
3491        }
3492    }
3493
3494    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3495        final String[] packageArray =
3496                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3497        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3498            if (DEBUG_EPHEMERAL) {
3499                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3500            }
3501            return null;
3502        }
3503
3504        final int callingUid = Binder.getCallingUid();
3505        final int resolveFlags =
3506                MATCH_DIRECT_BOOT_AWARE
3507                | MATCH_DIRECT_BOOT_UNAWARE
3508                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3509        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3510        final Intent resolverIntent = new Intent(actionName);
3511        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3512                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3513        // temporarily look for the old action
3514        if (resolvers.size() == 0) {
3515            if (DEBUG_EPHEMERAL) {
3516                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3517            }
3518            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3519            resolverIntent.setAction(actionName);
3520            resolvers = queryIntentServicesInternal(resolverIntent, null,
3521                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3522        }
3523        final int N = resolvers.size();
3524        if (N == 0) {
3525            if (DEBUG_EPHEMERAL) {
3526                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3527            }
3528            return null;
3529        }
3530
3531        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3532        for (int i = 0; i < N; i++) {
3533            final ResolveInfo info = resolvers.get(i);
3534
3535            if (info.serviceInfo == null) {
3536                continue;
3537            }
3538
3539            final String packageName = info.serviceInfo.packageName;
3540            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3541                if (DEBUG_EPHEMERAL) {
3542                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3543                            + " pkg: " + packageName + ", info:" + info);
3544                }
3545                continue;
3546            }
3547
3548            if (DEBUG_EPHEMERAL) {
3549                Slog.v(TAG, "Ephemeral resolver found;"
3550                        + " pkg: " + packageName + ", info:" + info);
3551            }
3552            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3553        }
3554        if (DEBUG_EPHEMERAL) {
3555            Slog.v(TAG, "Ephemeral resolver NOT found");
3556        }
3557        return null;
3558    }
3559
3560    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3561        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3562        intent.addCategory(Intent.CATEGORY_DEFAULT);
3563        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3564
3565        final int resolveFlags =
3566                MATCH_DIRECT_BOOT_AWARE
3567                | MATCH_DIRECT_BOOT_UNAWARE
3568                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3569        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3570                resolveFlags, UserHandle.USER_SYSTEM);
3571        // temporarily look for the old action
3572        if (matches.isEmpty()) {
3573            if (DEBUG_EPHEMERAL) {
3574                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3575            }
3576            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3577            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3578                    resolveFlags, UserHandle.USER_SYSTEM);
3579        }
3580        Iterator<ResolveInfo> iter = matches.iterator();
3581        while (iter.hasNext()) {
3582            final ResolveInfo rInfo = iter.next();
3583            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3584            if (ps != null) {
3585                final PermissionsState permissionsState = ps.getPermissionsState();
3586                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3587                    continue;
3588                }
3589            }
3590            iter.remove();
3591        }
3592        if (matches.size() == 0) {
3593            return null;
3594        } else if (matches.size() == 1) {
3595            return (ActivityInfo) matches.get(0).getComponentInfo();
3596        } else {
3597            throw new RuntimeException(
3598                    "There must be at most one ephemeral installer; found " + matches);
3599        }
3600    }
3601
3602    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3603            @NonNull ComponentName resolver) {
3604        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3605                .addCategory(Intent.CATEGORY_DEFAULT)
3606                .setPackage(resolver.getPackageName());
3607        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3608        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3609                UserHandle.USER_SYSTEM);
3610        // temporarily look for the old action
3611        if (matches.isEmpty()) {
3612            if (DEBUG_EPHEMERAL) {
3613                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3614            }
3615            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3616            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3617                    UserHandle.USER_SYSTEM);
3618        }
3619        if (matches.isEmpty()) {
3620            return null;
3621        }
3622        return matches.get(0).getComponentInfo().getComponentName();
3623    }
3624
3625    private void primeDomainVerificationsLPw(int userId) {
3626        if (DEBUG_DOMAIN_VERIFICATION) {
3627            Slog.d(TAG, "Priming domain verifications in user " + userId);
3628        }
3629
3630        SystemConfig systemConfig = SystemConfig.getInstance();
3631        ArraySet<String> packages = systemConfig.getLinkedApps();
3632
3633        for (String packageName : packages) {
3634            PackageParser.Package pkg = mPackages.get(packageName);
3635            if (pkg != null) {
3636                if (!pkg.isSystemApp()) {
3637                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3638                    continue;
3639                }
3640
3641                ArraySet<String> domains = null;
3642                for (PackageParser.Activity a : pkg.activities) {
3643                    for (ActivityIntentInfo filter : a.intents) {
3644                        if (hasValidDomains(filter)) {
3645                            if (domains == null) {
3646                                domains = new ArraySet<String>();
3647                            }
3648                            domains.addAll(filter.getHostsList());
3649                        }
3650                    }
3651                }
3652
3653                if (domains != null && domains.size() > 0) {
3654                    if (DEBUG_DOMAIN_VERIFICATION) {
3655                        Slog.v(TAG, "      + " + packageName);
3656                    }
3657                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3658                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3659                    // and then 'always' in the per-user state actually used for intent resolution.
3660                    final IntentFilterVerificationInfo ivi;
3661                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3662                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3663                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3664                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3665                } else {
3666                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3667                            + "' does not handle web links");
3668                }
3669            } else {
3670                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3671            }
3672        }
3673
3674        scheduleWritePackageRestrictionsLocked(userId);
3675        scheduleWriteSettingsLocked();
3676    }
3677
3678    private void applyFactoryDefaultBrowserLPw(int userId) {
3679        // The default browser app's package name is stored in a string resource,
3680        // with a product-specific overlay used for vendor customization.
3681        String browserPkg = mContext.getResources().getString(
3682                com.android.internal.R.string.default_browser);
3683        if (!TextUtils.isEmpty(browserPkg)) {
3684            // non-empty string => required to be a known package
3685            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3686            if (ps == null) {
3687                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3688                browserPkg = null;
3689            } else {
3690                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3691            }
3692        }
3693
3694        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3695        // default.  If there's more than one, just leave everything alone.
3696        if (browserPkg == null) {
3697            calculateDefaultBrowserLPw(userId);
3698        }
3699    }
3700
3701    private void calculateDefaultBrowserLPw(int userId) {
3702        List<String> allBrowsers = resolveAllBrowserApps(userId);
3703        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3704        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3705    }
3706
3707    private List<String> resolveAllBrowserApps(int userId) {
3708        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3709        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3710                PackageManager.MATCH_ALL, userId);
3711
3712        final int count = list.size();
3713        List<String> result = new ArrayList<String>(count);
3714        for (int i=0; i<count; i++) {
3715            ResolveInfo info = list.get(i);
3716            if (info.activityInfo == null
3717                    || !info.handleAllWebDataURI
3718                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3719                    || result.contains(info.activityInfo.packageName)) {
3720                continue;
3721            }
3722            result.add(info.activityInfo.packageName);
3723        }
3724
3725        return result;
3726    }
3727
3728    private boolean packageIsBrowser(String packageName, int userId) {
3729        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3730                PackageManager.MATCH_ALL, userId);
3731        final int N = list.size();
3732        for (int i = 0; i < N; i++) {
3733            ResolveInfo info = list.get(i);
3734            if (packageName.equals(info.activityInfo.packageName)) {
3735                return true;
3736            }
3737        }
3738        return false;
3739    }
3740
3741    private void checkDefaultBrowser() {
3742        final int myUserId = UserHandle.myUserId();
3743        final String packageName = getDefaultBrowserPackageName(myUserId);
3744        if (packageName != null) {
3745            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3746            if (info == null) {
3747                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3748                synchronized (mPackages) {
3749                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3750                }
3751            }
3752        }
3753    }
3754
3755    @Override
3756    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3757            throws RemoteException {
3758        try {
3759            return super.onTransact(code, data, reply, flags);
3760        } catch (RuntimeException e) {
3761            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3762                Slog.wtf(TAG, "Package Manager Crash", e);
3763            }
3764            throw e;
3765        }
3766    }
3767
3768    static int[] appendInts(int[] cur, int[] add) {
3769        if (add == null) return cur;
3770        if (cur == null) return add;
3771        final int N = add.length;
3772        for (int i=0; i<N; i++) {
3773            cur = appendInt(cur, add[i]);
3774        }
3775        return cur;
3776    }
3777
3778    /**
3779     * Returns whether or not a full application can see an instant application.
3780     * <p>
3781     * Currently, there are three cases in which this can occur:
3782     * <ol>
3783     * <li>The calling application is a "special" process. The special
3784     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3785     *     and {@code 0}</li>
3786     * <li>The calling application has the permission
3787     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3788     * <li>The calling application is the default launcher on the
3789     *     system partition.</li>
3790     * </ol>
3791     */
3792    private boolean canViewInstantApps(int callingUid, int userId) {
3793        if (callingUid == Process.SYSTEM_UID
3794                || callingUid == Process.SHELL_UID
3795                || callingUid == Process.ROOT_UID) {
3796            return true;
3797        }
3798        if (mContext.checkCallingOrSelfPermission(
3799                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3800            return true;
3801        }
3802        if (mContext.checkCallingOrSelfPermission(
3803                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3804            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3805            if (homeComponent != null
3806                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3807                return true;
3808            }
3809        }
3810        return false;
3811    }
3812
3813    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3814        if (!sUserManager.exists(userId)) return null;
3815        if (ps == null) {
3816            return null;
3817        }
3818        PackageParser.Package p = ps.pkg;
3819        if (p == null) {
3820            return null;
3821        }
3822        final int callingUid = Binder.getCallingUid();
3823        // Filter out ephemeral app metadata:
3824        //   * The system/shell/root can see metadata for any app
3825        //   * An installed app can see metadata for 1) other installed apps
3826        //     and 2) ephemeral apps that have explicitly interacted with it
3827        //   * Ephemeral apps can only see their own data and exposed installed apps
3828        //   * Holding a signature permission allows seeing instant apps
3829        if (filterAppAccessLPr(ps, callingUid, userId)) {
3830            return null;
3831        }
3832
3833        final PermissionsState permissionsState = ps.getPermissionsState();
3834
3835        // Compute GIDs only if requested
3836        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3837                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3838        // Compute granted permissions only if package has requested permissions
3839        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3840                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3841        final PackageUserState state = ps.readUserState(userId);
3842
3843        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3844                && ps.isSystem()) {
3845            flags |= MATCH_ANY_USER;
3846        }
3847
3848        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3849                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3850
3851        if (packageInfo == null) {
3852            return null;
3853        }
3854
3855        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3856                resolveExternalPackageNameLPr(p);
3857
3858        return packageInfo;
3859    }
3860
3861    @Override
3862    public void checkPackageStartable(String packageName, int userId) {
3863        final int callingUid = Binder.getCallingUid();
3864        if (getInstantAppPackageName(callingUid) != null) {
3865            throw new SecurityException("Instant applications don't have access to this method");
3866        }
3867        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3868        synchronized (mPackages) {
3869            final PackageSetting ps = mSettings.mPackages.get(packageName);
3870            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3871                throw new SecurityException("Package " + packageName + " was not found!");
3872            }
3873
3874            if (!ps.getInstalled(userId)) {
3875                throw new SecurityException(
3876                        "Package " + packageName + " was not installed for user " + userId + "!");
3877            }
3878
3879            if (mSafeMode && !ps.isSystem()) {
3880                throw new SecurityException("Package " + packageName + " not a system app!");
3881            }
3882
3883            if (mFrozenPackages.contains(packageName)) {
3884                throw new SecurityException("Package " + packageName + " is currently frozen!");
3885            }
3886
3887            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3888                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3889            }
3890        }
3891    }
3892
3893    @Override
3894    public boolean isPackageAvailable(String packageName, int userId) {
3895        if (!sUserManager.exists(userId)) return false;
3896        final int callingUid = Binder.getCallingUid();
3897        enforceCrossUserPermission(callingUid, userId,
3898                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3899        synchronized (mPackages) {
3900            PackageParser.Package p = mPackages.get(packageName);
3901            if (p != null) {
3902                final PackageSetting ps = (PackageSetting) p.mExtras;
3903                if (filterAppAccessLPr(ps, callingUid, userId)) {
3904                    return false;
3905                }
3906                if (ps != null) {
3907                    final PackageUserState state = ps.readUserState(userId);
3908                    if (state != null) {
3909                        return PackageParser.isAvailable(state);
3910                    }
3911                }
3912            }
3913        }
3914        return false;
3915    }
3916
3917    @Override
3918    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3919        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3920                flags, Binder.getCallingUid(), userId);
3921    }
3922
3923    @Override
3924    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3925            int flags, int userId) {
3926        return getPackageInfoInternal(versionedPackage.getPackageName(),
3927                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3928    }
3929
3930    /**
3931     * Important: The provided filterCallingUid is used exclusively to filter out packages
3932     * that can be seen based on user state. It's typically the original caller uid prior
3933     * to clearing. Because it can only be provided by trusted code, it's value can be
3934     * trusted and will be used as-is; unlike userId which will be validated by this method.
3935     */
3936    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3937            int flags, int filterCallingUid, int userId) {
3938        if (!sUserManager.exists(userId)) return null;
3939        flags = updateFlagsForPackage(flags, userId, packageName);
3940        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3941                false /* requireFullPermission */, false /* checkShell */, "get package info");
3942
3943        // reader
3944        synchronized (mPackages) {
3945            // Normalize package name to handle renamed packages and static libs
3946            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3947
3948            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3949            if (matchFactoryOnly) {
3950                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3951                if (ps != null) {
3952                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3953                        return null;
3954                    }
3955                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3956                        return null;
3957                    }
3958                    return generatePackageInfo(ps, flags, userId);
3959                }
3960            }
3961
3962            PackageParser.Package p = mPackages.get(packageName);
3963            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3964                return null;
3965            }
3966            if (DEBUG_PACKAGE_INFO)
3967                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3968            if (p != null) {
3969                final PackageSetting ps = (PackageSetting) p.mExtras;
3970                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3971                    return null;
3972                }
3973                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3974                    return null;
3975                }
3976                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3977            }
3978            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3979                final PackageSetting ps = mSettings.mPackages.get(packageName);
3980                if (ps == null) return null;
3981                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3982                    return null;
3983                }
3984                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3985                    return null;
3986                }
3987                return generatePackageInfo(ps, flags, userId);
3988            }
3989        }
3990        return null;
3991    }
3992
3993    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3994        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3995            return true;
3996        }
3997        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3998            return true;
3999        }
4000        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4001            return true;
4002        }
4003        return false;
4004    }
4005
4006    private boolean isComponentVisibleToInstantApp(
4007            @Nullable ComponentName component, @ComponentType int type) {
4008        if (type == TYPE_ACTIVITY) {
4009            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4010            return activity != null
4011                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4012                    : false;
4013        } else if (type == TYPE_RECEIVER) {
4014            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4015            return activity != null
4016                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4017                    : false;
4018        } else if (type == TYPE_SERVICE) {
4019            final PackageParser.Service service = mServices.mServices.get(component);
4020            return service != null
4021                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4022                    : false;
4023        } else if (type == TYPE_PROVIDER) {
4024            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4025            return provider != null
4026                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4027                    : false;
4028        } else if (type == TYPE_UNKNOWN) {
4029            return isComponentVisibleToInstantApp(component);
4030        }
4031        return false;
4032    }
4033
4034    /**
4035     * Returns whether or not access to the application should be filtered.
4036     * <p>
4037     * Access may be limited based upon whether the calling or target applications
4038     * are instant applications.
4039     *
4040     * @see #canAccessInstantApps(int)
4041     */
4042    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4043            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4044        // if we're in an isolated process, get the real calling UID
4045        if (Process.isIsolated(callingUid)) {
4046            callingUid = mIsolatedOwners.get(callingUid);
4047        }
4048        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4049        final boolean callerIsInstantApp = instantAppPkgName != null;
4050        if (ps == null) {
4051            if (callerIsInstantApp) {
4052                // pretend the application exists, but, needs to be filtered
4053                return true;
4054            }
4055            return false;
4056        }
4057        // if the target and caller are the same application, don't filter
4058        if (isCallerSameApp(ps.name, callingUid)) {
4059            return false;
4060        }
4061        if (callerIsInstantApp) {
4062            // request for a specific component; if it hasn't been explicitly exposed, filter
4063            if (component != null) {
4064                return !isComponentVisibleToInstantApp(component, componentType);
4065            }
4066            // request for application; if no components have been explicitly exposed, filter
4067            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4068        }
4069        if (ps.getInstantApp(userId)) {
4070            // caller can see all components of all instant applications, don't filter
4071            if (canViewInstantApps(callingUid, userId)) {
4072                return false;
4073            }
4074            // request for a specific instant application component, filter
4075            if (component != null) {
4076                return true;
4077            }
4078            // request for an instant application; if the caller hasn't been granted access, filter
4079            return !mInstantAppRegistry.isInstantAccessGranted(
4080                    userId, UserHandle.getAppId(callingUid), ps.appId);
4081        }
4082        return false;
4083    }
4084
4085    /**
4086     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4087     */
4088    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4089        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4090    }
4091
4092    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4093            int flags) {
4094        // Callers can access only the libs they depend on, otherwise they need to explicitly
4095        // ask for the shared libraries given the caller is allowed to access all static libs.
4096        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4097            // System/shell/root get to see all static libs
4098            final int appId = UserHandle.getAppId(uid);
4099            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4100                    || appId == Process.ROOT_UID) {
4101                return false;
4102            }
4103        }
4104
4105        // No package means no static lib as it is always on internal storage
4106        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4107            return false;
4108        }
4109
4110        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4111                ps.pkg.staticSharedLibVersion);
4112        if (libEntry == null) {
4113            return false;
4114        }
4115
4116        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4117        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4118        if (uidPackageNames == null) {
4119            return true;
4120        }
4121
4122        for (String uidPackageName : uidPackageNames) {
4123            if (ps.name.equals(uidPackageName)) {
4124                return false;
4125            }
4126            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4127            if (uidPs != null) {
4128                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4129                        libEntry.info.getName());
4130                if (index < 0) {
4131                    continue;
4132                }
4133                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4134                    return false;
4135                }
4136            }
4137        }
4138        return true;
4139    }
4140
4141    @Override
4142    public String[] currentToCanonicalPackageNames(String[] names) {
4143        final int callingUid = Binder.getCallingUid();
4144        if (getInstantAppPackageName(callingUid) != null) {
4145            return names;
4146        }
4147        final String[] out = new String[names.length];
4148        // reader
4149        synchronized (mPackages) {
4150            final int callingUserId = UserHandle.getUserId(callingUid);
4151            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4152            for (int i=names.length-1; i>=0; i--) {
4153                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4154                boolean translateName = false;
4155                if (ps != null && ps.realName != null) {
4156                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4157                    translateName = !targetIsInstantApp
4158                            || canViewInstantApps
4159                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4160                                    UserHandle.getAppId(callingUid), ps.appId);
4161                }
4162                out[i] = translateName ? ps.realName : names[i];
4163            }
4164        }
4165        return out;
4166    }
4167
4168    @Override
4169    public String[] canonicalToCurrentPackageNames(String[] names) {
4170        final int callingUid = Binder.getCallingUid();
4171        if (getInstantAppPackageName(callingUid) != null) {
4172            return names;
4173        }
4174        final String[] out = new String[names.length];
4175        // reader
4176        synchronized (mPackages) {
4177            final int callingUserId = UserHandle.getUserId(callingUid);
4178            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4179            for (int i=names.length-1; i>=0; i--) {
4180                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4181                boolean translateName = false;
4182                if (cur != null) {
4183                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4184                    final boolean targetIsInstantApp =
4185                            ps != null && ps.getInstantApp(callingUserId);
4186                    translateName = !targetIsInstantApp
4187                            || canViewInstantApps
4188                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4189                                    UserHandle.getAppId(callingUid), ps.appId);
4190                }
4191                out[i] = translateName ? cur : names[i];
4192            }
4193        }
4194        return out;
4195    }
4196
4197    @Override
4198    public int getPackageUid(String packageName, int flags, int userId) {
4199        if (!sUserManager.exists(userId)) return -1;
4200        final int callingUid = Binder.getCallingUid();
4201        flags = updateFlagsForPackage(flags, userId, packageName);
4202        enforceCrossUserPermission(callingUid, userId,
4203                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4204
4205        // reader
4206        synchronized (mPackages) {
4207            final PackageParser.Package p = mPackages.get(packageName);
4208            if (p != null && p.isMatch(flags)) {
4209                PackageSetting ps = (PackageSetting) p.mExtras;
4210                if (filterAppAccessLPr(ps, callingUid, userId)) {
4211                    return -1;
4212                }
4213                return UserHandle.getUid(userId, p.applicationInfo.uid);
4214            }
4215            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4216                final PackageSetting ps = mSettings.mPackages.get(packageName);
4217                if (ps != null && ps.isMatch(flags)
4218                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4219                    return UserHandle.getUid(userId, ps.appId);
4220                }
4221            }
4222        }
4223
4224        return -1;
4225    }
4226
4227    @Override
4228    public int[] getPackageGids(String packageName, int flags, int userId) {
4229        if (!sUserManager.exists(userId)) return null;
4230        final int callingUid = Binder.getCallingUid();
4231        flags = updateFlagsForPackage(flags, userId, packageName);
4232        enforceCrossUserPermission(callingUid, userId,
4233                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4234
4235        // reader
4236        synchronized (mPackages) {
4237            final PackageParser.Package p = mPackages.get(packageName);
4238            if (p != null && p.isMatch(flags)) {
4239                PackageSetting ps = (PackageSetting) p.mExtras;
4240                if (filterAppAccessLPr(ps, callingUid, userId)) {
4241                    return null;
4242                }
4243                // TODO: Shouldn't this be checking for package installed state for userId and
4244                // return null?
4245                return ps.getPermissionsState().computeGids(userId);
4246            }
4247            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4248                final PackageSetting ps = mSettings.mPackages.get(packageName);
4249                if (ps != null && ps.isMatch(flags)
4250                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4251                    return ps.getPermissionsState().computeGids(userId);
4252                }
4253            }
4254        }
4255
4256        return null;
4257    }
4258
4259    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4260        if (bp.perm != null) {
4261            return PackageParser.generatePermissionInfo(bp.perm, flags);
4262        }
4263        PermissionInfo pi = new PermissionInfo();
4264        pi.name = bp.name;
4265        pi.packageName = bp.sourcePackage;
4266        pi.nonLocalizedLabel = bp.name;
4267        pi.protectionLevel = bp.protectionLevel;
4268        return pi;
4269    }
4270
4271    @Override
4272    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4273        final int callingUid = Binder.getCallingUid();
4274        if (getInstantAppPackageName(callingUid) != null) {
4275            return null;
4276        }
4277        // reader
4278        synchronized (mPackages) {
4279            final BasePermission p = mSettings.mPermissions.get(name);
4280            if (p == null) {
4281                return null;
4282            }
4283            // If the caller is an app that targets pre 26 SDK drop protection flags.
4284            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4285            if (permissionInfo != null) {
4286                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4287                        permissionInfo.protectionLevel, packageName, callingUid);
4288                if (permissionInfo.protectionLevel != protectionLevel) {
4289                    // If we return different protection level, don't use the cached info
4290                    if (p.perm != null && p.perm.info == permissionInfo) {
4291                        permissionInfo = new PermissionInfo(permissionInfo);
4292                    }
4293                    permissionInfo.protectionLevel = protectionLevel;
4294                }
4295            }
4296            return permissionInfo;
4297        }
4298    }
4299
4300    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4301            String packageName, int uid) {
4302        // Signature permission flags area always reported
4303        final int protectionLevelMasked = protectionLevel
4304                & (PermissionInfo.PROTECTION_NORMAL
4305                | PermissionInfo.PROTECTION_DANGEROUS
4306                | PermissionInfo.PROTECTION_SIGNATURE);
4307        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4308            return protectionLevel;
4309        }
4310
4311        // System sees all flags.
4312        final int appId = UserHandle.getAppId(uid);
4313        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4314                || appId == Process.SHELL_UID) {
4315            return protectionLevel;
4316        }
4317
4318        // Normalize package name to handle renamed packages and static libs
4319        packageName = resolveInternalPackageNameLPr(packageName,
4320                PackageManager.VERSION_CODE_HIGHEST);
4321
4322        // Apps that target O see flags for all protection levels.
4323        final PackageSetting ps = mSettings.mPackages.get(packageName);
4324        if (ps == null) {
4325            return protectionLevel;
4326        }
4327        if (ps.appId != appId) {
4328            return protectionLevel;
4329        }
4330
4331        final PackageParser.Package pkg = mPackages.get(packageName);
4332        if (pkg == null) {
4333            return protectionLevel;
4334        }
4335        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4336            return protectionLevelMasked;
4337        }
4338
4339        return protectionLevel;
4340    }
4341
4342    @Override
4343    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4344            int flags) {
4345        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4346            return null;
4347        }
4348        // reader
4349        synchronized (mPackages) {
4350            if (group != null && !mPermissionGroups.containsKey(group)) {
4351                // This is thrown as NameNotFoundException
4352                return null;
4353            }
4354
4355            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4356            for (BasePermission p : mSettings.mPermissions.values()) {
4357                if (group == null) {
4358                    if (p.perm == null || p.perm.info.group == null) {
4359                        out.add(generatePermissionInfo(p, flags));
4360                    }
4361                } else {
4362                    if (p.perm != null && group.equals(p.perm.info.group)) {
4363                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4364                    }
4365                }
4366            }
4367            return new ParceledListSlice<>(out);
4368        }
4369    }
4370
4371    @Override
4372    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4373        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4374            return null;
4375        }
4376        // reader
4377        synchronized (mPackages) {
4378            return PackageParser.generatePermissionGroupInfo(
4379                    mPermissionGroups.get(name), flags);
4380        }
4381    }
4382
4383    @Override
4384    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4385        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4386            return ParceledListSlice.emptyList();
4387        }
4388        // reader
4389        synchronized (mPackages) {
4390            final int N = mPermissionGroups.size();
4391            ArrayList<PermissionGroupInfo> out
4392                    = new ArrayList<PermissionGroupInfo>(N);
4393            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4394                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4395            }
4396            return new ParceledListSlice<>(out);
4397        }
4398    }
4399
4400    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4401            int filterCallingUid, int userId) {
4402        if (!sUserManager.exists(userId)) return null;
4403        PackageSetting ps = mSettings.mPackages.get(packageName);
4404        if (ps != null) {
4405            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4406                return null;
4407            }
4408            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4409                return null;
4410            }
4411            if (ps.pkg == null) {
4412                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4413                if (pInfo != null) {
4414                    return pInfo.applicationInfo;
4415                }
4416                return null;
4417            }
4418            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4419                    ps.readUserState(userId), userId);
4420            if (ai != null) {
4421                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4422            }
4423            return ai;
4424        }
4425        return null;
4426    }
4427
4428    @Override
4429    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4430        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4431    }
4432
4433    /**
4434     * Important: The provided filterCallingUid is used exclusively to filter out applications
4435     * that can be seen based on user state. It's typically the original caller uid prior
4436     * to clearing. Because it can only be provided by trusted code, it's value can be
4437     * trusted and will be used as-is; unlike userId which will be validated by this method.
4438     */
4439    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4440            int filterCallingUid, int userId) {
4441        if (!sUserManager.exists(userId)) return null;
4442        flags = updateFlagsForApplication(flags, userId, packageName);
4443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4444                false /* requireFullPermission */, false /* checkShell */, "get application info");
4445
4446        // writer
4447        synchronized (mPackages) {
4448            // Normalize package name to handle renamed packages and static libs
4449            packageName = resolveInternalPackageNameLPr(packageName,
4450                    PackageManager.VERSION_CODE_HIGHEST);
4451
4452            PackageParser.Package p = mPackages.get(packageName);
4453            if (DEBUG_PACKAGE_INFO) Log.v(
4454                    TAG, "getApplicationInfo " + packageName
4455                    + ": " + p);
4456            if (p != null) {
4457                PackageSetting ps = mSettings.mPackages.get(packageName);
4458                if (ps == null) return null;
4459                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4460                    return null;
4461                }
4462                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4463                    return null;
4464                }
4465                // Note: isEnabledLP() does not apply here - always return info
4466                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4467                        p, flags, ps.readUserState(userId), userId);
4468                if (ai != null) {
4469                    ai.packageName = resolveExternalPackageNameLPr(p);
4470                }
4471                return ai;
4472            }
4473            if ("android".equals(packageName)||"system".equals(packageName)) {
4474                return mAndroidApplication;
4475            }
4476            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4477                // Already generates the external package name
4478                return generateApplicationInfoFromSettingsLPw(packageName,
4479                        flags, filterCallingUid, userId);
4480            }
4481        }
4482        return null;
4483    }
4484
4485    private String normalizePackageNameLPr(String packageName) {
4486        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4487        return normalizedPackageName != null ? normalizedPackageName : packageName;
4488    }
4489
4490    @Override
4491    public void deletePreloadsFileCache() {
4492        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4493            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4494        }
4495        File dir = Environment.getDataPreloadsFileCacheDirectory();
4496        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4497        FileUtils.deleteContents(dir);
4498    }
4499
4500    @Override
4501    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4502            final int storageFlags, final IPackageDataObserver observer) {
4503        mContext.enforceCallingOrSelfPermission(
4504                android.Manifest.permission.CLEAR_APP_CACHE, null);
4505        mHandler.post(() -> {
4506            boolean success = false;
4507            try {
4508                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4509                success = true;
4510            } catch (IOException e) {
4511                Slog.w(TAG, e);
4512            }
4513            if (observer != null) {
4514                try {
4515                    observer.onRemoveCompleted(null, success);
4516                } catch (RemoteException e) {
4517                    Slog.w(TAG, e);
4518                }
4519            }
4520        });
4521    }
4522
4523    @Override
4524    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4525            final int storageFlags, final IntentSender pi) {
4526        mContext.enforceCallingOrSelfPermission(
4527                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4528        mHandler.post(() -> {
4529            boolean success = false;
4530            try {
4531                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4532                success = true;
4533            } catch (IOException e) {
4534                Slog.w(TAG, e);
4535            }
4536            if (pi != null) {
4537                try {
4538                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4539                } catch (SendIntentException e) {
4540                    Slog.w(TAG, e);
4541                }
4542            }
4543        });
4544    }
4545
4546    /**
4547     * Blocking call to clear various types of cached data across the system
4548     * until the requested bytes are available.
4549     */
4550    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4551        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4552        final File file = storage.findPathForUuid(volumeUuid);
4553        if (file.getUsableSpace() >= bytes) return;
4554
4555        if (ENABLE_FREE_CACHE_V2) {
4556            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4557                    volumeUuid);
4558            final boolean aggressive = (storageFlags
4559                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4560            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4561
4562            // 1. Pre-flight to determine if we have any chance to succeed
4563            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4564            if (internalVolume && (aggressive || SystemProperties
4565                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4566                deletePreloadsFileCache();
4567                if (file.getUsableSpace() >= bytes) return;
4568            }
4569
4570            // 3. Consider parsed APK data (aggressive only)
4571            if (internalVolume && aggressive) {
4572                FileUtils.deleteContents(mCacheDir);
4573                if (file.getUsableSpace() >= bytes) return;
4574            }
4575
4576            // 4. Consider cached app data (above quotas)
4577            try {
4578                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4579                        Installer.FLAG_FREE_CACHE_V2);
4580            } catch (InstallerException ignored) {
4581            }
4582            if (file.getUsableSpace() >= bytes) return;
4583
4584            // 5. Consider shared libraries with refcount=0 and age>min cache period
4585            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4586                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4587                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4588                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4589                return;
4590            }
4591
4592            // 6. Consider dexopt output (aggressive only)
4593            // TODO: Implement
4594
4595            // 7. Consider installed instant apps unused longer than min cache period
4596            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4597                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4598                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4599                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4600                return;
4601            }
4602
4603            // 8. Consider cached app data (below quotas)
4604            try {
4605                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4606                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4607            } catch (InstallerException ignored) {
4608            }
4609            if (file.getUsableSpace() >= bytes) return;
4610
4611            // 9. Consider DropBox entries
4612            // TODO: Implement
4613
4614            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4615            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4616                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4617                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4618                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4619                return;
4620            }
4621        } else {
4622            try {
4623                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4624            } catch (InstallerException ignored) {
4625            }
4626            if (file.getUsableSpace() >= bytes) return;
4627        }
4628
4629        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4630    }
4631
4632    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4633            throws IOException {
4634        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4635        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4636
4637        List<VersionedPackage> packagesToDelete = null;
4638        final long now = System.currentTimeMillis();
4639
4640        synchronized (mPackages) {
4641            final int[] allUsers = sUserManager.getUserIds();
4642            final int libCount = mSharedLibraries.size();
4643            for (int i = 0; i < libCount; i++) {
4644                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4645                if (versionedLib == null) {
4646                    continue;
4647                }
4648                final int versionCount = versionedLib.size();
4649                for (int j = 0; j < versionCount; j++) {
4650                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4651                    // Skip packages that are not static shared libs.
4652                    if (!libInfo.isStatic()) {
4653                        break;
4654                    }
4655                    // Important: We skip static shared libs used for some user since
4656                    // in such a case we need to keep the APK on the device. The check for
4657                    // a lib being used for any user is performed by the uninstall call.
4658                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4659                    // Resolve the package name - we use synthetic package names internally
4660                    final String internalPackageName = resolveInternalPackageNameLPr(
4661                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4662                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4663                    // Skip unused static shared libs cached less than the min period
4664                    // to prevent pruning a lib needed by a subsequently installed package.
4665                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4666                        continue;
4667                    }
4668                    if (packagesToDelete == null) {
4669                        packagesToDelete = new ArrayList<>();
4670                    }
4671                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4672                            declaringPackage.getVersionCode()));
4673                }
4674            }
4675        }
4676
4677        if (packagesToDelete != null) {
4678            final int packageCount = packagesToDelete.size();
4679            for (int i = 0; i < packageCount; i++) {
4680                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4681                // Delete the package synchronously (will fail of the lib used for any user).
4682                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4683                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4684                                == PackageManager.DELETE_SUCCEEDED) {
4685                    if (volume.getUsableSpace() >= neededSpace) {
4686                        return true;
4687                    }
4688                }
4689            }
4690        }
4691
4692        return false;
4693    }
4694
4695    /**
4696     * Update given flags based on encryption status of current user.
4697     */
4698    private int updateFlags(int flags, int userId) {
4699        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4700                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4701            // Caller expressed an explicit opinion about what encryption
4702            // aware/unaware components they want to see, so fall through and
4703            // give them what they want
4704        } else {
4705            // Caller expressed no opinion, so match based on user state
4706            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4707                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4708            } else {
4709                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4710            }
4711        }
4712        return flags;
4713    }
4714
4715    private UserManagerInternal getUserManagerInternal() {
4716        if (mUserManagerInternal == null) {
4717            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4718        }
4719        return mUserManagerInternal;
4720    }
4721
4722    private DeviceIdleController.LocalService getDeviceIdleController() {
4723        if (mDeviceIdleController == null) {
4724            mDeviceIdleController =
4725                    LocalServices.getService(DeviceIdleController.LocalService.class);
4726        }
4727        return mDeviceIdleController;
4728    }
4729
4730    /**
4731     * Update given flags when being used to request {@link PackageInfo}.
4732     */
4733    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4734        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4735        boolean triaged = true;
4736        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4737                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4738            // Caller is asking for component details, so they'd better be
4739            // asking for specific encryption matching behavior, or be triaged
4740            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4741                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4742                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4743                triaged = false;
4744            }
4745        }
4746        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4747                | PackageManager.MATCH_SYSTEM_ONLY
4748                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4749            triaged = false;
4750        }
4751        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4752            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4753                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4754                    + Debug.getCallers(5));
4755        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4756                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4757            // If the caller wants all packages and has a restricted profile associated with it,
4758            // then match all users. This is to make sure that launchers that need to access work
4759            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4760            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4761            flags |= PackageManager.MATCH_ANY_USER;
4762        }
4763        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4764            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4765                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4766        }
4767        return updateFlags(flags, userId);
4768    }
4769
4770    /**
4771     * Update given flags when being used to request {@link ApplicationInfo}.
4772     */
4773    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4774        return updateFlagsForPackage(flags, userId, cookie);
4775    }
4776
4777    /**
4778     * Update given flags when being used to request {@link ComponentInfo}.
4779     */
4780    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4781        if (cookie instanceof Intent) {
4782            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4783                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4784            }
4785        }
4786
4787        boolean triaged = true;
4788        // Caller is asking for component details, so they'd better be
4789        // asking for specific encryption matching behavior, or be triaged
4790        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4791                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4792                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4793            triaged = false;
4794        }
4795        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4796            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4797                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4798        }
4799
4800        return updateFlags(flags, userId);
4801    }
4802
4803    /**
4804     * Update given intent when being used to request {@link ResolveInfo}.
4805     */
4806    private Intent updateIntentForResolve(Intent intent) {
4807        if (intent.getSelector() != null) {
4808            intent = intent.getSelector();
4809        }
4810        if (DEBUG_PREFERRED) {
4811            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4812        }
4813        return intent;
4814    }
4815
4816    /**
4817     * Update given flags when being used to request {@link ResolveInfo}.
4818     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4819     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4820     * flag set. However, this flag is only honoured in three circumstances:
4821     * <ul>
4822     * <li>when called from a system process</li>
4823     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4824     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4825     * action and a {@code android.intent.category.BROWSABLE} category</li>
4826     * </ul>
4827     */
4828    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4829        return updateFlagsForResolve(flags, userId, intent, callingUid,
4830                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4831    }
4832    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4833            boolean wantInstantApps) {
4834        return updateFlagsForResolve(flags, userId, intent, callingUid,
4835                wantInstantApps, false /*onlyExposedExplicitly*/);
4836    }
4837    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4838            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4839        // Safe mode means we shouldn't match any third-party components
4840        if (mSafeMode) {
4841            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4842        }
4843        if (getInstantAppPackageName(callingUid) != null) {
4844            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4845            if (onlyExposedExplicitly) {
4846                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4847            }
4848            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4849            flags |= PackageManager.MATCH_INSTANT;
4850        } else {
4851            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4852            final boolean allowMatchInstant =
4853                    (wantInstantApps
4854                            && Intent.ACTION_VIEW.equals(intent.getAction())
4855                            && hasWebURI(intent))
4856                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4857            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4858                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4859            if (!allowMatchInstant) {
4860                flags &= ~PackageManager.MATCH_INSTANT;
4861            }
4862        }
4863        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4864    }
4865
4866    @Override
4867    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4868        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4869    }
4870
4871    /**
4872     * Important: The provided filterCallingUid is used exclusively to filter out activities
4873     * that can be seen based on user state. It's typically the original caller uid prior
4874     * to clearing. Because it can only be provided by trusted code, it's value can be
4875     * trusted and will be used as-is; unlike userId which will be validated by this method.
4876     */
4877    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4878            int filterCallingUid, int userId) {
4879        if (!sUserManager.exists(userId)) return null;
4880        flags = updateFlagsForComponent(flags, userId, component);
4881        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4882                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4883        synchronized (mPackages) {
4884            PackageParser.Activity a = mActivities.mActivities.get(component);
4885
4886            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4887            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4888                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4889                if (ps == null) return null;
4890                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4891                    return null;
4892                }
4893                return PackageParser.generateActivityInfo(
4894                        a, flags, ps.readUserState(userId), userId);
4895            }
4896            if (mResolveComponentName.equals(component)) {
4897                return PackageParser.generateActivityInfo(
4898                        mResolveActivity, flags, new PackageUserState(), userId);
4899            }
4900        }
4901        return null;
4902    }
4903
4904    @Override
4905    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4906            String resolvedType) {
4907        synchronized (mPackages) {
4908            if (component.equals(mResolveComponentName)) {
4909                // The resolver supports EVERYTHING!
4910                return true;
4911            }
4912            final int callingUid = Binder.getCallingUid();
4913            final int callingUserId = UserHandle.getUserId(callingUid);
4914            PackageParser.Activity a = mActivities.mActivities.get(component);
4915            if (a == null) {
4916                return false;
4917            }
4918            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4919            if (ps == null) {
4920                return false;
4921            }
4922            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4923                return false;
4924            }
4925            for (int i=0; i<a.intents.size(); i++) {
4926                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4927                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4928                    return true;
4929                }
4930            }
4931            return false;
4932        }
4933    }
4934
4935    @Override
4936    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4937        if (!sUserManager.exists(userId)) return null;
4938        final int callingUid = Binder.getCallingUid();
4939        flags = updateFlagsForComponent(flags, userId, component);
4940        enforceCrossUserPermission(callingUid, userId,
4941                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4942        synchronized (mPackages) {
4943            PackageParser.Activity a = mReceivers.mActivities.get(component);
4944            if (DEBUG_PACKAGE_INFO) Log.v(
4945                TAG, "getReceiverInfo " + component + ": " + a);
4946            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4947                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4948                if (ps == null) return null;
4949                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4950                    return null;
4951                }
4952                return PackageParser.generateActivityInfo(
4953                        a, flags, ps.readUserState(userId), userId);
4954            }
4955        }
4956        return null;
4957    }
4958
4959    @Override
4960    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4961            int flags, int userId) {
4962        if (!sUserManager.exists(userId)) return null;
4963        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4964        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4965            return null;
4966        }
4967
4968        flags = updateFlagsForPackage(flags, userId, null);
4969
4970        final boolean canSeeStaticLibraries =
4971                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4972                        == PERMISSION_GRANTED
4973                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4974                        == PERMISSION_GRANTED
4975                || canRequestPackageInstallsInternal(packageName,
4976                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4977                        false  /* throwIfPermNotDeclared*/)
4978                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4979                        == PERMISSION_GRANTED;
4980
4981        synchronized (mPackages) {
4982            List<SharedLibraryInfo> result = null;
4983
4984            final int libCount = mSharedLibraries.size();
4985            for (int i = 0; i < libCount; i++) {
4986                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4987                if (versionedLib == null) {
4988                    continue;
4989                }
4990
4991                final int versionCount = versionedLib.size();
4992                for (int j = 0; j < versionCount; j++) {
4993                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4994                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4995                        break;
4996                    }
4997                    final long identity = Binder.clearCallingIdentity();
4998                    try {
4999                        PackageInfo packageInfo = getPackageInfoVersioned(
5000                                libInfo.getDeclaringPackage(), flags
5001                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5002                        if (packageInfo == null) {
5003                            continue;
5004                        }
5005                    } finally {
5006                        Binder.restoreCallingIdentity(identity);
5007                    }
5008
5009                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5010                            libInfo.getVersion(), libInfo.getType(),
5011                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5012                            flags, userId));
5013
5014                    if (result == null) {
5015                        result = new ArrayList<>();
5016                    }
5017                    result.add(resLibInfo);
5018                }
5019            }
5020
5021            return result != null ? new ParceledListSlice<>(result) : null;
5022        }
5023    }
5024
5025    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5026            SharedLibraryInfo libInfo, int flags, int userId) {
5027        List<VersionedPackage> versionedPackages = null;
5028        final int packageCount = mSettings.mPackages.size();
5029        for (int i = 0; i < packageCount; i++) {
5030            PackageSetting ps = mSettings.mPackages.valueAt(i);
5031
5032            if (ps == null) {
5033                continue;
5034            }
5035
5036            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5037                continue;
5038            }
5039
5040            final String libName = libInfo.getName();
5041            if (libInfo.isStatic()) {
5042                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5043                if (libIdx < 0) {
5044                    continue;
5045                }
5046                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5047                    continue;
5048                }
5049                if (versionedPackages == null) {
5050                    versionedPackages = new ArrayList<>();
5051                }
5052                // If the dependent is a static shared lib, use the public package name
5053                String dependentPackageName = ps.name;
5054                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5055                    dependentPackageName = ps.pkg.manifestPackageName;
5056                }
5057                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5058            } else if (ps.pkg != null) {
5059                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5060                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5061                    if (versionedPackages == null) {
5062                        versionedPackages = new ArrayList<>();
5063                    }
5064                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5065                }
5066            }
5067        }
5068
5069        return versionedPackages;
5070    }
5071
5072    @Override
5073    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5074        if (!sUserManager.exists(userId)) return null;
5075        final int callingUid = Binder.getCallingUid();
5076        flags = updateFlagsForComponent(flags, userId, component);
5077        enforceCrossUserPermission(callingUid, userId,
5078                false /* requireFullPermission */, false /* checkShell */, "get service info");
5079        synchronized (mPackages) {
5080            PackageParser.Service s = mServices.mServices.get(component);
5081            if (DEBUG_PACKAGE_INFO) Log.v(
5082                TAG, "getServiceInfo " + component + ": " + s);
5083            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5084                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5085                if (ps == null) return null;
5086                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5087                    return null;
5088                }
5089                return PackageParser.generateServiceInfo(
5090                        s, flags, ps.readUserState(userId), userId);
5091            }
5092        }
5093        return null;
5094    }
5095
5096    @Override
5097    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5098        if (!sUserManager.exists(userId)) return null;
5099        final int callingUid = Binder.getCallingUid();
5100        flags = updateFlagsForComponent(flags, userId, component);
5101        enforceCrossUserPermission(callingUid, userId,
5102                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5103        synchronized (mPackages) {
5104            PackageParser.Provider p = mProviders.mProviders.get(component);
5105            if (DEBUG_PACKAGE_INFO) Log.v(
5106                TAG, "getProviderInfo " + component + ": " + p);
5107            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5108                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5109                if (ps == null) return null;
5110                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5111                    return null;
5112                }
5113                return PackageParser.generateProviderInfo(
5114                        p, flags, ps.readUserState(userId), userId);
5115            }
5116        }
5117        return null;
5118    }
5119
5120    @Override
5121    public String[] getSystemSharedLibraryNames() {
5122        // allow instant applications
5123        synchronized (mPackages) {
5124            Set<String> libs = null;
5125            final int libCount = mSharedLibraries.size();
5126            for (int i = 0; i < libCount; i++) {
5127                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5128                if (versionedLib == null) {
5129                    continue;
5130                }
5131                final int versionCount = versionedLib.size();
5132                for (int j = 0; j < versionCount; j++) {
5133                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5134                    if (!libEntry.info.isStatic()) {
5135                        if (libs == null) {
5136                            libs = new ArraySet<>();
5137                        }
5138                        libs.add(libEntry.info.getName());
5139                        break;
5140                    }
5141                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5142                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5143                            UserHandle.getUserId(Binder.getCallingUid()),
5144                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5145                        if (libs == null) {
5146                            libs = new ArraySet<>();
5147                        }
5148                        libs.add(libEntry.info.getName());
5149                        break;
5150                    }
5151                }
5152            }
5153
5154            if (libs != null) {
5155                String[] libsArray = new String[libs.size()];
5156                libs.toArray(libsArray);
5157                return libsArray;
5158            }
5159
5160            return null;
5161        }
5162    }
5163
5164    @Override
5165    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5166        // allow instant applications
5167        synchronized (mPackages) {
5168            return mServicesSystemSharedLibraryPackageName;
5169        }
5170    }
5171
5172    @Override
5173    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5174        // allow instant applications
5175        synchronized (mPackages) {
5176            return mSharedSystemSharedLibraryPackageName;
5177        }
5178    }
5179
5180    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5181        for (int i = userList.length - 1; i >= 0; --i) {
5182            final int userId = userList[i];
5183            // don't add instant app to the list of updates
5184            if (pkgSetting.getInstantApp(userId)) {
5185                continue;
5186            }
5187            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5188            if (changedPackages == null) {
5189                changedPackages = new SparseArray<>();
5190                mChangedPackages.put(userId, changedPackages);
5191            }
5192            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5193            if (sequenceNumbers == null) {
5194                sequenceNumbers = new HashMap<>();
5195                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5196            }
5197            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5198            if (sequenceNumber != null) {
5199                changedPackages.remove(sequenceNumber);
5200            }
5201            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5202            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5203        }
5204        mChangedPackagesSequenceNumber++;
5205    }
5206
5207    @Override
5208    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5209        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5210            return null;
5211        }
5212        synchronized (mPackages) {
5213            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5214                return null;
5215            }
5216            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5217            if (changedPackages == null) {
5218                return null;
5219            }
5220            final List<String> packageNames =
5221                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5222            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5223                final String packageName = changedPackages.get(i);
5224                if (packageName != null) {
5225                    packageNames.add(packageName);
5226                }
5227            }
5228            return packageNames.isEmpty()
5229                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5230        }
5231    }
5232
5233    @Override
5234    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5235        // allow instant applications
5236        ArrayList<FeatureInfo> res;
5237        synchronized (mAvailableFeatures) {
5238            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5239            res.addAll(mAvailableFeatures.values());
5240        }
5241        final FeatureInfo fi = new FeatureInfo();
5242        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5243                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5244        res.add(fi);
5245
5246        return new ParceledListSlice<>(res);
5247    }
5248
5249    @Override
5250    public boolean hasSystemFeature(String name, int version) {
5251        // allow instant applications
5252        synchronized (mAvailableFeatures) {
5253            final FeatureInfo feat = mAvailableFeatures.get(name);
5254            if (feat == null) {
5255                return false;
5256            } else {
5257                return feat.version >= version;
5258            }
5259        }
5260    }
5261
5262    @Override
5263    public int checkPermission(String permName, String pkgName, int userId) {
5264        if (!sUserManager.exists(userId)) {
5265            return PackageManager.PERMISSION_DENIED;
5266        }
5267        final int callingUid = Binder.getCallingUid();
5268
5269        synchronized (mPackages) {
5270            final PackageParser.Package p = mPackages.get(pkgName);
5271            if (p != null && p.mExtras != null) {
5272                final PackageSetting ps = (PackageSetting) p.mExtras;
5273                if (filterAppAccessLPr(ps, callingUid, userId)) {
5274                    return PackageManager.PERMISSION_DENIED;
5275                }
5276                final boolean instantApp = ps.getInstantApp(userId);
5277                final PermissionsState permissionsState = ps.getPermissionsState();
5278                if (permissionsState.hasPermission(permName, userId)) {
5279                    if (instantApp) {
5280                        BasePermission bp = mSettings.mPermissions.get(permName);
5281                        if (bp != null && bp.isInstant()) {
5282                            return PackageManager.PERMISSION_GRANTED;
5283                        }
5284                    } else {
5285                        return PackageManager.PERMISSION_GRANTED;
5286                    }
5287                }
5288                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5289                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5290                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5291                    return PackageManager.PERMISSION_GRANTED;
5292                }
5293            }
5294        }
5295
5296        return PackageManager.PERMISSION_DENIED;
5297    }
5298
5299    @Override
5300    public int checkUidPermission(String permName, int uid) {
5301        final int callingUid = Binder.getCallingUid();
5302        final int callingUserId = UserHandle.getUserId(callingUid);
5303        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5304        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5305        final int userId = UserHandle.getUserId(uid);
5306        if (!sUserManager.exists(userId)) {
5307            return PackageManager.PERMISSION_DENIED;
5308        }
5309
5310        synchronized (mPackages) {
5311            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5312            if (obj != null) {
5313                if (obj instanceof SharedUserSetting) {
5314                    if (isCallerInstantApp) {
5315                        return PackageManager.PERMISSION_DENIED;
5316                    }
5317                } else if (obj instanceof PackageSetting) {
5318                    final PackageSetting ps = (PackageSetting) obj;
5319                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5320                        return PackageManager.PERMISSION_DENIED;
5321                    }
5322                }
5323                final SettingBase settingBase = (SettingBase) obj;
5324                final PermissionsState permissionsState = settingBase.getPermissionsState();
5325                if (permissionsState.hasPermission(permName, userId)) {
5326                    if (isUidInstantApp) {
5327                        BasePermission bp = mSettings.mPermissions.get(permName);
5328                        if (bp != null && bp.isInstant()) {
5329                            return PackageManager.PERMISSION_GRANTED;
5330                        }
5331                    } else {
5332                        return PackageManager.PERMISSION_GRANTED;
5333                    }
5334                }
5335                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5336                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5337                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5338                    return PackageManager.PERMISSION_GRANTED;
5339                }
5340            } else {
5341                ArraySet<String> perms = mSystemPermissions.get(uid);
5342                if (perms != null) {
5343                    if (perms.contains(permName)) {
5344                        return PackageManager.PERMISSION_GRANTED;
5345                    }
5346                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5347                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5348                        return PackageManager.PERMISSION_GRANTED;
5349                    }
5350                }
5351            }
5352        }
5353
5354        return PackageManager.PERMISSION_DENIED;
5355    }
5356
5357    @Override
5358    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5359        if (UserHandle.getCallingUserId() != userId) {
5360            mContext.enforceCallingPermission(
5361                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5362                    "isPermissionRevokedByPolicy for user " + userId);
5363        }
5364
5365        if (checkPermission(permission, packageName, userId)
5366                == PackageManager.PERMISSION_GRANTED) {
5367            return false;
5368        }
5369
5370        final int callingUid = Binder.getCallingUid();
5371        if (getInstantAppPackageName(callingUid) != null) {
5372            if (!isCallerSameApp(packageName, callingUid)) {
5373                return false;
5374            }
5375        } else {
5376            if (isInstantApp(packageName, userId)) {
5377                return false;
5378            }
5379        }
5380
5381        final long identity = Binder.clearCallingIdentity();
5382        try {
5383            final int flags = getPermissionFlags(permission, packageName, userId);
5384            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5385        } finally {
5386            Binder.restoreCallingIdentity(identity);
5387        }
5388    }
5389
5390    @Override
5391    public String getPermissionControllerPackageName() {
5392        synchronized (mPackages) {
5393            return mRequiredInstallerPackage;
5394        }
5395    }
5396
5397    /**
5398     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5399     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5400     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5401     * @param message the message to log on security exception
5402     */
5403    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5404            boolean checkShell, String message) {
5405        if (userId < 0) {
5406            throw new IllegalArgumentException("Invalid userId " + userId);
5407        }
5408        if (checkShell) {
5409            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5410        }
5411        if (userId == UserHandle.getUserId(callingUid)) return;
5412        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5413            if (requireFullPermission) {
5414                mContext.enforceCallingOrSelfPermission(
5415                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5416            } else {
5417                try {
5418                    mContext.enforceCallingOrSelfPermission(
5419                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5420                } catch (SecurityException se) {
5421                    mContext.enforceCallingOrSelfPermission(
5422                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5423                }
5424            }
5425        }
5426    }
5427
5428    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5429        if (callingUid == Process.SHELL_UID) {
5430            if (userHandle >= 0
5431                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5432                throw new SecurityException("Shell does not have permission to access user "
5433                        + userHandle);
5434            } else if (userHandle < 0) {
5435                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5436                        + Debug.getCallers(3));
5437            }
5438        }
5439    }
5440
5441    private BasePermission findPermissionTreeLP(String permName) {
5442        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5443            if (permName.startsWith(bp.name) &&
5444                    permName.length() > bp.name.length() &&
5445                    permName.charAt(bp.name.length()) == '.') {
5446                return bp;
5447            }
5448        }
5449        return null;
5450    }
5451
5452    private BasePermission checkPermissionTreeLP(String permName) {
5453        if (permName != null) {
5454            BasePermission bp = findPermissionTreeLP(permName);
5455            if (bp != null) {
5456                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5457                    return bp;
5458                }
5459                throw new SecurityException("Calling uid "
5460                        + Binder.getCallingUid()
5461                        + " is not allowed to add to permission tree "
5462                        + bp.name + " owned by uid " + bp.uid);
5463            }
5464        }
5465        throw new SecurityException("No permission tree found for " + permName);
5466    }
5467
5468    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5469        if (s1 == null) {
5470            return s2 == null;
5471        }
5472        if (s2 == null) {
5473            return false;
5474        }
5475        if (s1.getClass() != s2.getClass()) {
5476            return false;
5477        }
5478        return s1.equals(s2);
5479    }
5480
5481    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5482        if (pi1.icon != pi2.icon) return false;
5483        if (pi1.logo != pi2.logo) return false;
5484        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5485        if (!compareStrings(pi1.name, pi2.name)) return false;
5486        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5487        // We'll take care of setting this one.
5488        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5489        // These are not currently stored in settings.
5490        //if (!compareStrings(pi1.group, pi2.group)) return false;
5491        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5492        //if (pi1.labelRes != pi2.labelRes) return false;
5493        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5494        return true;
5495    }
5496
5497    int permissionInfoFootprint(PermissionInfo info) {
5498        int size = info.name.length();
5499        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5500        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5501        return size;
5502    }
5503
5504    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5505        int size = 0;
5506        for (BasePermission perm : mSettings.mPermissions.values()) {
5507            if (perm.uid == tree.uid) {
5508                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5509            }
5510        }
5511        return size;
5512    }
5513
5514    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5515        // We calculate the max size of permissions defined by this uid and throw
5516        // if that plus the size of 'info' would exceed our stated maximum.
5517        if (tree.uid != Process.SYSTEM_UID) {
5518            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5519            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5520                throw new SecurityException("Permission tree size cap exceeded");
5521            }
5522        }
5523    }
5524
5525    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5526        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5527            throw new SecurityException("Instant apps can't add permissions");
5528        }
5529        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5530            throw new SecurityException("Label must be specified in permission");
5531        }
5532        BasePermission tree = checkPermissionTreeLP(info.name);
5533        BasePermission bp = mSettings.mPermissions.get(info.name);
5534        boolean added = bp == null;
5535        boolean changed = true;
5536        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5537        if (added) {
5538            enforcePermissionCapLocked(info, tree);
5539            bp = new BasePermission(info.name, tree.sourcePackage,
5540                    BasePermission.TYPE_DYNAMIC);
5541        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5542            throw new SecurityException(
5543                    "Not allowed to modify non-dynamic permission "
5544                    + info.name);
5545        } else {
5546            if (bp.protectionLevel == fixedLevel
5547                    && bp.perm.owner.equals(tree.perm.owner)
5548                    && bp.uid == tree.uid
5549                    && comparePermissionInfos(bp.perm.info, info)) {
5550                changed = false;
5551            }
5552        }
5553        bp.protectionLevel = fixedLevel;
5554        info = new PermissionInfo(info);
5555        info.protectionLevel = fixedLevel;
5556        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5557        bp.perm.info.packageName = tree.perm.info.packageName;
5558        bp.uid = tree.uid;
5559        if (added) {
5560            mSettings.mPermissions.put(info.name, bp);
5561        }
5562        if (changed) {
5563            if (!async) {
5564                mSettings.writeLPr();
5565            } else {
5566                scheduleWriteSettingsLocked();
5567            }
5568        }
5569        return added;
5570    }
5571
5572    @Override
5573    public boolean addPermission(PermissionInfo info) {
5574        synchronized (mPackages) {
5575            return addPermissionLocked(info, false);
5576        }
5577    }
5578
5579    @Override
5580    public boolean addPermissionAsync(PermissionInfo info) {
5581        synchronized (mPackages) {
5582            return addPermissionLocked(info, true);
5583        }
5584    }
5585
5586    @Override
5587    public void removePermission(String name) {
5588        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5589            throw new SecurityException("Instant applications don't have access to this method");
5590        }
5591        synchronized (mPackages) {
5592            checkPermissionTreeLP(name);
5593            BasePermission bp = mSettings.mPermissions.get(name);
5594            if (bp != null) {
5595                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5596                    throw new SecurityException(
5597                            "Not allowed to modify non-dynamic permission "
5598                            + name);
5599                }
5600                mSettings.mPermissions.remove(name);
5601                mSettings.writeLPr();
5602            }
5603        }
5604    }
5605
5606    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5607            PackageParser.Package pkg, BasePermission bp) {
5608        int index = pkg.requestedPermissions.indexOf(bp.name);
5609        if (index == -1) {
5610            throw new SecurityException("Package " + pkg.packageName
5611                    + " has not requested permission " + bp.name);
5612        }
5613        if (!bp.isRuntime() && !bp.isDevelopment()) {
5614            throw new SecurityException("Permission " + bp.name
5615                    + " is not a changeable permission type");
5616        }
5617    }
5618
5619    @Override
5620    public void grantRuntimePermission(String packageName, String name, final int userId) {
5621        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5622    }
5623
5624    private void grantRuntimePermission(String packageName, String name, final int userId,
5625            boolean overridePolicy) {
5626        if (!sUserManager.exists(userId)) {
5627            Log.e(TAG, "No such user:" + userId);
5628            return;
5629        }
5630        final int callingUid = Binder.getCallingUid();
5631
5632        mContext.enforceCallingOrSelfPermission(
5633                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5634                "grantRuntimePermission");
5635
5636        enforceCrossUserPermission(callingUid, userId,
5637                true /* requireFullPermission */, true /* checkShell */,
5638                "grantRuntimePermission");
5639
5640        final int uid;
5641        final PackageSetting ps;
5642
5643        synchronized (mPackages) {
5644            final PackageParser.Package pkg = mPackages.get(packageName);
5645            if (pkg == null) {
5646                throw new IllegalArgumentException("Unknown package: " + packageName);
5647            }
5648            final BasePermission bp = mSettings.mPermissions.get(name);
5649            if (bp == null) {
5650                throw new IllegalArgumentException("Unknown permission: " + name);
5651            }
5652            ps = (PackageSetting) pkg.mExtras;
5653            if (ps == null
5654                    || filterAppAccessLPr(ps, callingUid, userId)) {
5655                throw new IllegalArgumentException("Unknown package: " + packageName);
5656            }
5657
5658            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5659
5660            // If a permission review is required for legacy apps we represent
5661            // their permissions as always granted runtime ones since we need
5662            // to keep the review required permission flag per user while an
5663            // install permission's state is shared across all users.
5664            if (mPermissionReviewRequired
5665                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5666                    && bp.isRuntime()) {
5667                return;
5668            }
5669
5670            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5671
5672            final PermissionsState permissionsState = ps.getPermissionsState();
5673
5674            final int flags = permissionsState.getPermissionFlags(name, userId);
5675            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5676                throw new SecurityException("Cannot grant system fixed permission "
5677                        + name + " for package " + packageName);
5678            }
5679            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5680                throw new SecurityException("Cannot grant policy fixed permission "
5681                        + name + " for package " + packageName);
5682            }
5683
5684            if (bp.isDevelopment()) {
5685                // Development permissions must be handled specially, since they are not
5686                // normal runtime permissions.  For now they apply to all users.
5687                if (permissionsState.grantInstallPermission(bp) !=
5688                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5689                    scheduleWriteSettingsLocked();
5690                }
5691                return;
5692            }
5693
5694            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5695                throw new SecurityException("Cannot grant non-ephemeral permission"
5696                        + name + " for package " + packageName);
5697            }
5698
5699            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5700                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5701                return;
5702            }
5703
5704            final int result = permissionsState.grantRuntimePermission(bp, userId);
5705            switch (result) {
5706                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5707                    return;
5708                }
5709
5710                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5711                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5712                    mHandler.post(new Runnable() {
5713                        @Override
5714                        public void run() {
5715                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5716                        }
5717                    });
5718                }
5719                break;
5720            }
5721
5722            if (bp.isRuntime()) {
5723                logPermissionGranted(mContext, name, packageName);
5724            }
5725
5726            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5727
5728            // Not critical if that is lost - app has to request again.
5729            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5730        }
5731
5732        // Only need to do this if user is initialized. Otherwise it's a new user
5733        // and there are no processes running as the user yet and there's no need
5734        // to make an expensive call to remount processes for the changed permissions.
5735        if (READ_EXTERNAL_STORAGE.equals(name)
5736                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5737            final long token = Binder.clearCallingIdentity();
5738            try {
5739                if (sUserManager.isInitialized(userId)) {
5740                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5741                            StorageManagerInternal.class);
5742                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5743                }
5744            } finally {
5745                Binder.restoreCallingIdentity(token);
5746            }
5747        }
5748    }
5749
5750    @Override
5751    public void revokeRuntimePermission(String packageName, String name, int userId) {
5752        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5753    }
5754
5755    private void revokeRuntimePermission(String packageName, String name, int userId,
5756            boolean overridePolicy) {
5757        if (!sUserManager.exists(userId)) {
5758            Log.e(TAG, "No such user:" + userId);
5759            return;
5760        }
5761
5762        mContext.enforceCallingOrSelfPermission(
5763                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5764                "revokeRuntimePermission");
5765
5766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5767                true /* requireFullPermission */, true /* checkShell */,
5768                "revokeRuntimePermission");
5769
5770        final int appId;
5771
5772        synchronized (mPackages) {
5773            final PackageParser.Package pkg = mPackages.get(packageName);
5774            if (pkg == null) {
5775                throw new IllegalArgumentException("Unknown package: " + packageName);
5776            }
5777            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5778            if (ps == null
5779                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5780                throw new IllegalArgumentException("Unknown package: " + packageName);
5781            }
5782            final BasePermission bp = mSettings.mPermissions.get(name);
5783            if (bp == null) {
5784                throw new IllegalArgumentException("Unknown permission: " + name);
5785            }
5786
5787            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5788
5789            // If a permission review is required for legacy apps we represent
5790            // their permissions as always granted runtime ones since we need
5791            // to keep the review required permission flag per user while an
5792            // install permission's state is shared across all users.
5793            if (mPermissionReviewRequired
5794                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5795                    && bp.isRuntime()) {
5796                return;
5797            }
5798
5799            final PermissionsState permissionsState = ps.getPermissionsState();
5800
5801            final int flags = permissionsState.getPermissionFlags(name, userId);
5802            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5803                throw new SecurityException("Cannot revoke system fixed permission "
5804                        + name + " for package " + packageName);
5805            }
5806            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5807                throw new SecurityException("Cannot revoke policy fixed permission "
5808                        + name + " for package " + packageName);
5809            }
5810
5811            if (bp.isDevelopment()) {
5812                // Development permissions must be handled specially, since they are not
5813                // normal runtime permissions.  For now they apply to all users.
5814                if (permissionsState.revokeInstallPermission(bp) !=
5815                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5816                    scheduleWriteSettingsLocked();
5817                }
5818                return;
5819            }
5820
5821            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5822                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5823                return;
5824            }
5825
5826            if (bp.isRuntime()) {
5827                logPermissionRevoked(mContext, name, packageName);
5828            }
5829
5830            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5831
5832            // Critical, after this call app should never have the permission.
5833            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5834
5835            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5836        }
5837
5838        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5839    }
5840
5841    /**
5842     * Get the first event id for the permission.
5843     *
5844     * <p>There are four events for each permission: <ul>
5845     *     <li>Request permission: first id + 0</li>
5846     *     <li>Grant permission: first id + 1</li>
5847     *     <li>Request for permission denied: first id + 2</li>
5848     *     <li>Revoke permission: first id + 3</li>
5849     * </ul></p>
5850     *
5851     * @param name name of the permission
5852     *
5853     * @return The first event id for the permission
5854     */
5855    private static int getBaseEventId(@NonNull String name) {
5856        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5857
5858        if (eventIdIndex == -1) {
5859            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5860                    || Build.IS_USER) {
5861                Log.i(TAG, "Unknown permission " + name);
5862
5863                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5864            } else {
5865                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5866                //
5867                // Also update
5868                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5869                // - metrics_constants.proto
5870                throw new IllegalStateException("Unknown permission " + name);
5871            }
5872        }
5873
5874        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5875    }
5876
5877    /**
5878     * Log that a permission was revoked.
5879     *
5880     * @param context Context of the caller
5881     * @param name name of the permission
5882     * @param packageName package permission if for
5883     */
5884    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5885            @NonNull String packageName) {
5886        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5887    }
5888
5889    /**
5890     * Log that a permission request was granted.
5891     *
5892     * @param context Context of the caller
5893     * @param name name of the permission
5894     * @param packageName package permission if for
5895     */
5896    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5897            @NonNull String packageName) {
5898        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5899    }
5900
5901    @Override
5902    public void resetRuntimePermissions() {
5903        mContext.enforceCallingOrSelfPermission(
5904                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5905                "revokeRuntimePermission");
5906
5907        int callingUid = Binder.getCallingUid();
5908        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5909            mContext.enforceCallingOrSelfPermission(
5910                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5911                    "resetRuntimePermissions");
5912        }
5913
5914        synchronized (mPackages) {
5915            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5916            for (int userId : UserManagerService.getInstance().getUserIds()) {
5917                final int packageCount = mPackages.size();
5918                for (int i = 0; i < packageCount; i++) {
5919                    PackageParser.Package pkg = mPackages.valueAt(i);
5920                    if (!(pkg.mExtras instanceof PackageSetting)) {
5921                        continue;
5922                    }
5923                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5924                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5925                }
5926            }
5927        }
5928    }
5929
5930    @Override
5931    public int getPermissionFlags(String name, String packageName, int userId) {
5932        if (!sUserManager.exists(userId)) {
5933            return 0;
5934        }
5935
5936        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5937
5938        final int callingUid = Binder.getCallingUid();
5939        enforceCrossUserPermission(callingUid, userId,
5940                true /* requireFullPermission */, false /* checkShell */,
5941                "getPermissionFlags");
5942
5943        synchronized (mPackages) {
5944            final PackageParser.Package pkg = mPackages.get(packageName);
5945            if (pkg == null) {
5946                return 0;
5947            }
5948            final BasePermission bp = mSettings.mPermissions.get(name);
5949            if (bp == null) {
5950                return 0;
5951            }
5952            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5953            if (ps == null
5954                    || filterAppAccessLPr(ps, callingUid, userId)) {
5955                return 0;
5956            }
5957            PermissionsState permissionsState = ps.getPermissionsState();
5958            return permissionsState.getPermissionFlags(name, userId);
5959        }
5960    }
5961
5962    @Override
5963    public void updatePermissionFlags(String name, String packageName, int flagMask,
5964            int flagValues, int userId) {
5965        if (!sUserManager.exists(userId)) {
5966            return;
5967        }
5968
5969        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5970
5971        final int callingUid = Binder.getCallingUid();
5972        enforceCrossUserPermission(callingUid, userId,
5973                true /* requireFullPermission */, true /* checkShell */,
5974                "updatePermissionFlags");
5975
5976        // Only the system can change these flags and nothing else.
5977        if (getCallingUid() != Process.SYSTEM_UID) {
5978            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5979            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5980            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5981            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5982            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5983        }
5984
5985        synchronized (mPackages) {
5986            final PackageParser.Package pkg = mPackages.get(packageName);
5987            if (pkg == null) {
5988                throw new IllegalArgumentException("Unknown package: " + packageName);
5989            }
5990            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5991            if (ps == null
5992                    || filterAppAccessLPr(ps, callingUid, userId)) {
5993                throw new IllegalArgumentException("Unknown package: " + packageName);
5994            }
5995
5996            final BasePermission bp = mSettings.mPermissions.get(name);
5997            if (bp == null) {
5998                throw new IllegalArgumentException("Unknown permission: " + name);
5999            }
6000
6001            PermissionsState permissionsState = ps.getPermissionsState();
6002
6003            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6004
6005            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6006                // Install and runtime permissions are stored in different places,
6007                // so figure out what permission changed and persist the change.
6008                if (permissionsState.getInstallPermissionState(name) != null) {
6009                    scheduleWriteSettingsLocked();
6010                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6011                        || hadState) {
6012                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6013                }
6014            }
6015        }
6016    }
6017
6018    /**
6019     * Update the permission flags for all packages and runtime permissions of a user in order
6020     * to allow device or profile owner to remove POLICY_FIXED.
6021     */
6022    @Override
6023    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6024        if (!sUserManager.exists(userId)) {
6025            return;
6026        }
6027
6028        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6029
6030        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6031                true /* requireFullPermission */, true /* checkShell */,
6032                "updatePermissionFlagsForAllApps");
6033
6034        // Only the system can change system fixed flags.
6035        if (getCallingUid() != Process.SYSTEM_UID) {
6036            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6037            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6038        }
6039
6040        synchronized (mPackages) {
6041            boolean changed = false;
6042            final int packageCount = mPackages.size();
6043            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6044                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6045                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6046                if (ps == null) {
6047                    continue;
6048                }
6049                PermissionsState permissionsState = ps.getPermissionsState();
6050                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6051                        userId, flagMask, flagValues);
6052            }
6053            if (changed) {
6054                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6055            }
6056        }
6057    }
6058
6059    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6060        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6061                != PackageManager.PERMISSION_GRANTED
6062            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6063                != PackageManager.PERMISSION_GRANTED) {
6064            throw new SecurityException(message + " requires "
6065                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6066                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6067        }
6068    }
6069
6070    @Override
6071    public boolean shouldShowRequestPermissionRationale(String permissionName,
6072            String packageName, int userId) {
6073        if (UserHandle.getCallingUserId() != userId) {
6074            mContext.enforceCallingPermission(
6075                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6076                    "canShowRequestPermissionRationale for user " + userId);
6077        }
6078
6079        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6080        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6081            return false;
6082        }
6083
6084        if (checkPermission(permissionName, packageName, userId)
6085                == PackageManager.PERMISSION_GRANTED) {
6086            return false;
6087        }
6088
6089        final int flags;
6090
6091        final long identity = Binder.clearCallingIdentity();
6092        try {
6093            flags = getPermissionFlags(permissionName,
6094                    packageName, userId);
6095        } finally {
6096            Binder.restoreCallingIdentity(identity);
6097        }
6098
6099        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6100                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6101                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6102
6103        if ((flags & fixedFlags) != 0) {
6104            return false;
6105        }
6106
6107        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6108    }
6109
6110    @Override
6111    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6112        mContext.enforceCallingOrSelfPermission(
6113                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6114                "addOnPermissionsChangeListener");
6115
6116        synchronized (mPackages) {
6117            mOnPermissionChangeListeners.addListenerLocked(listener);
6118        }
6119    }
6120
6121    @Override
6122    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6123        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6124            throw new SecurityException("Instant applications don't have access to this method");
6125        }
6126        synchronized (mPackages) {
6127            mOnPermissionChangeListeners.removeListenerLocked(listener);
6128        }
6129    }
6130
6131    @Override
6132    public boolean isProtectedBroadcast(String actionName) {
6133        // allow instant applications
6134        synchronized (mProtectedBroadcasts) {
6135            if (mProtectedBroadcasts.contains(actionName)) {
6136                return true;
6137            } else if (actionName != null) {
6138                // TODO: remove these terrible hacks
6139                if (actionName.startsWith("android.net.netmon.lingerExpired")
6140                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6141                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6142                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6143                    return true;
6144                }
6145            }
6146        }
6147        return false;
6148    }
6149
6150    @Override
6151    public int checkSignatures(String pkg1, String pkg2) {
6152        synchronized (mPackages) {
6153            final PackageParser.Package p1 = mPackages.get(pkg1);
6154            final PackageParser.Package p2 = mPackages.get(pkg2);
6155            if (p1 == null || p1.mExtras == null
6156                    || p2 == null || p2.mExtras == null) {
6157                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6158            }
6159            final int callingUid = Binder.getCallingUid();
6160            final int callingUserId = UserHandle.getUserId(callingUid);
6161            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6162            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6163            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6164                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6166            }
6167            return compareSignatures(p1.mSignatures, p2.mSignatures);
6168        }
6169    }
6170
6171    @Override
6172    public int checkUidSignatures(int uid1, int uid2) {
6173        final int callingUid = Binder.getCallingUid();
6174        final int callingUserId = UserHandle.getUserId(callingUid);
6175        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6176        // Map to base uids.
6177        uid1 = UserHandle.getAppId(uid1);
6178        uid2 = UserHandle.getAppId(uid2);
6179        // reader
6180        synchronized (mPackages) {
6181            Signature[] s1;
6182            Signature[] s2;
6183            Object obj = mSettings.getUserIdLPr(uid1);
6184            if (obj != null) {
6185                if (obj instanceof SharedUserSetting) {
6186                    if (isCallerInstantApp) {
6187                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6188                    }
6189                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6190                } else if (obj instanceof PackageSetting) {
6191                    final PackageSetting ps = (PackageSetting) obj;
6192                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6193                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6194                    }
6195                    s1 = ps.signatures.mSignatures;
6196                } else {
6197                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6198                }
6199            } else {
6200                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6201            }
6202            obj = mSettings.getUserIdLPr(uid2);
6203            if (obj != null) {
6204                if (obj instanceof SharedUserSetting) {
6205                    if (isCallerInstantApp) {
6206                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6207                    }
6208                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6209                } else if (obj instanceof PackageSetting) {
6210                    final PackageSetting ps = (PackageSetting) obj;
6211                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6212                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6213                    }
6214                    s2 = ps.signatures.mSignatures;
6215                } else {
6216                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6217                }
6218            } else {
6219                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6220            }
6221            return compareSignatures(s1, s2);
6222        }
6223    }
6224
6225    /**
6226     * This method should typically only be used when granting or revoking
6227     * permissions, since the app may immediately restart after this call.
6228     * <p>
6229     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6230     * guard your work against the app being relaunched.
6231     */
6232    private void killUid(int appId, int userId, String reason) {
6233        final long identity = Binder.clearCallingIdentity();
6234        try {
6235            IActivityManager am = ActivityManager.getService();
6236            if (am != null) {
6237                try {
6238                    am.killUid(appId, userId, reason);
6239                } catch (RemoteException e) {
6240                    /* ignore - same process */
6241                }
6242            }
6243        } finally {
6244            Binder.restoreCallingIdentity(identity);
6245        }
6246    }
6247
6248    /**
6249     * Compares two sets of signatures. Returns:
6250     * <br />
6251     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6252     * <br />
6253     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6254     * <br />
6255     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6256     * <br />
6257     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6258     * <br />
6259     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6260     */
6261    static int compareSignatures(Signature[] s1, Signature[] s2) {
6262        if (s1 == null) {
6263            return s2 == null
6264                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6265                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6266        }
6267
6268        if (s2 == null) {
6269            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6270        }
6271
6272        if (s1.length != s2.length) {
6273            return PackageManager.SIGNATURE_NO_MATCH;
6274        }
6275
6276        // Since both signature sets are of size 1, we can compare without HashSets.
6277        if (s1.length == 1) {
6278            return s1[0].equals(s2[0]) ?
6279                    PackageManager.SIGNATURE_MATCH :
6280                    PackageManager.SIGNATURE_NO_MATCH;
6281        }
6282
6283        ArraySet<Signature> set1 = new ArraySet<Signature>();
6284        for (Signature sig : s1) {
6285            set1.add(sig);
6286        }
6287        ArraySet<Signature> set2 = new ArraySet<Signature>();
6288        for (Signature sig : s2) {
6289            set2.add(sig);
6290        }
6291        // Make sure s2 contains all signatures in s1.
6292        if (set1.equals(set2)) {
6293            return PackageManager.SIGNATURE_MATCH;
6294        }
6295        return PackageManager.SIGNATURE_NO_MATCH;
6296    }
6297
6298    /**
6299     * If the database version for this type of package (internal storage or
6300     * external storage) is less than the version where package signatures
6301     * were updated, return true.
6302     */
6303    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6304        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6305        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6306    }
6307
6308    /**
6309     * Used for backward compatibility to make sure any packages with
6310     * certificate chains get upgraded to the new style. {@code existingSigs}
6311     * will be in the old format (since they were stored on disk from before the
6312     * system upgrade) and {@code scannedSigs} will be in the newer format.
6313     */
6314    private int compareSignaturesCompat(PackageSignatures existingSigs,
6315            PackageParser.Package scannedPkg) {
6316        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6317            return PackageManager.SIGNATURE_NO_MATCH;
6318        }
6319
6320        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6321        for (Signature sig : existingSigs.mSignatures) {
6322            existingSet.add(sig);
6323        }
6324        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6325        for (Signature sig : scannedPkg.mSignatures) {
6326            try {
6327                Signature[] chainSignatures = sig.getChainSignatures();
6328                for (Signature chainSig : chainSignatures) {
6329                    scannedCompatSet.add(chainSig);
6330                }
6331            } catch (CertificateEncodingException e) {
6332                scannedCompatSet.add(sig);
6333            }
6334        }
6335        /*
6336         * Make sure the expanded scanned set contains all signatures in the
6337         * existing one.
6338         */
6339        if (scannedCompatSet.equals(existingSet)) {
6340            // Migrate the old signatures to the new scheme.
6341            existingSigs.assignSignatures(scannedPkg.mSignatures);
6342            // The new KeySets will be re-added later in the scanning process.
6343            synchronized (mPackages) {
6344                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6345            }
6346            return PackageManager.SIGNATURE_MATCH;
6347        }
6348        return PackageManager.SIGNATURE_NO_MATCH;
6349    }
6350
6351    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6352        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6353        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6354    }
6355
6356    private int compareSignaturesRecover(PackageSignatures existingSigs,
6357            PackageParser.Package scannedPkg) {
6358        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6359            return PackageManager.SIGNATURE_NO_MATCH;
6360        }
6361
6362        String msg = null;
6363        try {
6364            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6365                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6366                        + scannedPkg.packageName);
6367                return PackageManager.SIGNATURE_MATCH;
6368            }
6369        } catch (CertificateException e) {
6370            msg = e.getMessage();
6371        }
6372
6373        logCriticalInfo(Log.INFO,
6374                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6375        return PackageManager.SIGNATURE_NO_MATCH;
6376    }
6377
6378    @Override
6379    public List<String> getAllPackages() {
6380        final int callingUid = Binder.getCallingUid();
6381        final int callingUserId = UserHandle.getUserId(callingUid);
6382        synchronized (mPackages) {
6383            if (canViewInstantApps(callingUid, callingUserId)) {
6384                return new ArrayList<String>(mPackages.keySet());
6385            }
6386            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6387            final List<String> result = new ArrayList<>();
6388            if (instantAppPkgName != null) {
6389                // caller is an instant application; filter unexposed applications
6390                for (PackageParser.Package pkg : mPackages.values()) {
6391                    if (!pkg.visibleToInstantApps) {
6392                        continue;
6393                    }
6394                    result.add(pkg.packageName);
6395                }
6396            } else {
6397                // caller is a normal application; filter instant applications
6398                for (PackageParser.Package pkg : mPackages.values()) {
6399                    final PackageSetting ps =
6400                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6401                    if (ps != null
6402                            && ps.getInstantApp(callingUserId)
6403                            && !mInstantAppRegistry.isInstantAccessGranted(
6404                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6405                        continue;
6406                    }
6407                    result.add(pkg.packageName);
6408                }
6409            }
6410            return result;
6411        }
6412    }
6413
6414    @Override
6415    public String[] getPackagesForUid(int uid) {
6416        final int callingUid = Binder.getCallingUid();
6417        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6418        final int userId = UserHandle.getUserId(uid);
6419        uid = UserHandle.getAppId(uid);
6420        // reader
6421        synchronized (mPackages) {
6422            Object obj = mSettings.getUserIdLPr(uid);
6423            if (obj instanceof SharedUserSetting) {
6424                if (isCallerInstantApp) {
6425                    return null;
6426                }
6427                final SharedUserSetting sus = (SharedUserSetting) obj;
6428                final int N = sus.packages.size();
6429                String[] res = new String[N];
6430                final Iterator<PackageSetting> it = sus.packages.iterator();
6431                int i = 0;
6432                while (it.hasNext()) {
6433                    PackageSetting ps = it.next();
6434                    if (ps.getInstalled(userId)) {
6435                        res[i++] = ps.name;
6436                    } else {
6437                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6438                    }
6439                }
6440                return res;
6441            } else if (obj instanceof PackageSetting) {
6442                final PackageSetting ps = (PackageSetting) obj;
6443                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6444                    return new String[]{ps.name};
6445                }
6446            }
6447        }
6448        return null;
6449    }
6450
6451    @Override
6452    public String getNameForUid(int uid) {
6453        final int callingUid = Binder.getCallingUid();
6454        if (getInstantAppPackageName(callingUid) != null) {
6455            return null;
6456        }
6457        synchronized (mPackages) {
6458            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6459            if (obj instanceof SharedUserSetting) {
6460                final SharedUserSetting sus = (SharedUserSetting) obj;
6461                return sus.name + ":" + sus.userId;
6462            } else if (obj instanceof PackageSetting) {
6463                final PackageSetting ps = (PackageSetting) obj;
6464                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6465                    return null;
6466                }
6467                return ps.name;
6468            }
6469            return null;
6470        }
6471    }
6472
6473    @Override
6474    public String[] getNamesForUids(int[] uids) {
6475        if (uids == null || uids.length == 0) {
6476            return null;
6477        }
6478        final int callingUid = Binder.getCallingUid();
6479        if (getInstantAppPackageName(callingUid) != null) {
6480            return null;
6481        }
6482        final String[] names = new String[uids.length];
6483        synchronized (mPackages) {
6484            for (int i = uids.length - 1; i >= 0; i--) {
6485                final int uid = uids[i];
6486                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6487                if (obj instanceof SharedUserSetting) {
6488                    final SharedUserSetting sus = (SharedUserSetting) obj;
6489                    names[i] = "shared:" + sus.name;
6490                } else if (obj instanceof PackageSetting) {
6491                    final PackageSetting ps = (PackageSetting) obj;
6492                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6493                        names[i] = null;
6494                    } else {
6495                        names[i] = ps.name;
6496                    }
6497                } else {
6498                    names[i] = null;
6499                }
6500            }
6501        }
6502        return names;
6503    }
6504
6505    @Override
6506    public int getUidForSharedUser(String sharedUserName) {
6507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6508            return -1;
6509        }
6510        if (sharedUserName == null) {
6511            return -1;
6512        }
6513        // reader
6514        synchronized (mPackages) {
6515            SharedUserSetting suid;
6516            try {
6517                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6518                if (suid != null) {
6519                    return suid.userId;
6520                }
6521            } catch (PackageManagerException ignore) {
6522                // can't happen, but, still need to catch it
6523            }
6524            return -1;
6525        }
6526    }
6527
6528    @Override
6529    public int getFlagsForUid(int uid) {
6530        final int callingUid = Binder.getCallingUid();
6531        if (getInstantAppPackageName(callingUid) != null) {
6532            return 0;
6533        }
6534        synchronized (mPackages) {
6535            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6536            if (obj instanceof SharedUserSetting) {
6537                final SharedUserSetting sus = (SharedUserSetting) obj;
6538                return sus.pkgFlags;
6539            } else if (obj instanceof PackageSetting) {
6540                final PackageSetting ps = (PackageSetting) obj;
6541                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6542                    return 0;
6543                }
6544                return ps.pkgFlags;
6545            }
6546        }
6547        return 0;
6548    }
6549
6550    @Override
6551    public int getPrivateFlagsForUid(int uid) {
6552        final int callingUid = Binder.getCallingUid();
6553        if (getInstantAppPackageName(callingUid) != null) {
6554            return 0;
6555        }
6556        synchronized (mPackages) {
6557            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6558            if (obj instanceof SharedUserSetting) {
6559                final SharedUserSetting sus = (SharedUserSetting) obj;
6560                return sus.pkgPrivateFlags;
6561            } else if (obj instanceof PackageSetting) {
6562                final PackageSetting ps = (PackageSetting) obj;
6563                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6564                    return 0;
6565                }
6566                return ps.pkgPrivateFlags;
6567            }
6568        }
6569        return 0;
6570    }
6571
6572    @Override
6573    public boolean isUidPrivileged(int uid) {
6574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6575            return false;
6576        }
6577        uid = UserHandle.getAppId(uid);
6578        // reader
6579        synchronized (mPackages) {
6580            Object obj = mSettings.getUserIdLPr(uid);
6581            if (obj instanceof SharedUserSetting) {
6582                final SharedUserSetting sus = (SharedUserSetting) obj;
6583                final Iterator<PackageSetting> it = sus.packages.iterator();
6584                while (it.hasNext()) {
6585                    if (it.next().isPrivileged()) {
6586                        return true;
6587                    }
6588                }
6589            } else if (obj instanceof PackageSetting) {
6590                final PackageSetting ps = (PackageSetting) obj;
6591                return ps.isPrivileged();
6592            }
6593        }
6594        return false;
6595    }
6596
6597    @Override
6598    public String[] getAppOpPermissionPackages(String permissionName) {
6599        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6600            return null;
6601        }
6602        synchronized (mPackages) {
6603            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6604            if (pkgs == null) {
6605                return null;
6606            }
6607            return pkgs.toArray(new String[pkgs.size()]);
6608        }
6609    }
6610
6611    @Override
6612    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6613            int flags, int userId) {
6614        return resolveIntentInternal(
6615                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6616    }
6617
6618    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6619            int flags, int userId, boolean resolveForStart) {
6620        try {
6621            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6622
6623            if (!sUserManager.exists(userId)) return null;
6624            final int callingUid = Binder.getCallingUid();
6625            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6626            enforceCrossUserPermission(callingUid, userId,
6627                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6628
6629            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6630            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6631                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6633
6634            final ResolveInfo bestChoice =
6635                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6636            return bestChoice;
6637        } finally {
6638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6639        }
6640    }
6641
6642    @Override
6643    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6644        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6645            throw new SecurityException(
6646                    "findPersistentPreferredActivity can only be run by the system");
6647        }
6648        if (!sUserManager.exists(userId)) {
6649            return null;
6650        }
6651        final int callingUid = Binder.getCallingUid();
6652        intent = updateIntentForResolve(intent);
6653        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6654        final int flags = updateFlagsForResolve(
6655                0, userId, intent, callingUid, false /*includeInstantApps*/);
6656        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6657                userId);
6658        synchronized (mPackages) {
6659            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6660                    userId);
6661        }
6662    }
6663
6664    @Override
6665    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6666            IntentFilter filter, int match, ComponentName activity) {
6667        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6668            return;
6669        }
6670        final int userId = UserHandle.getCallingUserId();
6671        if (DEBUG_PREFERRED) {
6672            Log.v(TAG, "setLastChosenActivity intent=" + intent
6673                + " resolvedType=" + resolvedType
6674                + " flags=" + flags
6675                + " filter=" + filter
6676                + " match=" + match
6677                + " activity=" + activity);
6678            filter.dump(new PrintStreamPrinter(System.out), "    ");
6679        }
6680        intent.setComponent(null);
6681        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6682                userId);
6683        // Find any earlier preferred or last chosen entries and nuke them
6684        findPreferredActivity(intent, resolvedType,
6685                flags, query, 0, false, true, false, userId);
6686        // Add the new activity as the last chosen for this filter
6687        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6688                "Setting last chosen");
6689    }
6690
6691    @Override
6692    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6693        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6694            return null;
6695        }
6696        final int userId = UserHandle.getCallingUserId();
6697        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6698        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6699                userId);
6700        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6701                false, false, false, userId);
6702    }
6703
6704    /**
6705     * Returns whether or not instant apps have been disabled remotely.
6706     */
6707    private boolean isEphemeralDisabled() {
6708        return mEphemeralAppsDisabled;
6709    }
6710
6711    private boolean isInstantAppAllowed(
6712            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6713            boolean skipPackageCheck) {
6714        if (mInstantAppResolverConnection == null) {
6715            return false;
6716        }
6717        if (mInstantAppInstallerActivity == null) {
6718            return false;
6719        }
6720        if (intent.getComponent() != null) {
6721            return false;
6722        }
6723        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6724            return false;
6725        }
6726        if (!skipPackageCheck && intent.getPackage() != null) {
6727            return false;
6728        }
6729        final boolean isWebUri = hasWebURI(intent);
6730        if (!isWebUri || intent.getData().getHost() == null) {
6731            return false;
6732        }
6733        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6734        // Or if there's already an ephemeral app installed that handles the action
6735        synchronized (mPackages) {
6736            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6737            for (int n = 0; n < count; n++) {
6738                final ResolveInfo info = resolvedActivities.get(n);
6739                final String packageName = info.activityInfo.packageName;
6740                final PackageSetting ps = mSettings.mPackages.get(packageName);
6741                if (ps != null) {
6742                    // only check domain verification status if the app is not a browser
6743                    if (!info.handleAllWebDataURI) {
6744                        // Try to get the status from User settings first
6745                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6746                        final int status = (int) (packedStatus >> 32);
6747                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6748                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6749                            if (DEBUG_EPHEMERAL) {
6750                                Slog.v(TAG, "DENY instant app;"
6751                                    + " pkg: " + packageName + ", status: " + status);
6752                            }
6753                            return false;
6754                        }
6755                    }
6756                    if (ps.getInstantApp(userId)) {
6757                        if (DEBUG_EPHEMERAL) {
6758                            Slog.v(TAG, "DENY instant app installed;"
6759                                    + " pkg: " + packageName);
6760                        }
6761                        return false;
6762                    }
6763                }
6764            }
6765        }
6766        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6767        return true;
6768    }
6769
6770    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6771            Intent origIntent, String resolvedType, String callingPackage,
6772            Bundle verificationBundle, int userId) {
6773        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6774                new InstantAppRequest(responseObj, origIntent, resolvedType,
6775                        callingPackage, userId, verificationBundle));
6776        mHandler.sendMessage(msg);
6777    }
6778
6779    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6780            int flags, List<ResolveInfo> query, int userId) {
6781        if (query != null) {
6782            final int N = query.size();
6783            if (N == 1) {
6784                return query.get(0);
6785            } else if (N > 1) {
6786                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6787                // If there is more than one activity with the same priority,
6788                // then let the user decide between them.
6789                ResolveInfo r0 = query.get(0);
6790                ResolveInfo r1 = query.get(1);
6791                if (DEBUG_INTENT_MATCHING || debug) {
6792                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6793                            + r1.activityInfo.name + "=" + r1.priority);
6794                }
6795                // If the first activity has a higher priority, or a different
6796                // default, then it is always desirable to pick it.
6797                if (r0.priority != r1.priority
6798                        || r0.preferredOrder != r1.preferredOrder
6799                        || r0.isDefault != r1.isDefault) {
6800                    return query.get(0);
6801                }
6802                // If we have saved a preference for a preferred activity for
6803                // this Intent, use that.
6804                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6805                        flags, query, r0.priority, true, false, debug, userId);
6806                if (ri != null) {
6807                    return ri;
6808                }
6809                // If we have an ephemeral app, use it
6810                for (int i = 0; i < N; i++) {
6811                    ri = query.get(i);
6812                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6813                        final String packageName = ri.activityInfo.packageName;
6814                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6815                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6816                        final int status = (int)(packedStatus >> 32);
6817                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6818                            return ri;
6819                        }
6820                    }
6821                }
6822                ri = new ResolveInfo(mResolveInfo);
6823                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6824                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6825                // If all of the options come from the same package, show the application's
6826                // label and icon instead of the generic resolver's.
6827                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6828                // and then throw away the ResolveInfo itself, meaning that the caller loses
6829                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6830                // a fallback for this case; we only set the target package's resources on
6831                // the ResolveInfo, not the ActivityInfo.
6832                final String intentPackage = intent.getPackage();
6833                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6834                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6835                    ri.resolvePackageName = intentPackage;
6836                    if (userNeedsBadging(userId)) {
6837                        ri.noResourceId = true;
6838                    } else {
6839                        ri.icon = appi.icon;
6840                    }
6841                    ri.iconResourceId = appi.icon;
6842                    ri.labelRes = appi.labelRes;
6843                }
6844                ri.activityInfo.applicationInfo = new ApplicationInfo(
6845                        ri.activityInfo.applicationInfo);
6846                if (userId != 0) {
6847                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6848                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6849                }
6850                // Make sure that the resolver is displayable in car mode
6851                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6852                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6853                return ri;
6854            }
6855        }
6856        return null;
6857    }
6858
6859    /**
6860     * Return true if the given list is not empty and all of its contents have
6861     * an activityInfo with the given package name.
6862     */
6863    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6864        if (ArrayUtils.isEmpty(list)) {
6865            return false;
6866        }
6867        for (int i = 0, N = list.size(); i < N; i++) {
6868            final ResolveInfo ri = list.get(i);
6869            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6870            if (ai == null || !packageName.equals(ai.packageName)) {
6871                return false;
6872            }
6873        }
6874        return true;
6875    }
6876
6877    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6878            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6879        final int N = query.size();
6880        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6881                .get(userId);
6882        // Get the list of persistent preferred activities that handle the intent
6883        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6884        List<PersistentPreferredActivity> pprefs = ppir != null
6885                ? ppir.queryIntent(intent, resolvedType,
6886                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6887                        userId)
6888                : null;
6889        if (pprefs != null && pprefs.size() > 0) {
6890            final int M = pprefs.size();
6891            for (int i=0; i<M; i++) {
6892                final PersistentPreferredActivity ppa = pprefs.get(i);
6893                if (DEBUG_PREFERRED || debug) {
6894                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6895                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6896                            + "\n  component=" + ppa.mComponent);
6897                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6898                }
6899                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6900                        flags | MATCH_DISABLED_COMPONENTS, userId);
6901                if (DEBUG_PREFERRED || debug) {
6902                    Slog.v(TAG, "Found persistent preferred activity:");
6903                    if (ai != null) {
6904                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6905                    } else {
6906                        Slog.v(TAG, "  null");
6907                    }
6908                }
6909                if (ai == null) {
6910                    // This previously registered persistent preferred activity
6911                    // component is no longer known. Ignore it and do NOT remove it.
6912                    continue;
6913                }
6914                for (int j=0; j<N; j++) {
6915                    final ResolveInfo ri = query.get(j);
6916                    if (!ri.activityInfo.applicationInfo.packageName
6917                            .equals(ai.applicationInfo.packageName)) {
6918                        continue;
6919                    }
6920                    if (!ri.activityInfo.name.equals(ai.name)) {
6921                        continue;
6922                    }
6923                    //  Found a persistent preference that can handle the intent.
6924                    if (DEBUG_PREFERRED || debug) {
6925                        Slog.v(TAG, "Returning persistent preferred activity: " +
6926                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6927                    }
6928                    return ri;
6929                }
6930            }
6931        }
6932        return null;
6933    }
6934
6935    // TODO: handle preferred activities missing while user has amnesia
6936    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6937            List<ResolveInfo> query, int priority, boolean always,
6938            boolean removeMatches, boolean debug, int userId) {
6939        if (!sUserManager.exists(userId)) return null;
6940        final int callingUid = Binder.getCallingUid();
6941        flags = updateFlagsForResolve(
6942                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6943        intent = updateIntentForResolve(intent);
6944        // writer
6945        synchronized (mPackages) {
6946            // Try to find a matching persistent preferred activity.
6947            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6948                    debug, userId);
6949
6950            // If a persistent preferred activity matched, use it.
6951            if (pri != null) {
6952                return pri;
6953            }
6954
6955            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6956            // Get the list of preferred activities that handle the intent
6957            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6958            List<PreferredActivity> prefs = pir != null
6959                    ? pir.queryIntent(intent, resolvedType,
6960                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6961                            userId)
6962                    : null;
6963            if (prefs != null && prefs.size() > 0) {
6964                boolean changed = false;
6965                try {
6966                    // First figure out how good the original match set is.
6967                    // We will only allow preferred activities that came
6968                    // from the same match quality.
6969                    int match = 0;
6970
6971                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6972
6973                    final int N = query.size();
6974                    for (int j=0; j<N; j++) {
6975                        final ResolveInfo ri = query.get(j);
6976                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6977                                + ": 0x" + Integer.toHexString(match));
6978                        if (ri.match > match) {
6979                            match = ri.match;
6980                        }
6981                    }
6982
6983                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6984                            + Integer.toHexString(match));
6985
6986                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6987                    final int M = prefs.size();
6988                    for (int i=0; i<M; i++) {
6989                        final PreferredActivity pa = prefs.get(i);
6990                        if (DEBUG_PREFERRED || debug) {
6991                            Slog.v(TAG, "Checking PreferredActivity ds="
6992                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6993                                    + "\n  component=" + pa.mPref.mComponent);
6994                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6995                        }
6996                        if (pa.mPref.mMatch != match) {
6997                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6998                                    + Integer.toHexString(pa.mPref.mMatch));
6999                            continue;
7000                        }
7001                        // If it's not an "always" type preferred activity and that's what we're
7002                        // looking for, skip it.
7003                        if (always && !pa.mPref.mAlways) {
7004                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7005                            continue;
7006                        }
7007                        final ActivityInfo ai = getActivityInfo(
7008                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7009                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7010                                userId);
7011                        if (DEBUG_PREFERRED || debug) {
7012                            Slog.v(TAG, "Found preferred activity:");
7013                            if (ai != null) {
7014                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7015                            } else {
7016                                Slog.v(TAG, "  null");
7017                            }
7018                        }
7019                        if (ai == null) {
7020                            // This previously registered preferred activity
7021                            // component is no longer known.  Most likely an update
7022                            // to the app was installed and in the new version this
7023                            // component no longer exists.  Clean it up by removing
7024                            // it from the preferred activities list, and skip it.
7025                            Slog.w(TAG, "Removing dangling preferred activity: "
7026                                    + pa.mPref.mComponent);
7027                            pir.removeFilter(pa);
7028                            changed = true;
7029                            continue;
7030                        }
7031                        for (int j=0; j<N; j++) {
7032                            final ResolveInfo ri = query.get(j);
7033                            if (!ri.activityInfo.applicationInfo.packageName
7034                                    .equals(ai.applicationInfo.packageName)) {
7035                                continue;
7036                            }
7037                            if (!ri.activityInfo.name.equals(ai.name)) {
7038                                continue;
7039                            }
7040
7041                            if (removeMatches) {
7042                                pir.removeFilter(pa);
7043                                changed = true;
7044                                if (DEBUG_PREFERRED) {
7045                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7046                                }
7047                                break;
7048                            }
7049
7050                            // Okay we found a previously set preferred or last chosen app.
7051                            // If the result set is different from when this
7052                            // was created, and is not a subset of the preferred set, we need to
7053                            // clear it and re-ask the user their preference, if we're looking for
7054                            // an "always" type entry.
7055                            if (always && !pa.mPref.sameSet(query)) {
7056                                if (pa.mPref.isSuperset(query)) {
7057                                    // some components of the set are no longer present in
7058                                    // the query, but the preferred activity can still be reused
7059                                    if (DEBUG_PREFERRED) {
7060                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7061                                                + " still valid as only non-preferred components"
7062                                                + " were removed for " + intent + " type "
7063                                                + resolvedType);
7064                                    }
7065                                    // remove obsolete components and re-add the up-to-date filter
7066                                    PreferredActivity freshPa = new PreferredActivity(pa,
7067                                            pa.mPref.mMatch,
7068                                            pa.mPref.discardObsoleteComponents(query),
7069                                            pa.mPref.mComponent,
7070                                            pa.mPref.mAlways);
7071                                    pir.removeFilter(pa);
7072                                    pir.addFilter(freshPa);
7073                                    changed = true;
7074                                } else {
7075                                    Slog.i(TAG,
7076                                            "Result set changed, dropping preferred activity for "
7077                                                    + intent + " type " + resolvedType);
7078                                    if (DEBUG_PREFERRED) {
7079                                        Slog.v(TAG, "Removing preferred activity since set changed "
7080                                                + pa.mPref.mComponent);
7081                                    }
7082                                    pir.removeFilter(pa);
7083                                    // Re-add the filter as a "last chosen" entry (!always)
7084                                    PreferredActivity lastChosen = new PreferredActivity(
7085                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7086                                    pir.addFilter(lastChosen);
7087                                    changed = true;
7088                                    return null;
7089                                }
7090                            }
7091
7092                            // Yay! Either the set matched or we're looking for the last chosen
7093                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7094                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7095                            return ri;
7096                        }
7097                    }
7098                } finally {
7099                    if (changed) {
7100                        if (DEBUG_PREFERRED) {
7101                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7102                        }
7103                        scheduleWritePackageRestrictionsLocked(userId);
7104                    }
7105                }
7106            }
7107        }
7108        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7109        return null;
7110    }
7111
7112    /*
7113     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7114     */
7115    @Override
7116    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7117            int targetUserId) {
7118        mContext.enforceCallingOrSelfPermission(
7119                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7120        List<CrossProfileIntentFilter> matches =
7121                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7122        if (matches != null) {
7123            int size = matches.size();
7124            for (int i = 0; i < size; i++) {
7125                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7126            }
7127        }
7128        if (hasWebURI(intent)) {
7129            // cross-profile app linking works only towards the parent.
7130            final int callingUid = Binder.getCallingUid();
7131            final UserInfo parent = getProfileParent(sourceUserId);
7132            synchronized(mPackages) {
7133                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7134                        false /*includeInstantApps*/);
7135                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7136                        intent, resolvedType, flags, sourceUserId, parent.id);
7137                return xpDomainInfo != null;
7138            }
7139        }
7140        return false;
7141    }
7142
7143    private UserInfo getProfileParent(int userId) {
7144        final long identity = Binder.clearCallingIdentity();
7145        try {
7146            return sUserManager.getProfileParent(userId);
7147        } finally {
7148            Binder.restoreCallingIdentity(identity);
7149        }
7150    }
7151
7152    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7153            String resolvedType, int userId) {
7154        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7155        if (resolver != null) {
7156            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7157        }
7158        return null;
7159    }
7160
7161    @Override
7162    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7163            String resolvedType, int flags, int userId) {
7164        try {
7165            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7166
7167            return new ParceledListSlice<>(
7168                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7169        } finally {
7170            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7171        }
7172    }
7173
7174    /**
7175     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7176     * instant, returns {@code null}.
7177     */
7178    private String getInstantAppPackageName(int callingUid) {
7179        synchronized (mPackages) {
7180            // If the caller is an isolated app use the owner's uid for the lookup.
7181            if (Process.isIsolated(callingUid)) {
7182                callingUid = mIsolatedOwners.get(callingUid);
7183            }
7184            final int appId = UserHandle.getAppId(callingUid);
7185            final Object obj = mSettings.getUserIdLPr(appId);
7186            if (obj instanceof PackageSetting) {
7187                final PackageSetting ps = (PackageSetting) obj;
7188                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7189                return isInstantApp ? ps.pkg.packageName : null;
7190            }
7191        }
7192        return null;
7193    }
7194
7195    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7196            String resolvedType, int flags, int userId) {
7197        return queryIntentActivitiesInternal(
7198                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7199                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7200    }
7201
7202    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7203            String resolvedType, int flags, int filterCallingUid, int userId,
7204            boolean resolveForStart, boolean allowDynamicSplits) {
7205        if (!sUserManager.exists(userId)) return Collections.emptyList();
7206        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7208                false /* requireFullPermission */, false /* checkShell */,
7209                "query intent activities");
7210        final String pkgName = intent.getPackage();
7211        ComponentName comp = intent.getComponent();
7212        if (comp == null) {
7213            if (intent.getSelector() != null) {
7214                intent = intent.getSelector();
7215                comp = intent.getComponent();
7216            }
7217        }
7218
7219        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7220                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7221        if (comp != null) {
7222            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7223            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7224            if (ai != null) {
7225                // When specifying an explicit component, we prevent the activity from being
7226                // used when either 1) the calling package is normal and the activity is within
7227                // an ephemeral application or 2) the calling package is ephemeral and the
7228                // activity is not visible to ephemeral applications.
7229                final boolean matchInstantApp =
7230                        (flags & PackageManager.MATCH_INSTANT) != 0;
7231                final boolean matchVisibleToInstantAppOnly =
7232                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7233                final boolean matchExplicitlyVisibleOnly =
7234                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7235                final boolean isCallerInstantApp =
7236                        instantAppPkgName != null;
7237                final boolean isTargetSameInstantApp =
7238                        comp.getPackageName().equals(instantAppPkgName);
7239                final boolean isTargetInstantApp =
7240                        (ai.applicationInfo.privateFlags
7241                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7242                final boolean isTargetVisibleToInstantApp =
7243                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7244                final boolean isTargetExplicitlyVisibleToInstantApp =
7245                        isTargetVisibleToInstantApp
7246                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7247                final boolean isTargetHiddenFromInstantApp =
7248                        !isTargetVisibleToInstantApp
7249                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7250                final boolean blockResolution =
7251                        !isTargetSameInstantApp
7252                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7253                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7254                                        && isTargetHiddenFromInstantApp));
7255                if (!blockResolution) {
7256                    final ResolveInfo ri = new ResolveInfo();
7257                    ri.activityInfo = ai;
7258                    list.add(ri);
7259                }
7260            }
7261            return applyPostResolutionFilter(
7262                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7263        }
7264
7265        // reader
7266        boolean sortResult = false;
7267        boolean addEphemeral = false;
7268        List<ResolveInfo> result;
7269        final boolean ephemeralDisabled = isEphemeralDisabled();
7270        synchronized (mPackages) {
7271            if (pkgName == null) {
7272                List<CrossProfileIntentFilter> matchingFilters =
7273                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7274                // Check for results that need to skip the current profile.
7275                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7276                        resolvedType, flags, userId);
7277                if (xpResolveInfo != null) {
7278                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7279                    xpResult.add(xpResolveInfo);
7280                    return applyPostResolutionFilter(
7281                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7282                            allowDynamicSplits, filterCallingUid, userId);
7283                }
7284
7285                // Check for results in the current profile.
7286                result = filterIfNotSystemUser(mActivities.queryIntent(
7287                        intent, resolvedType, flags, userId), userId);
7288                addEphemeral = !ephemeralDisabled
7289                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7290                // Check for cross profile results.
7291                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7292                xpResolveInfo = queryCrossProfileIntents(
7293                        matchingFilters, intent, resolvedType, flags, userId,
7294                        hasNonNegativePriorityResult);
7295                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7296                    boolean isVisibleToUser = filterIfNotSystemUser(
7297                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7298                    if (isVisibleToUser) {
7299                        result.add(xpResolveInfo);
7300                        sortResult = true;
7301                    }
7302                }
7303                if (hasWebURI(intent)) {
7304                    CrossProfileDomainInfo xpDomainInfo = null;
7305                    final UserInfo parent = getProfileParent(userId);
7306                    if (parent != null) {
7307                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7308                                flags, userId, parent.id);
7309                    }
7310                    if (xpDomainInfo != null) {
7311                        if (xpResolveInfo != null) {
7312                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7313                            // in the result.
7314                            result.remove(xpResolveInfo);
7315                        }
7316                        if (result.size() == 0 && !addEphemeral) {
7317                            // No result in current profile, but found candidate in parent user.
7318                            // And we are not going to add emphemeral app, so we can return the
7319                            // result straight away.
7320                            result.add(xpDomainInfo.resolveInfo);
7321                            return applyPostResolutionFilter(result, instantAppPkgName,
7322                                    allowDynamicSplits, filterCallingUid, userId);
7323                        }
7324                    } else if (result.size() <= 1 && !addEphemeral) {
7325                        // No result in parent user and <= 1 result in current profile, and we
7326                        // are not going to add emphemeral app, so we can return the result without
7327                        // further processing.
7328                        return applyPostResolutionFilter(result, instantAppPkgName,
7329                                allowDynamicSplits, filterCallingUid, userId);
7330                    }
7331                    // We have more than one candidate (combining results from current and parent
7332                    // profile), so we need filtering and sorting.
7333                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7334                            intent, flags, result, xpDomainInfo, userId);
7335                    sortResult = true;
7336                }
7337            } else {
7338                final PackageParser.Package pkg = mPackages.get(pkgName);
7339                result = null;
7340                if (pkg != null) {
7341                    result = filterIfNotSystemUser(
7342                            mActivities.queryIntentForPackage(
7343                                    intent, resolvedType, flags, pkg.activities, userId),
7344                            userId);
7345                }
7346                if (result == null || result.size() == 0) {
7347                    // the caller wants to resolve for a particular package; however, there
7348                    // were no installed results, so, try to find an ephemeral result
7349                    addEphemeral = !ephemeralDisabled
7350                            && isInstantAppAllowed(
7351                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7352                    if (result == null) {
7353                        result = new ArrayList<>();
7354                    }
7355                }
7356            }
7357        }
7358        if (addEphemeral) {
7359            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7360        }
7361        if (sortResult) {
7362            Collections.sort(result, mResolvePrioritySorter);
7363        }
7364        return applyPostResolutionFilter(
7365                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7366    }
7367
7368    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7369            String resolvedType, int flags, int userId) {
7370        // first, check to see if we've got an instant app already installed
7371        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7372        ResolveInfo localInstantApp = null;
7373        boolean blockResolution = false;
7374        if (!alreadyResolvedLocally) {
7375            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7376                    flags
7377                        | PackageManager.GET_RESOLVED_FILTER
7378                        | PackageManager.MATCH_INSTANT
7379                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7380                    userId);
7381            for (int i = instantApps.size() - 1; i >= 0; --i) {
7382                final ResolveInfo info = instantApps.get(i);
7383                final String packageName = info.activityInfo.packageName;
7384                final PackageSetting ps = mSettings.mPackages.get(packageName);
7385                if (ps.getInstantApp(userId)) {
7386                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7387                    final int status = (int)(packedStatus >> 32);
7388                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7389                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7390                        // there's a local instant application installed, but, the user has
7391                        // chosen to never use it; skip resolution and don't acknowledge
7392                        // an instant application is even available
7393                        if (DEBUG_EPHEMERAL) {
7394                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7395                        }
7396                        blockResolution = true;
7397                        break;
7398                    } else {
7399                        // we have a locally installed instant application; skip resolution
7400                        // but acknowledge there's an instant application available
7401                        if (DEBUG_EPHEMERAL) {
7402                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7403                        }
7404                        localInstantApp = info;
7405                        break;
7406                    }
7407                }
7408            }
7409        }
7410        // no app installed, let's see if one's available
7411        AuxiliaryResolveInfo auxiliaryResponse = null;
7412        if (!blockResolution) {
7413            if (localInstantApp == null) {
7414                // we don't have an instant app locally, resolve externally
7415                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7416                final InstantAppRequest requestObject = new InstantAppRequest(
7417                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7418                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7419                auxiliaryResponse =
7420                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7421                                mContext, mInstantAppResolverConnection, requestObject);
7422                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7423            } else {
7424                // we have an instant application locally, but, we can't admit that since
7425                // callers shouldn't be able to determine prior browsing. create a dummy
7426                // auxiliary response so the downstream code behaves as if there's an
7427                // instant application available externally. when it comes time to start
7428                // the instant application, we'll do the right thing.
7429                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7430                auxiliaryResponse = new AuxiliaryResolveInfo(
7431                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7432                        ai.versionCode, null /*failureIntent*/);
7433            }
7434        }
7435        if (auxiliaryResponse != null) {
7436            if (DEBUG_EPHEMERAL) {
7437                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7438            }
7439            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7440            final PackageSetting ps =
7441                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7442            if (ps != null) {
7443                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7444                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7445                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7446                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7447                // make sure this resolver is the default
7448                ephemeralInstaller.isDefault = true;
7449                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7450                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7451                // add a non-generic filter
7452                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7453                ephemeralInstaller.filter.addDataPath(
7454                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7455                ephemeralInstaller.isInstantAppAvailable = true;
7456                result.add(ephemeralInstaller);
7457            }
7458        }
7459        return result;
7460    }
7461
7462    private static class CrossProfileDomainInfo {
7463        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7464        ResolveInfo resolveInfo;
7465        /* Best domain verification status of the activities found in the other profile */
7466        int bestDomainVerificationStatus;
7467    }
7468
7469    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7470            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7471        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7472                sourceUserId)) {
7473            return null;
7474        }
7475        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7476                resolvedType, flags, parentUserId);
7477
7478        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7479            return null;
7480        }
7481        CrossProfileDomainInfo result = null;
7482        int size = resultTargetUser.size();
7483        for (int i = 0; i < size; i++) {
7484            ResolveInfo riTargetUser = resultTargetUser.get(i);
7485            // Intent filter verification is only for filters that specify a host. So don't return
7486            // those that handle all web uris.
7487            if (riTargetUser.handleAllWebDataURI) {
7488                continue;
7489            }
7490            String packageName = riTargetUser.activityInfo.packageName;
7491            PackageSetting ps = mSettings.mPackages.get(packageName);
7492            if (ps == null) {
7493                continue;
7494            }
7495            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7496            int status = (int)(verificationState >> 32);
7497            if (result == null) {
7498                result = new CrossProfileDomainInfo();
7499                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7500                        sourceUserId, parentUserId);
7501                result.bestDomainVerificationStatus = status;
7502            } else {
7503                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7504                        result.bestDomainVerificationStatus);
7505            }
7506        }
7507        // Don't consider matches with status NEVER across profiles.
7508        if (result != null && result.bestDomainVerificationStatus
7509                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7510            return null;
7511        }
7512        return result;
7513    }
7514
7515    /**
7516     * Verification statuses are ordered from the worse to the best, except for
7517     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7518     */
7519    private int bestDomainVerificationStatus(int status1, int status2) {
7520        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7521            return status2;
7522        }
7523        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7524            return status1;
7525        }
7526        return (int) MathUtils.max(status1, status2);
7527    }
7528
7529    private boolean isUserEnabled(int userId) {
7530        long callingId = Binder.clearCallingIdentity();
7531        try {
7532            UserInfo userInfo = sUserManager.getUserInfo(userId);
7533            return userInfo != null && userInfo.isEnabled();
7534        } finally {
7535            Binder.restoreCallingIdentity(callingId);
7536        }
7537    }
7538
7539    /**
7540     * Filter out activities with systemUserOnly flag set, when current user is not System.
7541     *
7542     * @return filtered list
7543     */
7544    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7545        if (userId == UserHandle.USER_SYSTEM) {
7546            return resolveInfos;
7547        }
7548        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7549            ResolveInfo info = resolveInfos.get(i);
7550            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7551                resolveInfos.remove(i);
7552            }
7553        }
7554        return resolveInfos;
7555    }
7556
7557    /**
7558     * Filters out ephemeral activities.
7559     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7560     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7561     *
7562     * @param resolveInfos The pre-filtered list of resolved activities
7563     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7564     *          is performed.
7565     * @return A filtered list of resolved activities.
7566     */
7567    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7568            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7569        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7570            final ResolveInfo info = resolveInfos.get(i);
7571            // allow activities that are defined in the provided package
7572            if (allowDynamicSplits
7573                    && info.activityInfo.splitName != null
7574                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7575                            info.activityInfo.splitName)) {
7576                // requested activity is defined in a split that hasn't been installed yet.
7577                // add the installer to the resolve list
7578                if (DEBUG_INSTALL) {
7579                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7580                }
7581                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7582                final ComponentName installFailureActivity = findInstallFailureActivity(
7583                        info.activityInfo.packageName,  filterCallingUid, userId);
7584                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7585                        info.activityInfo.packageName, info.activityInfo.splitName,
7586                        installFailureActivity,
7587                        info.activityInfo.applicationInfo.versionCode,
7588                        null /*failureIntent*/);
7589                // make sure this resolver is the default
7590                installerInfo.isDefault = true;
7591                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7592                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7593                // add a non-generic filter
7594                installerInfo.filter = new IntentFilter();
7595                // load resources from the correct package
7596                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7597                resolveInfos.set(i, installerInfo);
7598                continue;
7599            }
7600            // caller is a full app, don't need to apply any other filtering
7601            if (ephemeralPkgName == null) {
7602                continue;
7603            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7604                // caller is same app; don't need to apply any other filtering
7605                continue;
7606            }
7607            // allow activities that have been explicitly exposed to ephemeral apps
7608            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7609            if (!isEphemeralApp
7610                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7611                continue;
7612            }
7613            resolveInfos.remove(i);
7614        }
7615        return resolveInfos;
7616    }
7617
7618    /**
7619     * Returns the activity component that can handle install failures.
7620     * <p>By default, the instant application installer handles failures. However, an
7621     * application may want to handle failures on its own. Applications do this by
7622     * creating an activity with an intent filter that handles the action
7623     * {@link Intent#ACTION_INSTALL_FAILURE}.
7624     */
7625    private @Nullable ComponentName findInstallFailureActivity(
7626            String packageName, int filterCallingUid, int userId) {
7627        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7628        failureActivityIntent.setPackage(packageName);
7629        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7630        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7631                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7632                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7633        final int NR = result.size();
7634        if (NR > 0) {
7635            for (int i = 0; i < NR; i++) {
7636                final ResolveInfo info = result.get(i);
7637                if (info.activityInfo.splitName != null) {
7638                    continue;
7639                }
7640                return new ComponentName(packageName, info.activityInfo.name);
7641            }
7642        }
7643        return null;
7644    }
7645
7646    /**
7647     * @param resolveInfos list of resolve infos in descending priority order
7648     * @return if the list contains a resolve info with non-negative priority
7649     */
7650    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7651        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7652    }
7653
7654    private static boolean hasWebURI(Intent intent) {
7655        if (intent.getData() == null) {
7656            return false;
7657        }
7658        final String scheme = intent.getScheme();
7659        if (TextUtils.isEmpty(scheme)) {
7660            return false;
7661        }
7662        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7663    }
7664
7665    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7666            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7667            int userId) {
7668        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7669
7670        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7671            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7672                    candidates.size());
7673        }
7674
7675        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7676        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7677        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7678        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7679        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7680        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7681
7682        synchronized (mPackages) {
7683            final int count = candidates.size();
7684            // First, try to use linked apps. Partition the candidates into four lists:
7685            // one for the final results, one for the "do not use ever", one for "undefined status"
7686            // and finally one for "browser app type".
7687            for (int n=0; n<count; n++) {
7688                ResolveInfo info = candidates.get(n);
7689                String packageName = info.activityInfo.packageName;
7690                PackageSetting ps = mSettings.mPackages.get(packageName);
7691                if (ps != null) {
7692                    // Add to the special match all list (Browser use case)
7693                    if (info.handleAllWebDataURI) {
7694                        matchAllList.add(info);
7695                        continue;
7696                    }
7697                    // Try to get the status from User settings first
7698                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7699                    int status = (int)(packedStatus >> 32);
7700                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7701                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7702                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7703                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7704                                    + " : linkgen=" + linkGeneration);
7705                        }
7706                        // Use link-enabled generation as preferredOrder, i.e.
7707                        // prefer newly-enabled over earlier-enabled.
7708                        info.preferredOrder = linkGeneration;
7709                        alwaysList.add(info);
7710                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7711                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7712                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7713                        }
7714                        neverList.add(info);
7715                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7716                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7717                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7718                        }
7719                        alwaysAskList.add(info);
7720                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7721                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7722                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7723                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7724                        }
7725                        undefinedList.add(info);
7726                    }
7727                }
7728            }
7729
7730            // We'll want to include browser possibilities in a few cases
7731            boolean includeBrowser = false;
7732
7733            // First try to add the "always" resolution(s) for the current user, if any
7734            if (alwaysList.size() > 0) {
7735                result.addAll(alwaysList);
7736            } else {
7737                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7738                result.addAll(undefinedList);
7739                // Maybe add one for the other profile.
7740                if (xpDomainInfo != null && (
7741                        xpDomainInfo.bestDomainVerificationStatus
7742                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7743                    result.add(xpDomainInfo.resolveInfo);
7744                }
7745                includeBrowser = true;
7746            }
7747
7748            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7749            // If there were 'always' entries their preferred order has been set, so we also
7750            // back that off to make the alternatives equivalent
7751            if (alwaysAskList.size() > 0) {
7752                for (ResolveInfo i : result) {
7753                    i.preferredOrder = 0;
7754                }
7755                result.addAll(alwaysAskList);
7756                includeBrowser = true;
7757            }
7758
7759            if (includeBrowser) {
7760                // Also add browsers (all of them or only the default one)
7761                if (DEBUG_DOMAIN_VERIFICATION) {
7762                    Slog.v(TAG, "   ...including browsers in candidate set");
7763                }
7764                if ((matchFlags & MATCH_ALL) != 0) {
7765                    result.addAll(matchAllList);
7766                } else {
7767                    // Browser/generic handling case.  If there's a default browser, go straight
7768                    // to that (but only if there is no other higher-priority match).
7769                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7770                    int maxMatchPrio = 0;
7771                    ResolveInfo defaultBrowserMatch = null;
7772                    final int numCandidates = matchAllList.size();
7773                    for (int n = 0; n < numCandidates; n++) {
7774                        ResolveInfo info = matchAllList.get(n);
7775                        // track the highest overall match priority...
7776                        if (info.priority > maxMatchPrio) {
7777                            maxMatchPrio = info.priority;
7778                        }
7779                        // ...and the highest-priority default browser match
7780                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7781                            if (defaultBrowserMatch == null
7782                                    || (defaultBrowserMatch.priority < info.priority)) {
7783                                if (debug) {
7784                                    Slog.v(TAG, "Considering default browser match " + info);
7785                                }
7786                                defaultBrowserMatch = info;
7787                            }
7788                        }
7789                    }
7790                    if (defaultBrowserMatch != null
7791                            && defaultBrowserMatch.priority >= maxMatchPrio
7792                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7793                    {
7794                        if (debug) {
7795                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7796                        }
7797                        result.add(defaultBrowserMatch);
7798                    } else {
7799                        result.addAll(matchAllList);
7800                    }
7801                }
7802
7803                // If there is nothing selected, add all candidates and remove the ones that the user
7804                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7805                if (result.size() == 0) {
7806                    result.addAll(candidates);
7807                    result.removeAll(neverList);
7808                }
7809            }
7810        }
7811        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7812            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7813                    result.size());
7814            for (ResolveInfo info : result) {
7815                Slog.v(TAG, "  + " + info.activityInfo);
7816            }
7817        }
7818        return result;
7819    }
7820
7821    // Returns a packed value as a long:
7822    //
7823    // high 'int'-sized word: link status: undefined/ask/never/always.
7824    // low 'int'-sized word: relative priority among 'always' results.
7825    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7826        long result = ps.getDomainVerificationStatusForUser(userId);
7827        // if none available, get the master status
7828        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7829            if (ps.getIntentFilterVerificationInfo() != null) {
7830                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7831            }
7832        }
7833        return result;
7834    }
7835
7836    private ResolveInfo querySkipCurrentProfileIntents(
7837            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7838            int flags, int sourceUserId) {
7839        if (matchingFilters != null) {
7840            int size = matchingFilters.size();
7841            for (int i = 0; i < size; i ++) {
7842                CrossProfileIntentFilter filter = matchingFilters.get(i);
7843                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7844                    // Checking if there are activities in the target user that can handle the
7845                    // intent.
7846                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7847                            resolvedType, flags, sourceUserId);
7848                    if (resolveInfo != null) {
7849                        return resolveInfo;
7850                    }
7851                }
7852            }
7853        }
7854        return null;
7855    }
7856
7857    // Return matching ResolveInfo in target user if any.
7858    private ResolveInfo queryCrossProfileIntents(
7859            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7860            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7861        if (matchingFilters != null) {
7862            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7863            // match the same intent. For performance reasons, it is better not to
7864            // run queryIntent twice for the same userId
7865            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7866            int size = matchingFilters.size();
7867            for (int i = 0; i < size; i++) {
7868                CrossProfileIntentFilter filter = matchingFilters.get(i);
7869                int targetUserId = filter.getTargetUserId();
7870                boolean skipCurrentProfile =
7871                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7872                boolean skipCurrentProfileIfNoMatchFound =
7873                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7874                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7875                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7876                    // Checking if there are activities in the target user that can handle the
7877                    // intent.
7878                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7879                            resolvedType, flags, sourceUserId);
7880                    if (resolveInfo != null) return resolveInfo;
7881                    alreadyTriedUserIds.put(targetUserId, true);
7882                }
7883            }
7884        }
7885        return null;
7886    }
7887
7888    /**
7889     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7890     * will forward the intent to the filter's target user.
7891     * Otherwise, returns null.
7892     */
7893    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7894            String resolvedType, int flags, int sourceUserId) {
7895        int targetUserId = filter.getTargetUserId();
7896        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7897                resolvedType, flags, targetUserId);
7898        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7899            // If all the matches in the target profile are suspended, return null.
7900            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7901                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7902                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7903                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7904                            targetUserId);
7905                }
7906            }
7907        }
7908        return null;
7909    }
7910
7911    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7912            int sourceUserId, int targetUserId) {
7913        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7914        long ident = Binder.clearCallingIdentity();
7915        boolean targetIsProfile;
7916        try {
7917            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7918        } finally {
7919            Binder.restoreCallingIdentity(ident);
7920        }
7921        String className;
7922        if (targetIsProfile) {
7923            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7924        } else {
7925            className = FORWARD_INTENT_TO_PARENT;
7926        }
7927        ComponentName forwardingActivityComponentName = new ComponentName(
7928                mAndroidApplication.packageName, className);
7929        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7930                sourceUserId);
7931        if (!targetIsProfile) {
7932            forwardingActivityInfo.showUserIcon = targetUserId;
7933            forwardingResolveInfo.noResourceId = true;
7934        }
7935        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7936        forwardingResolveInfo.priority = 0;
7937        forwardingResolveInfo.preferredOrder = 0;
7938        forwardingResolveInfo.match = 0;
7939        forwardingResolveInfo.isDefault = true;
7940        forwardingResolveInfo.filter = filter;
7941        forwardingResolveInfo.targetUserId = targetUserId;
7942        return forwardingResolveInfo;
7943    }
7944
7945    @Override
7946    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7947            Intent[] specifics, String[] specificTypes, Intent intent,
7948            String resolvedType, int flags, int userId) {
7949        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7950                specificTypes, intent, resolvedType, flags, userId));
7951    }
7952
7953    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7954            Intent[] specifics, String[] specificTypes, Intent intent,
7955            String resolvedType, int flags, int userId) {
7956        if (!sUserManager.exists(userId)) return Collections.emptyList();
7957        final int callingUid = Binder.getCallingUid();
7958        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7959                false /*includeInstantApps*/);
7960        enforceCrossUserPermission(callingUid, userId,
7961                false /*requireFullPermission*/, false /*checkShell*/,
7962                "query intent activity options");
7963        final String resultsAction = intent.getAction();
7964
7965        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7966                | PackageManager.GET_RESOLVED_FILTER, userId);
7967
7968        if (DEBUG_INTENT_MATCHING) {
7969            Log.v(TAG, "Query " + intent + ": " + results);
7970        }
7971
7972        int specificsPos = 0;
7973        int N;
7974
7975        // todo: note that the algorithm used here is O(N^2).  This
7976        // isn't a problem in our current environment, but if we start running
7977        // into situations where we have more than 5 or 10 matches then this
7978        // should probably be changed to something smarter...
7979
7980        // First we go through and resolve each of the specific items
7981        // that were supplied, taking care of removing any corresponding
7982        // duplicate items in the generic resolve list.
7983        if (specifics != null) {
7984            for (int i=0; i<specifics.length; i++) {
7985                final Intent sintent = specifics[i];
7986                if (sintent == null) {
7987                    continue;
7988                }
7989
7990                if (DEBUG_INTENT_MATCHING) {
7991                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7992                }
7993
7994                String action = sintent.getAction();
7995                if (resultsAction != null && resultsAction.equals(action)) {
7996                    // If this action was explicitly requested, then don't
7997                    // remove things that have it.
7998                    action = null;
7999                }
8000
8001                ResolveInfo ri = null;
8002                ActivityInfo ai = null;
8003
8004                ComponentName comp = sintent.getComponent();
8005                if (comp == null) {
8006                    ri = resolveIntent(
8007                        sintent,
8008                        specificTypes != null ? specificTypes[i] : null,
8009                            flags, userId);
8010                    if (ri == null) {
8011                        continue;
8012                    }
8013                    if (ri == mResolveInfo) {
8014                        // ACK!  Must do something better with this.
8015                    }
8016                    ai = ri.activityInfo;
8017                    comp = new ComponentName(ai.applicationInfo.packageName,
8018                            ai.name);
8019                } else {
8020                    ai = getActivityInfo(comp, flags, userId);
8021                    if (ai == null) {
8022                        continue;
8023                    }
8024                }
8025
8026                // Look for any generic query activities that are duplicates
8027                // of this specific one, and remove them from the results.
8028                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8029                N = results.size();
8030                int j;
8031                for (j=specificsPos; j<N; j++) {
8032                    ResolveInfo sri = results.get(j);
8033                    if ((sri.activityInfo.name.equals(comp.getClassName())
8034                            && sri.activityInfo.applicationInfo.packageName.equals(
8035                                    comp.getPackageName()))
8036                        || (action != null && sri.filter.matchAction(action))) {
8037                        results.remove(j);
8038                        if (DEBUG_INTENT_MATCHING) Log.v(
8039                            TAG, "Removing duplicate item from " + j
8040                            + " due to specific " + specificsPos);
8041                        if (ri == null) {
8042                            ri = sri;
8043                        }
8044                        j--;
8045                        N--;
8046                    }
8047                }
8048
8049                // Add this specific item to its proper place.
8050                if (ri == null) {
8051                    ri = new ResolveInfo();
8052                    ri.activityInfo = ai;
8053                }
8054                results.add(specificsPos, ri);
8055                ri.specificIndex = i;
8056                specificsPos++;
8057            }
8058        }
8059
8060        // Now we go through the remaining generic results and remove any
8061        // duplicate actions that are found here.
8062        N = results.size();
8063        for (int i=specificsPos; i<N-1; i++) {
8064            final ResolveInfo rii = results.get(i);
8065            if (rii.filter == null) {
8066                continue;
8067            }
8068
8069            // Iterate over all of the actions of this result's intent
8070            // filter...  typically this should be just one.
8071            final Iterator<String> it = rii.filter.actionsIterator();
8072            if (it == null) {
8073                continue;
8074            }
8075            while (it.hasNext()) {
8076                final String action = it.next();
8077                if (resultsAction != null && resultsAction.equals(action)) {
8078                    // If this action was explicitly requested, then don't
8079                    // remove things that have it.
8080                    continue;
8081                }
8082                for (int j=i+1; j<N; j++) {
8083                    final ResolveInfo rij = results.get(j);
8084                    if (rij.filter != null && rij.filter.hasAction(action)) {
8085                        results.remove(j);
8086                        if (DEBUG_INTENT_MATCHING) Log.v(
8087                            TAG, "Removing duplicate item from " + j
8088                            + " due to action " + action + " at " + i);
8089                        j--;
8090                        N--;
8091                    }
8092                }
8093            }
8094
8095            // If the caller didn't request filter information, drop it now
8096            // so we don't have to marshall/unmarshall it.
8097            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8098                rii.filter = null;
8099            }
8100        }
8101
8102        // Filter out the caller activity if so requested.
8103        if (caller != null) {
8104            N = results.size();
8105            for (int i=0; i<N; i++) {
8106                ActivityInfo ainfo = results.get(i).activityInfo;
8107                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8108                        && caller.getClassName().equals(ainfo.name)) {
8109                    results.remove(i);
8110                    break;
8111                }
8112            }
8113        }
8114
8115        // If the caller didn't request filter information,
8116        // drop them now so we don't have to
8117        // marshall/unmarshall it.
8118        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8119            N = results.size();
8120            for (int i=0; i<N; i++) {
8121                results.get(i).filter = null;
8122            }
8123        }
8124
8125        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8126        return results;
8127    }
8128
8129    @Override
8130    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8131            String resolvedType, int flags, int userId) {
8132        return new ParceledListSlice<>(
8133                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8134                        false /*allowDynamicSplits*/));
8135    }
8136
8137    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8138            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8139        if (!sUserManager.exists(userId)) return Collections.emptyList();
8140        final int callingUid = Binder.getCallingUid();
8141        enforceCrossUserPermission(callingUid, userId,
8142                false /*requireFullPermission*/, false /*checkShell*/,
8143                "query intent receivers");
8144        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8145        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8146                false /*includeInstantApps*/);
8147        ComponentName comp = intent.getComponent();
8148        if (comp == null) {
8149            if (intent.getSelector() != null) {
8150                intent = intent.getSelector();
8151                comp = intent.getComponent();
8152            }
8153        }
8154        if (comp != null) {
8155            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8156            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8157            if (ai != null) {
8158                // When specifying an explicit component, we prevent the activity from being
8159                // used when either 1) the calling package is normal and the activity is within
8160                // an instant application or 2) the calling package is ephemeral and the
8161                // activity is not visible to instant applications.
8162                final boolean matchInstantApp =
8163                        (flags & PackageManager.MATCH_INSTANT) != 0;
8164                final boolean matchVisibleToInstantAppOnly =
8165                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8166                final boolean matchExplicitlyVisibleOnly =
8167                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8168                final boolean isCallerInstantApp =
8169                        instantAppPkgName != null;
8170                final boolean isTargetSameInstantApp =
8171                        comp.getPackageName().equals(instantAppPkgName);
8172                final boolean isTargetInstantApp =
8173                        (ai.applicationInfo.privateFlags
8174                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8175                final boolean isTargetVisibleToInstantApp =
8176                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8177                final boolean isTargetExplicitlyVisibleToInstantApp =
8178                        isTargetVisibleToInstantApp
8179                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8180                final boolean isTargetHiddenFromInstantApp =
8181                        !isTargetVisibleToInstantApp
8182                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8183                final boolean blockResolution =
8184                        !isTargetSameInstantApp
8185                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8186                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8187                                        && isTargetHiddenFromInstantApp));
8188                if (!blockResolution) {
8189                    ResolveInfo ri = new ResolveInfo();
8190                    ri.activityInfo = ai;
8191                    list.add(ri);
8192                }
8193            }
8194            return applyPostResolutionFilter(
8195                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8196        }
8197
8198        // reader
8199        synchronized (mPackages) {
8200            String pkgName = intent.getPackage();
8201            if (pkgName == null) {
8202                final List<ResolveInfo> result =
8203                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8204                return applyPostResolutionFilter(
8205                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8206            }
8207            final PackageParser.Package pkg = mPackages.get(pkgName);
8208            if (pkg != null) {
8209                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8210                        intent, resolvedType, flags, pkg.receivers, userId);
8211                return applyPostResolutionFilter(
8212                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8213            }
8214            return Collections.emptyList();
8215        }
8216    }
8217
8218    @Override
8219    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8220        final int callingUid = Binder.getCallingUid();
8221        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8222    }
8223
8224    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8225            int userId, int callingUid) {
8226        if (!sUserManager.exists(userId)) return null;
8227        flags = updateFlagsForResolve(
8228                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8229        List<ResolveInfo> query = queryIntentServicesInternal(
8230                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8231        if (query != null) {
8232            if (query.size() >= 1) {
8233                // If there is more than one service with the same priority,
8234                // just arbitrarily pick the first one.
8235                return query.get(0);
8236            }
8237        }
8238        return null;
8239    }
8240
8241    @Override
8242    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8243            String resolvedType, int flags, int userId) {
8244        final int callingUid = Binder.getCallingUid();
8245        return new ParceledListSlice<>(queryIntentServicesInternal(
8246                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8247    }
8248
8249    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8250            String resolvedType, int flags, int userId, int callingUid,
8251            boolean includeInstantApps) {
8252        if (!sUserManager.exists(userId)) return Collections.emptyList();
8253        enforceCrossUserPermission(callingUid, userId,
8254                false /*requireFullPermission*/, false /*checkShell*/,
8255                "query intent receivers");
8256        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8257        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8258        ComponentName comp = intent.getComponent();
8259        if (comp == null) {
8260            if (intent.getSelector() != null) {
8261                intent = intent.getSelector();
8262                comp = intent.getComponent();
8263            }
8264        }
8265        if (comp != null) {
8266            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8267            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8268            if (si != null) {
8269                // When specifying an explicit component, we prevent the service from being
8270                // used when either 1) the service is in an instant application and the
8271                // caller is not the same instant application or 2) the calling package is
8272                // ephemeral and the activity is not visible to ephemeral applications.
8273                final boolean matchInstantApp =
8274                        (flags & PackageManager.MATCH_INSTANT) != 0;
8275                final boolean matchVisibleToInstantAppOnly =
8276                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8277                final boolean isCallerInstantApp =
8278                        instantAppPkgName != null;
8279                final boolean isTargetSameInstantApp =
8280                        comp.getPackageName().equals(instantAppPkgName);
8281                final boolean isTargetInstantApp =
8282                        (si.applicationInfo.privateFlags
8283                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8284                final boolean isTargetHiddenFromInstantApp =
8285                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8286                final boolean blockResolution =
8287                        !isTargetSameInstantApp
8288                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8289                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8290                                        && isTargetHiddenFromInstantApp));
8291                if (!blockResolution) {
8292                    final ResolveInfo ri = new ResolveInfo();
8293                    ri.serviceInfo = si;
8294                    list.add(ri);
8295                }
8296            }
8297            return list;
8298        }
8299
8300        // reader
8301        synchronized (mPackages) {
8302            String pkgName = intent.getPackage();
8303            if (pkgName == null) {
8304                return applyPostServiceResolutionFilter(
8305                        mServices.queryIntent(intent, resolvedType, flags, userId),
8306                        instantAppPkgName);
8307            }
8308            final PackageParser.Package pkg = mPackages.get(pkgName);
8309            if (pkg != null) {
8310                return applyPostServiceResolutionFilter(
8311                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8312                                userId),
8313                        instantAppPkgName);
8314            }
8315            return Collections.emptyList();
8316        }
8317    }
8318
8319    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8320            String instantAppPkgName) {
8321        if (instantAppPkgName == null) {
8322            return resolveInfos;
8323        }
8324        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8325            final ResolveInfo info = resolveInfos.get(i);
8326            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8327            // allow services that are defined in the provided package
8328            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8329                if (info.serviceInfo.splitName != null
8330                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8331                                info.serviceInfo.splitName)) {
8332                    // requested service is defined in a split that hasn't been installed yet.
8333                    // add the installer to the resolve list
8334                    if (DEBUG_EPHEMERAL) {
8335                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8336                    }
8337                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8338                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8339                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8340                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8341                            null /*failureIntent*/);
8342                    // make sure this resolver is the default
8343                    installerInfo.isDefault = true;
8344                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8345                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8346                    // add a non-generic filter
8347                    installerInfo.filter = new IntentFilter();
8348                    // load resources from the correct package
8349                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8350                    resolveInfos.set(i, installerInfo);
8351                }
8352                continue;
8353            }
8354            // allow services that have been explicitly exposed to ephemeral apps
8355            if (!isEphemeralApp
8356                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8357                continue;
8358            }
8359            resolveInfos.remove(i);
8360        }
8361        return resolveInfos;
8362    }
8363
8364    @Override
8365    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8366            String resolvedType, int flags, int userId) {
8367        return new ParceledListSlice<>(
8368                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8369    }
8370
8371    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8372            Intent intent, String resolvedType, int flags, int userId) {
8373        if (!sUserManager.exists(userId)) return Collections.emptyList();
8374        final int callingUid = Binder.getCallingUid();
8375        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8376        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8377                false /*includeInstantApps*/);
8378        ComponentName comp = intent.getComponent();
8379        if (comp == null) {
8380            if (intent.getSelector() != null) {
8381                intent = intent.getSelector();
8382                comp = intent.getComponent();
8383            }
8384        }
8385        if (comp != null) {
8386            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8387            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8388            if (pi != null) {
8389                // When specifying an explicit component, we prevent the provider from being
8390                // used when either 1) the provider is in an instant application and the
8391                // caller is not the same instant application or 2) the calling package is an
8392                // instant application and the provider is not visible to instant applications.
8393                final boolean matchInstantApp =
8394                        (flags & PackageManager.MATCH_INSTANT) != 0;
8395                final boolean matchVisibleToInstantAppOnly =
8396                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8397                final boolean isCallerInstantApp =
8398                        instantAppPkgName != null;
8399                final boolean isTargetSameInstantApp =
8400                        comp.getPackageName().equals(instantAppPkgName);
8401                final boolean isTargetInstantApp =
8402                        (pi.applicationInfo.privateFlags
8403                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8404                final boolean isTargetHiddenFromInstantApp =
8405                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8406                final boolean blockResolution =
8407                        !isTargetSameInstantApp
8408                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8409                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8410                                        && isTargetHiddenFromInstantApp));
8411                if (!blockResolution) {
8412                    final ResolveInfo ri = new ResolveInfo();
8413                    ri.providerInfo = pi;
8414                    list.add(ri);
8415                }
8416            }
8417            return list;
8418        }
8419
8420        // reader
8421        synchronized (mPackages) {
8422            String pkgName = intent.getPackage();
8423            if (pkgName == null) {
8424                return applyPostContentProviderResolutionFilter(
8425                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8426                        instantAppPkgName);
8427            }
8428            final PackageParser.Package pkg = mPackages.get(pkgName);
8429            if (pkg != null) {
8430                return applyPostContentProviderResolutionFilter(
8431                        mProviders.queryIntentForPackage(
8432                        intent, resolvedType, flags, pkg.providers, userId),
8433                        instantAppPkgName);
8434            }
8435            return Collections.emptyList();
8436        }
8437    }
8438
8439    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8440            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8441        if (instantAppPkgName == null) {
8442            return resolveInfos;
8443        }
8444        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8445            final ResolveInfo info = resolveInfos.get(i);
8446            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8447            // allow providers that are defined in the provided package
8448            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8449                if (info.providerInfo.splitName != null
8450                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8451                                info.providerInfo.splitName)) {
8452                    // requested provider is defined in a split that hasn't been installed yet.
8453                    // add the installer to the resolve list
8454                    if (DEBUG_EPHEMERAL) {
8455                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8456                    }
8457                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8458                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8459                            info.providerInfo.packageName, info.providerInfo.splitName,
8460                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8461                            null /*failureIntent*/);
8462                    // make sure this resolver is the default
8463                    installerInfo.isDefault = true;
8464                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8465                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8466                    // add a non-generic filter
8467                    installerInfo.filter = new IntentFilter();
8468                    // load resources from the correct package
8469                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8470                    resolveInfos.set(i, installerInfo);
8471                }
8472                continue;
8473            }
8474            // allow providers that have been explicitly exposed to instant applications
8475            if (!isEphemeralApp
8476                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8477                continue;
8478            }
8479            resolveInfos.remove(i);
8480        }
8481        return resolveInfos;
8482    }
8483
8484    @Override
8485    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8486        final int callingUid = Binder.getCallingUid();
8487        if (getInstantAppPackageName(callingUid) != null) {
8488            return ParceledListSlice.emptyList();
8489        }
8490        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8491        flags = updateFlagsForPackage(flags, userId, null);
8492        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8493        enforceCrossUserPermission(callingUid, userId,
8494                true /* requireFullPermission */, false /* checkShell */,
8495                "get installed packages");
8496
8497        // writer
8498        synchronized (mPackages) {
8499            ArrayList<PackageInfo> list;
8500            if (listUninstalled) {
8501                list = new ArrayList<>(mSettings.mPackages.size());
8502                for (PackageSetting ps : mSettings.mPackages.values()) {
8503                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8504                        continue;
8505                    }
8506                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8507                        return null;
8508                    }
8509                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8510                    if (pi != null) {
8511                        list.add(pi);
8512                    }
8513                }
8514            } else {
8515                list = new ArrayList<>(mPackages.size());
8516                for (PackageParser.Package p : mPackages.values()) {
8517                    final PackageSetting ps = (PackageSetting) p.mExtras;
8518                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8519                        continue;
8520                    }
8521                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8522                        return null;
8523                    }
8524                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8525                            p.mExtras, flags, userId);
8526                    if (pi != null) {
8527                        list.add(pi);
8528                    }
8529                }
8530            }
8531
8532            return new ParceledListSlice<>(list);
8533        }
8534    }
8535
8536    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8537            String[] permissions, boolean[] tmp, int flags, int userId) {
8538        int numMatch = 0;
8539        final PermissionsState permissionsState = ps.getPermissionsState();
8540        for (int i=0; i<permissions.length; i++) {
8541            final String permission = permissions[i];
8542            if (permissionsState.hasPermission(permission, userId)) {
8543                tmp[i] = true;
8544                numMatch++;
8545            } else {
8546                tmp[i] = false;
8547            }
8548        }
8549        if (numMatch == 0) {
8550            return;
8551        }
8552        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8553
8554        // The above might return null in cases of uninstalled apps or install-state
8555        // skew across users/profiles.
8556        if (pi != null) {
8557            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8558                if (numMatch == permissions.length) {
8559                    pi.requestedPermissions = permissions;
8560                } else {
8561                    pi.requestedPermissions = new String[numMatch];
8562                    numMatch = 0;
8563                    for (int i=0; i<permissions.length; i++) {
8564                        if (tmp[i]) {
8565                            pi.requestedPermissions[numMatch] = permissions[i];
8566                            numMatch++;
8567                        }
8568                    }
8569                }
8570            }
8571            list.add(pi);
8572        }
8573    }
8574
8575    @Override
8576    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8577            String[] permissions, int flags, int userId) {
8578        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8579        flags = updateFlagsForPackage(flags, userId, permissions);
8580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8581                true /* requireFullPermission */, false /* checkShell */,
8582                "get packages holding permissions");
8583        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8584
8585        // writer
8586        synchronized (mPackages) {
8587            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8588            boolean[] tmpBools = new boolean[permissions.length];
8589            if (listUninstalled) {
8590                for (PackageSetting ps : mSettings.mPackages.values()) {
8591                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8592                            userId);
8593                }
8594            } else {
8595                for (PackageParser.Package pkg : mPackages.values()) {
8596                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8597                    if (ps != null) {
8598                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8599                                userId);
8600                    }
8601                }
8602            }
8603
8604            return new ParceledListSlice<PackageInfo>(list);
8605        }
8606    }
8607
8608    @Override
8609    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8610        final int callingUid = Binder.getCallingUid();
8611        if (getInstantAppPackageName(callingUid) != null) {
8612            return ParceledListSlice.emptyList();
8613        }
8614        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8615        flags = updateFlagsForApplication(flags, userId, null);
8616        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8617
8618        // writer
8619        synchronized (mPackages) {
8620            ArrayList<ApplicationInfo> list;
8621            if (listUninstalled) {
8622                list = new ArrayList<>(mSettings.mPackages.size());
8623                for (PackageSetting ps : mSettings.mPackages.values()) {
8624                    ApplicationInfo ai;
8625                    int effectiveFlags = flags;
8626                    if (ps.isSystem()) {
8627                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8628                    }
8629                    if (ps.pkg != null) {
8630                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8631                            continue;
8632                        }
8633                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8634                            return null;
8635                        }
8636                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8637                                ps.readUserState(userId), userId);
8638                        if (ai != null) {
8639                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8640                        }
8641                    } else {
8642                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8643                        // and already converts to externally visible package name
8644                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8645                                callingUid, effectiveFlags, userId);
8646                    }
8647                    if (ai != null) {
8648                        list.add(ai);
8649                    }
8650                }
8651            } else {
8652                list = new ArrayList<>(mPackages.size());
8653                for (PackageParser.Package p : mPackages.values()) {
8654                    if (p.mExtras != null) {
8655                        PackageSetting ps = (PackageSetting) p.mExtras;
8656                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8657                            continue;
8658                        }
8659                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8660                            return null;
8661                        }
8662                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8663                                ps.readUserState(userId), userId);
8664                        if (ai != null) {
8665                            ai.packageName = resolveExternalPackageNameLPr(p);
8666                            list.add(ai);
8667                        }
8668                    }
8669                }
8670            }
8671
8672            return new ParceledListSlice<>(list);
8673        }
8674    }
8675
8676    @Override
8677    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8678        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8679            return null;
8680        }
8681        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8682            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8683                    "getEphemeralApplications");
8684        }
8685        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8686                true /* requireFullPermission */, false /* checkShell */,
8687                "getEphemeralApplications");
8688        synchronized (mPackages) {
8689            List<InstantAppInfo> instantApps = mInstantAppRegistry
8690                    .getInstantAppsLPr(userId);
8691            if (instantApps != null) {
8692                return new ParceledListSlice<>(instantApps);
8693            }
8694        }
8695        return null;
8696    }
8697
8698    @Override
8699    public boolean isInstantApp(String packageName, int userId) {
8700        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8701                true /* requireFullPermission */, false /* checkShell */,
8702                "isInstantApp");
8703        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8704            return false;
8705        }
8706
8707        synchronized (mPackages) {
8708            int callingUid = Binder.getCallingUid();
8709            if (Process.isIsolated(callingUid)) {
8710                callingUid = mIsolatedOwners.get(callingUid);
8711            }
8712            final PackageSetting ps = mSettings.mPackages.get(packageName);
8713            PackageParser.Package pkg = mPackages.get(packageName);
8714            final boolean returnAllowed =
8715                    ps != null
8716                    && (isCallerSameApp(packageName, callingUid)
8717                            || canViewInstantApps(callingUid, userId)
8718                            || mInstantAppRegistry.isInstantAccessGranted(
8719                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8720            if (returnAllowed) {
8721                return ps.getInstantApp(userId);
8722            }
8723        }
8724        return false;
8725    }
8726
8727    @Override
8728    public byte[] getInstantAppCookie(String packageName, int userId) {
8729        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8730            return null;
8731        }
8732
8733        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8734                true /* requireFullPermission */, false /* checkShell */,
8735                "getInstantAppCookie");
8736        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8737            return null;
8738        }
8739        synchronized (mPackages) {
8740            return mInstantAppRegistry.getInstantAppCookieLPw(
8741                    packageName, userId);
8742        }
8743    }
8744
8745    @Override
8746    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8747        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8748            return true;
8749        }
8750
8751        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8752                true /* requireFullPermission */, true /* checkShell */,
8753                "setInstantAppCookie");
8754        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8755            return false;
8756        }
8757        synchronized (mPackages) {
8758            return mInstantAppRegistry.setInstantAppCookieLPw(
8759                    packageName, cookie, userId);
8760        }
8761    }
8762
8763    @Override
8764    public Bitmap getInstantAppIcon(String packageName, int userId) {
8765        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8766            return null;
8767        }
8768
8769        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8770            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8771                    "getInstantAppIcon");
8772        }
8773        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8774                true /* requireFullPermission */, false /* checkShell */,
8775                "getInstantAppIcon");
8776
8777        synchronized (mPackages) {
8778            return mInstantAppRegistry.getInstantAppIconLPw(
8779                    packageName, userId);
8780        }
8781    }
8782
8783    private boolean isCallerSameApp(String packageName, int uid) {
8784        PackageParser.Package pkg = mPackages.get(packageName);
8785        return pkg != null
8786                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8787    }
8788
8789    @Override
8790    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8791        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8792            return ParceledListSlice.emptyList();
8793        }
8794        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8795    }
8796
8797    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8798        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8799
8800        // reader
8801        synchronized (mPackages) {
8802            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8803            final int userId = UserHandle.getCallingUserId();
8804            while (i.hasNext()) {
8805                final PackageParser.Package p = i.next();
8806                if (p.applicationInfo == null) continue;
8807
8808                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8809                        && !p.applicationInfo.isDirectBootAware();
8810                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8811                        && p.applicationInfo.isDirectBootAware();
8812
8813                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8814                        && (!mSafeMode || isSystemApp(p))
8815                        && (matchesUnaware || matchesAware)) {
8816                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8817                    if (ps != null) {
8818                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8819                                ps.readUserState(userId), userId);
8820                        if (ai != null) {
8821                            finalList.add(ai);
8822                        }
8823                    }
8824                }
8825            }
8826        }
8827
8828        return finalList;
8829    }
8830
8831    @Override
8832    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8833        if (!sUserManager.exists(userId)) return null;
8834        flags = updateFlagsForComponent(flags, userId, name);
8835        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8836        // reader
8837        synchronized (mPackages) {
8838            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8839            PackageSetting ps = provider != null
8840                    ? mSettings.mPackages.get(provider.owner.packageName)
8841                    : null;
8842            if (ps != null) {
8843                final boolean isInstantApp = ps.getInstantApp(userId);
8844                // normal application; filter out instant application provider
8845                if (instantAppPkgName == null && isInstantApp) {
8846                    return null;
8847                }
8848                // instant application; filter out other instant applications
8849                if (instantAppPkgName != null
8850                        && isInstantApp
8851                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8852                    return null;
8853                }
8854                // instant application; filter out non-exposed provider
8855                if (instantAppPkgName != null
8856                        && !isInstantApp
8857                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8858                    return null;
8859                }
8860                // provider not enabled
8861                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8862                    return null;
8863                }
8864                return PackageParser.generateProviderInfo(
8865                        provider, flags, ps.readUserState(userId), userId);
8866            }
8867            return null;
8868        }
8869    }
8870
8871    /**
8872     * @deprecated
8873     */
8874    @Deprecated
8875    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8877            return;
8878        }
8879        // reader
8880        synchronized (mPackages) {
8881            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8882                    .entrySet().iterator();
8883            final int userId = UserHandle.getCallingUserId();
8884            while (i.hasNext()) {
8885                Map.Entry<String, PackageParser.Provider> entry = i.next();
8886                PackageParser.Provider p = entry.getValue();
8887                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8888
8889                if (ps != null && p.syncable
8890                        && (!mSafeMode || (p.info.applicationInfo.flags
8891                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8892                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8893                            ps.readUserState(userId), userId);
8894                    if (info != null) {
8895                        outNames.add(entry.getKey());
8896                        outInfo.add(info);
8897                    }
8898                }
8899            }
8900        }
8901    }
8902
8903    @Override
8904    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8905            int uid, int flags, String metaDataKey) {
8906        final int callingUid = Binder.getCallingUid();
8907        final int userId = processName != null ? UserHandle.getUserId(uid)
8908                : UserHandle.getCallingUserId();
8909        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8910        flags = updateFlagsForComponent(flags, userId, processName);
8911        ArrayList<ProviderInfo> finalList = null;
8912        // reader
8913        synchronized (mPackages) {
8914            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8915            while (i.hasNext()) {
8916                final PackageParser.Provider p = i.next();
8917                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8918                if (ps != null && p.info.authority != null
8919                        && (processName == null
8920                                || (p.info.processName.equals(processName)
8921                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8922                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8923
8924                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8925                    // parameter.
8926                    if (metaDataKey != null
8927                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8928                        continue;
8929                    }
8930                    final ComponentName component =
8931                            new ComponentName(p.info.packageName, p.info.name);
8932                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8933                        continue;
8934                    }
8935                    if (finalList == null) {
8936                        finalList = new ArrayList<ProviderInfo>(3);
8937                    }
8938                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8939                            ps.readUserState(userId), userId);
8940                    if (info != null) {
8941                        finalList.add(info);
8942                    }
8943                }
8944            }
8945        }
8946
8947        if (finalList != null) {
8948            Collections.sort(finalList, mProviderInitOrderSorter);
8949            return new ParceledListSlice<ProviderInfo>(finalList);
8950        }
8951
8952        return ParceledListSlice.emptyList();
8953    }
8954
8955    @Override
8956    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8957        // reader
8958        synchronized (mPackages) {
8959            final int callingUid = Binder.getCallingUid();
8960            final int callingUserId = UserHandle.getUserId(callingUid);
8961            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8962            if (ps == null) return null;
8963            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8964                return null;
8965            }
8966            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8967            return PackageParser.generateInstrumentationInfo(i, flags);
8968        }
8969    }
8970
8971    @Override
8972    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8973            String targetPackage, int flags) {
8974        final int callingUid = Binder.getCallingUid();
8975        final int callingUserId = UserHandle.getUserId(callingUid);
8976        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8977        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8978            return ParceledListSlice.emptyList();
8979        }
8980        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8981    }
8982
8983    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8984            int flags) {
8985        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8986
8987        // reader
8988        synchronized (mPackages) {
8989            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8990            while (i.hasNext()) {
8991                final PackageParser.Instrumentation p = i.next();
8992                if (targetPackage == null
8993                        || targetPackage.equals(p.info.targetPackage)) {
8994                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8995                            flags);
8996                    if (ii != null) {
8997                        finalList.add(ii);
8998                    }
8999                }
9000            }
9001        }
9002
9003        return finalList;
9004    }
9005
9006    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9007        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9008        try {
9009            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9010        } finally {
9011            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9012        }
9013    }
9014
9015    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9016        final File[] files = dir.listFiles();
9017        if (ArrayUtils.isEmpty(files)) {
9018            Log.d(TAG, "No files in app dir " + dir);
9019            return;
9020        }
9021
9022        if (DEBUG_PACKAGE_SCANNING) {
9023            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9024                    + " flags=0x" + Integer.toHexString(parseFlags));
9025        }
9026        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9027                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9028                mParallelPackageParserCallback);
9029
9030        // Submit files for parsing in parallel
9031        int fileCount = 0;
9032        for (File file : files) {
9033            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9034                    && !PackageInstallerService.isStageName(file.getName());
9035            if (!isPackage) {
9036                // Ignore entries which are not packages
9037                continue;
9038            }
9039            parallelPackageParser.submit(file, parseFlags);
9040            fileCount++;
9041        }
9042
9043        // Process results one by one
9044        for (; fileCount > 0; fileCount--) {
9045            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9046            Throwable throwable = parseResult.throwable;
9047            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9048
9049            if (throwable == null) {
9050                // Static shared libraries have synthetic package names
9051                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9052                    renameStaticSharedLibraryPackage(parseResult.pkg);
9053                }
9054                try {
9055                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9056                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9057                                currentTime, null);
9058                    }
9059                } catch (PackageManagerException e) {
9060                    errorCode = e.error;
9061                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9062                }
9063            } else if (throwable instanceof PackageParser.PackageParserException) {
9064                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9065                        throwable;
9066                errorCode = e.error;
9067                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9068            } else {
9069                throw new IllegalStateException("Unexpected exception occurred while parsing "
9070                        + parseResult.scanFile, throwable);
9071            }
9072
9073            // Delete invalid userdata apps
9074            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9075                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9076                logCriticalInfo(Log.WARN,
9077                        "Deleting invalid package at " + parseResult.scanFile);
9078                removeCodePathLI(parseResult.scanFile);
9079            }
9080        }
9081        parallelPackageParser.close();
9082    }
9083
9084    private static File getSettingsProblemFile() {
9085        File dataDir = Environment.getDataDirectory();
9086        File systemDir = new File(dataDir, "system");
9087        File fname = new File(systemDir, "uiderrors.txt");
9088        return fname;
9089    }
9090
9091    static void reportSettingsProblem(int priority, String msg) {
9092        logCriticalInfo(priority, msg);
9093    }
9094
9095    public static void logCriticalInfo(int priority, String msg) {
9096        Slog.println(priority, TAG, msg);
9097        EventLogTags.writePmCriticalInfo(msg);
9098        try {
9099            File fname = getSettingsProblemFile();
9100            FileOutputStream out = new FileOutputStream(fname, true);
9101            PrintWriter pw = new FastPrintWriter(out);
9102            SimpleDateFormat formatter = new SimpleDateFormat();
9103            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9104            pw.println(dateString + ": " + msg);
9105            pw.close();
9106            FileUtils.setPermissions(
9107                    fname.toString(),
9108                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9109                    -1, -1);
9110        } catch (java.io.IOException e) {
9111        }
9112    }
9113
9114    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9115        if (srcFile.isDirectory()) {
9116            final File baseFile = new File(pkg.baseCodePath);
9117            long maxModifiedTime = baseFile.lastModified();
9118            if (pkg.splitCodePaths != null) {
9119                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9120                    final File splitFile = new File(pkg.splitCodePaths[i]);
9121                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9122                }
9123            }
9124            return maxModifiedTime;
9125        }
9126        return srcFile.lastModified();
9127    }
9128
9129    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9130            final int policyFlags) throws PackageManagerException {
9131        // When upgrading from pre-N MR1, verify the package time stamp using the package
9132        // directory and not the APK file.
9133        final long lastModifiedTime = mIsPreNMR1Upgrade
9134                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9135        if (ps != null
9136                && ps.codePath.equals(srcFile)
9137                && ps.timeStamp == lastModifiedTime
9138                && !isCompatSignatureUpdateNeeded(pkg)
9139                && !isRecoverSignatureUpdateNeeded(pkg)) {
9140            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9141            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9142            ArraySet<PublicKey> signingKs;
9143            synchronized (mPackages) {
9144                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9145            }
9146            if (ps.signatures.mSignatures != null
9147                    && ps.signatures.mSignatures.length != 0
9148                    && signingKs != null) {
9149                // Optimization: reuse the existing cached certificates
9150                // if the package appears to be unchanged.
9151                pkg.mSignatures = ps.signatures.mSignatures;
9152                pkg.mSigningKeys = signingKs;
9153                return;
9154            }
9155
9156            Slog.w(TAG, "PackageSetting for " + ps.name
9157                    + " is missing signatures.  Collecting certs again to recover them.");
9158        } else {
9159            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9160        }
9161
9162        try {
9163            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9164            PackageParser.collectCertificates(pkg, policyFlags);
9165        } catch (PackageParserException e) {
9166            throw PackageManagerException.from(e);
9167        } finally {
9168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9169        }
9170    }
9171
9172    /**
9173     *  Traces a package scan.
9174     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9175     */
9176    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9177            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9178        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9179        try {
9180            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9181        } finally {
9182            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9183        }
9184    }
9185
9186    /**
9187     *  Scans a package and returns the newly parsed package.
9188     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9189     */
9190    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9191            long currentTime, UserHandle user) throws PackageManagerException {
9192        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9193        PackageParser pp = new PackageParser();
9194        pp.setSeparateProcesses(mSeparateProcesses);
9195        pp.setOnlyCoreApps(mOnlyCore);
9196        pp.setDisplayMetrics(mMetrics);
9197        pp.setCallback(mPackageParserCallback);
9198
9199        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9200            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9201        }
9202
9203        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9204        final PackageParser.Package pkg;
9205        try {
9206            pkg = pp.parsePackage(scanFile, parseFlags);
9207        } catch (PackageParserException e) {
9208            throw PackageManagerException.from(e);
9209        } finally {
9210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9211        }
9212
9213        // Static shared libraries have synthetic package names
9214        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9215            renameStaticSharedLibraryPackage(pkg);
9216        }
9217
9218        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9219    }
9220
9221    /**
9222     *  Scans a package and returns the newly parsed package.
9223     *  @throws PackageManagerException on a parse error.
9224     */
9225    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9226            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9227            throws PackageManagerException {
9228        // If the package has children and this is the first dive in the function
9229        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9230        // packages (parent and children) would be successfully scanned before the
9231        // actual scan since scanning mutates internal state and we want to atomically
9232        // install the package and its children.
9233        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9234            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9235                scanFlags |= SCAN_CHECK_ONLY;
9236            }
9237        } else {
9238            scanFlags &= ~SCAN_CHECK_ONLY;
9239        }
9240
9241        // Scan the parent
9242        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9243                scanFlags, currentTime, user);
9244
9245        // Scan the children
9246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9247        for (int i = 0; i < childCount; i++) {
9248            PackageParser.Package childPackage = pkg.childPackages.get(i);
9249            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9250                    currentTime, user);
9251        }
9252
9253
9254        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9255            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9256        }
9257
9258        return scannedPkg;
9259    }
9260
9261    /**
9262     *  Scans a package and returns the newly parsed package.
9263     *  @throws PackageManagerException on a parse error.
9264     */
9265    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9266            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9267            throws PackageManagerException {
9268        PackageSetting ps = null;
9269        PackageSetting updatedPkg;
9270        // reader
9271        synchronized (mPackages) {
9272            // Look to see if we already know about this package.
9273            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9274            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9275                // This package has been renamed to its original name.  Let's
9276                // use that.
9277                ps = mSettings.getPackageLPr(oldName);
9278            }
9279            // If there was no original package, see one for the real package name.
9280            if (ps == null) {
9281                ps = mSettings.getPackageLPr(pkg.packageName);
9282            }
9283            // Check to see if this package could be hiding/updating a system
9284            // package.  Must look for it either under the original or real
9285            // package name depending on our state.
9286            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9287            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9288
9289            // If this is a package we don't know about on the system partition, we
9290            // may need to remove disabled child packages on the system partition
9291            // or may need to not add child packages if the parent apk is updated
9292            // on the data partition and no longer defines this child package.
9293            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9294                // If this is a parent package for an updated system app and this system
9295                // app got an OTA update which no longer defines some of the child packages
9296                // we have to prune them from the disabled system packages.
9297                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9298                if (disabledPs != null) {
9299                    final int scannedChildCount = (pkg.childPackages != null)
9300                            ? pkg.childPackages.size() : 0;
9301                    final int disabledChildCount = disabledPs.childPackageNames != null
9302                            ? disabledPs.childPackageNames.size() : 0;
9303                    for (int i = 0; i < disabledChildCount; i++) {
9304                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9305                        boolean disabledPackageAvailable = false;
9306                        for (int j = 0; j < scannedChildCount; j++) {
9307                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9308                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9309                                disabledPackageAvailable = true;
9310                                break;
9311                            }
9312                         }
9313                         if (!disabledPackageAvailable) {
9314                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9315                         }
9316                    }
9317                }
9318            }
9319        }
9320
9321        final boolean isUpdatedPkg = updatedPkg != null;
9322        final boolean isUpdatedSystemPkg = isUpdatedPkg
9323                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9324        boolean isUpdatedPkgBetter = false;
9325        // First check if this is a system package that may involve an update
9326        if (isUpdatedSystemPkg) {
9327            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9328            // it needs to drop FLAG_PRIVILEGED.
9329            if (locationIsPrivileged(scanFile)) {
9330                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9331            } else {
9332                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9333            }
9334
9335            if (ps != null && !ps.codePath.equals(scanFile)) {
9336                // The path has changed from what was last scanned...  check the
9337                // version of the new path against what we have stored to determine
9338                // what to do.
9339                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9340                if (pkg.mVersionCode <= ps.versionCode) {
9341                    // The system package has been updated and the code path does not match
9342                    // Ignore entry. Skip it.
9343                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9344                            + " ignored: updated version " + ps.versionCode
9345                            + " better than this " + pkg.mVersionCode);
9346                    if (!updatedPkg.codePath.equals(scanFile)) {
9347                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9348                                + ps.name + " changing from " + updatedPkg.codePathString
9349                                + " to " + scanFile);
9350                        updatedPkg.codePath = scanFile;
9351                        updatedPkg.codePathString = scanFile.toString();
9352                        updatedPkg.resourcePath = scanFile;
9353                        updatedPkg.resourcePathString = scanFile.toString();
9354                    }
9355                    updatedPkg.pkg = pkg;
9356                    updatedPkg.versionCode = pkg.mVersionCode;
9357
9358                    // Update the disabled system child packages to point to the package too.
9359                    final int childCount = updatedPkg.childPackageNames != null
9360                            ? updatedPkg.childPackageNames.size() : 0;
9361                    for (int i = 0; i < childCount; i++) {
9362                        String childPackageName = updatedPkg.childPackageNames.get(i);
9363                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9364                                childPackageName);
9365                        if (updatedChildPkg != null) {
9366                            updatedChildPkg.pkg = pkg;
9367                            updatedChildPkg.versionCode = pkg.mVersionCode;
9368                        }
9369                    }
9370                } else {
9371                    // The current app on the system partition is better than
9372                    // what we have updated to on the data partition; switch
9373                    // back to the system partition version.
9374                    // At this point, its safely assumed that package installation for
9375                    // apps in system partition will go through. If not there won't be a working
9376                    // version of the app
9377                    // writer
9378                    synchronized (mPackages) {
9379                        // Just remove the loaded entries from package lists.
9380                        mPackages.remove(ps.name);
9381                    }
9382
9383                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9384                            + " reverting from " + ps.codePathString
9385                            + ": new version " + pkg.mVersionCode
9386                            + " better than installed " + ps.versionCode);
9387
9388                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9389                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9390                    synchronized (mInstallLock) {
9391                        args.cleanUpResourcesLI();
9392                    }
9393                    synchronized (mPackages) {
9394                        mSettings.enableSystemPackageLPw(ps.name);
9395                    }
9396                    isUpdatedPkgBetter = true;
9397                }
9398            }
9399        }
9400
9401        String resourcePath = null;
9402        String baseResourcePath = null;
9403        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9404            if (ps != null && ps.resourcePathString != null) {
9405                resourcePath = ps.resourcePathString;
9406                baseResourcePath = ps.resourcePathString;
9407            } else {
9408                // Should not happen at all. Just log an error.
9409                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9410            }
9411        } else {
9412            resourcePath = pkg.codePath;
9413            baseResourcePath = pkg.baseCodePath;
9414        }
9415
9416        // Set application objects path explicitly.
9417        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9418        pkg.setApplicationInfoCodePath(pkg.codePath);
9419        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9420        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9421        pkg.setApplicationInfoResourcePath(resourcePath);
9422        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9423        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9424
9425        // throw an exception if we have an update to a system application, but, it's not more
9426        // recent than the package we've already scanned
9427        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9428            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9429                    + scanFile + " ignored: updated version " + ps.versionCode
9430                    + " better than this " + pkg.mVersionCode);
9431        }
9432
9433        if (isUpdatedPkg) {
9434            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9435            // initially
9436            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9437
9438            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9439            // flag set initially
9440            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9441                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9442            }
9443        }
9444
9445        // Verify certificates against what was last scanned
9446        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9447
9448        /*
9449         * A new system app appeared, but we already had a non-system one of the
9450         * same name installed earlier.
9451         */
9452        boolean shouldHideSystemApp = false;
9453        if (!isUpdatedPkg && ps != null
9454                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9455            /*
9456             * Check to make sure the signatures match first. If they don't,
9457             * wipe the installed application and its data.
9458             */
9459            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9460                    != PackageManager.SIGNATURE_MATCH) {
9461                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9462                        + " signatures don't match existing userdata copy; removing");
9463                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9464                        "scanPackageInternalLI")) {
9465                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9466                }
9467                ps = null;
9468            } else {
9469                /*
9470                 * If the newly-added system app is an older version than the
9471                 * already installed version, hide it. It will be scanned later
9472                 * and re-added like an update.
9473                 */
9474                if (pkg.mVersionCode <= ps.versionCode) {
9475                    shouldHideSystemApp = true;
9476                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9477                            + " but new version " + pkg.mVersionCode + " better than installed "
9478                            + ps.versionCode + "; hiding system");
9479                } else {
9480                    /*
9481                     * The newly found system app is a newer version that the
9482                     * one previously installed. Simply remove the
9483                     * already-installed application and replace it with our own
9484                     * while keeping the application data.
9485                     */
9486                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9487                            + " reverting from " + ps.codePathString + ": new version "
9488                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9489                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9490                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9491                    synchronized (mInstallLock) {
9492                        args.cleanUpResourcesLI();
9493                    }
9494                }
9495            }
9496        }
9497
9498        // The apk is forward locked (not public) if its code and resources
9499        // are kept in different files. (except for app in either system or
9500        // vendor path).
9501        // TODO grab this value from PackageSettings
9502        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9503            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9504                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9505            }
9506        }
9507
9508        final int userId = ((user == null) ? 0 : user.getIdentifier());
9509        if (ps != null && ps.getInstantApp(userId)) {
9510            scanFlags |= SCAN_AS_INSTANT_APP;
9511        }
9512        if (ps != null && ps.getVirtulalPreload(userId)) {
9513            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9514        }
9515
9516        // Note that we invoke the following method only if we are about to unpack an application
9517        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9518                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9519
9520        /*
9521         * If the system app should be overridden by a previously installed
9522         * data, hide the system app now and let the /data/app scan pick it up
9523         * again.
9524         */
9525        if (shouldHideSystemApp) {
9526            synchronized (mPackages) {
9527                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9528            }
9529        }
9530
9531        return scannedPkg;
9532    }
9533
9534    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9535        // Derive the new package synthetic package name
9536        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9537                + pkg.staticSharedLibVersion);
9538    }
9539
9540    private static String fixProcessName(String defProcessName,
9541            String processName) {
9542        if (processName == null) {
9543            return defProcessName;
9544        }
9545        return processName;
9546    }
9547
9548    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9549            throws PackageManagerException {
9550        if (pkgSetting.signatures.mSignatures != null) {
9551            // Already existing package. Make sure signatures match
9552            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9553                    == PackageManager.SIGNATURE_MATCH;
9554            if (!match) {
9555                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9556                        == PackageManager.SIGNATURE_MATCH;
9557            }
9558            if (!match) {
9559                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9560                        == PackageManager.SIGNATURE_MATCH;
9561            }
9562            if (!match) {
9563                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9564                        + pkg.packageName + " signatures do not match the "
9565                        + "previously installed version; ignoring!");
9566            }
9567        }
9568
9569        // Check for shared user signatures
9570        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9571            // Already existing package. Make sure signatures match
9572            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9573                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9574            if (!match) {
9575                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9576                        == PackageManager.SIGNATURE_MATCH;
9577            }
9578            if (!match) {
9579                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9580                        == PackageManager.SIGNATURE_MATCH;
9581            }
9582            if (!match) {
9583                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9584                        "Package " + pkg.packageName
9585                        + " has no signatures that match those in shared user "
9586                        + pkgSetting.sharedUser.name + "; ignoring!");
9587            }
9588        }
9589    }
9590
9591    /**
9592     * Enforces that only the system UID or root's UID can call a method exposed
9593     * via Binder.
9594     *
9595     * @param message used as message if SecurityException is thrown
9596     * @throws SecurityException if the caller is not system or root
9597     */
9598    private static final void enforceSystemOrRoot(String message) {
9599        final int uid = Binder.getCallingUid();
9600        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9601            throw new SecurityException(message);
9602        }
9603    }
9604
9605    @Override
9606    public void performFstrimIfNeeded() {
9607        enforceSystemOrRoot("Only the system can request fstrim");
9608
9609        // Before everything else, see whether we need to fstrim.
9610        try {
9611            IStorageManager sm = PackageHelper.getStorageManager();
9612            if (sm != null) {
9613                boolean doTrim = false;
9614                final long interval = android.provider.Settings.Global.getLong(
9615                        mContext.getContentResolver(),
9616                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9617                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9618                if (interval > 0) {
9619                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9620                    if (timeSinceLast > interval) {
9621                        doTrim = true;
9622                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9623                                + "; running immediately");
9624                    }
9625                }
9626                if (doTrim) {
9627                    final boolean dexOptDialogShown;
9628                    synchronized (mPackages) {
9629                        dexOptDialogShown = mDexOptDialogShown;
9630                    }
9631                    if (!isFirstBoot() && dexOptDialogShown) {
9632                        try {
9633                            ActivityManager.getService().showBootMessage(
9634                                    mContext.getResources().getString(
9635                                            R.string.android_upgrading_fstrim), true);
9636                        } catch (RemoteException e) {
9637                        }
9638                    }
9639                    sm.runMaintenance();
9640                }
9641            } else {
9642                Slog.e(TAG, "storageManager service unavailable!");
9643            }
9644        } catch (RemoteException e) {
9645            // Can't happen; StorageManagerService is local
9646        }
9647    }
9648
9649    @Override
9650    public void updatePackagesIfNeeded() {
9651        enforceSystemOrRoot("Only the system can request package update");
9652
9653        // We need to re-extract after an OTA.
9654        boolean causeUpgrade = isUpgrade();
9655
9656        // First boot or factory reset.
9657        // Note: we also handle devices that are upgrading to N right now as if it is their
9658        //       first boot, as they do not have profile data.
9659        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9660
9661        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9662        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9663
9664        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9665            return;
9666        }
9667
9668        List<PackageParser.Package> pkgs;
9669        synchronized (mPackages) {
9670            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9671        }
9672
9673        final long startTime = System.nanoTime();
9674        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9675                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9676                    false /* bootComplete */);
9677
9678        final int elapsedTimeSeconds =
9679                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9680
9681        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9682        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9683        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9684        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9685        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9686    }
9687
9688    /*
9689     * Return the prebuilt profile path given a package base code path.
9690     */
9691    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9692        return pkg.baseCodePath + ".prof";
9693    }
9694
9695    /**
9696     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9697     * containing statistics about the invocation. The array consists of three elements,
9698     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9699     * and {@code numberOfPackagesFailed}.
9700     */
9701    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9702            String compilerFilter, boolean bootComplete) {
9703
9704        int numberOfPackagesVisited = 0;
9705        int numberOfPackagesOptimized = 0;
9706        int numberOfPackagesSkipped = 0;
9707        int numberOfPackagesFailed = 0;
9708        final int numberOfPackagesToDexopt = pkgs.size();
9709
9710        for (PackageParser.Package pkg : pkgs) {
9711            numberOfPackagesVisited++;
9712
9713            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9714                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9715                // that are already compiled.
9716                File profileFile = new File(getPrebuildProfilePath(pkg));
9717                // Copy profile if it exists.
9718                if (profileFile.exists()) {
9719                    try {
9720                        // We could also do this lazily before calling dexopt in
9721                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9722                        // is that we don't have a good way to say "do this only once".
9723                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9724                                pkg.applicationInfo.uid, pkg.packageName)) {
9725                            Log.e(TAG, "Installer failed to copy system profile!");
9726                        }
9727                    } catch (Exception e) {
9728                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9729                                e);
9730                    }
9731                }
9732            }
9733
9734            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9735                if (DEBUG_DEXOPT) {
9736                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9737                }
9738                numberOfPackagesSkipped++;
9739                continue;
9740            }
9741
9742            if (DEBUG_DEXOPT) {
9743                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9744                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9745            }
9746
9747            if (showDialog) {
9748                try {
9749                    ActivityManager.getService().showBootMessage(
9750                            mContext.getResources().getString(R.string.android_upgrading_apk,
9751                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9752                } catch (RemoteException e) {
9753                }
9754                synchronized (mPackages) {
9755                    mDexOptDialogShown = true;
9756                }
9757            }
9758
9759            // If the OTA updates a system app which was previously preopted to a non-preopted state
9760            // the app might end up being verified at runtime. That's because by default the apps
9761            // are verify-profile but for preopted apps there's no profile.
9762            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9763            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9764            // filter (by default 'quicken').
9765            // Note that at this stage unused apps are already filtered.
9766            if (isSystemApp(pkg) &&
9767                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9768                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9769                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9770            }
9771
9772            // checkProfiles is false to avoid merging profiles during boot which
9773            // might interfere with background compilation (b/28612421).
9774            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9775            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9776            // trade-off worth doing to save boot time work.
9777            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9778            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9779                    pkg.packageName,
9780                    compilerFilter,
9781                    dexoptFlags));
9782
9783            if (pkg.isSystemApp()) {
9784                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9785                // too much boot after an OTA.
9786                int secondaryDexoptFlags = dexoptFlags |
9787                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9788                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9789                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9790                        pkg.packageName,
9791                        compilerFilter,
9792                        secondaryDexoptFlags));
9793            }
9794
9795            // TODO(shubhamajmera): Record secondary dexopt stats.
9796            switch (primaryDexOptStaus) {
9797                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9798                    numberOfPackagesOptimized++;
9799                    break;
9800                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9801                    numberOfPackagesSkipped++;
9802                    break;
9803                case PackageDexOptimizer.DEX_OPT_FAILED:
9804                    numberOfPackagesFailed++;
9805                    break;
9806                default:
9807                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9808                    break;
9809            }
9810        }
9811
9812        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9813                numberOfPackagesFailed };
9814    }
9815
9816    @Override
9817    public void notifyPackageUse(String packageName, int reason) {
9818        synchronized (mPackages) {
9819            final int callingUid = Binder.getCallingUid();
9820            final int callingUserId = UserHandle.getUserId(callingUid);
9821            if (getInstantAppPackageName(callingUid) != null) {
9822                if (!isCallerSameApp(packageName, callingUid)) {
9823                    return;
9824                }
9825            } else {
9826                if (isInstantApp(packageName, callingUserId)) {
9827                    return;
9828                }
9829            }
9830            final PackageParser.Package p = mPackages.get(packageName);
9831            if (p == null) {
9832                return;
9833            }
9834            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9835        }
9836    }
9837
9838    @Override
9839    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9840            List<String> classPaths, String loaderIsa) {
9841        int userId = UserHandle.getCallingUserId();
9842        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9843        if (ai == null) {
9844            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9845                + loadingPackageName + ", user=" + userId);
9846            return;
9847        }
9848        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9849    }
9850
9851    @Override
9852    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9853            IDexModuleRegisterCallback callback) {
9854        int userId = UserHandle.getCallingUserId();
9855        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9856        DexManager.RegisterDexModuleResult result;
9857        if (ai == null) {
9858            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9859                     " calling user. package=" + packageName + ", user=" + userId);
9860            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9861        } else {
9862            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9863        }
9864
9865        if (callback != null) {
9866            mHandler.post(() -> {
9867                try {
9868                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9869                } catch (RemoteException e) {
9870                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9871                }
9872            });
9873        }
9874    }
9875
9876    /**
9877     * Ask the package manager to perform a dex-opt with the given compiler filter.
9878     *
9879     * Note: exposed only for the shell command to allow moving packages explicitly to a
9880     *       definite state.
9881     */
9882    @Override
9883    public boolean performDexOptMode(String packageName,
9884            boolean checkProfiles, String targetCompilerFilter, boolean force,
9885            boolean bootComplete, String splitName) {
9886        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9887                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9888                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9889        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9890                splitName, flags));
9891    }
9892
9893    /**
9894     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9895     * secondary dex files belonging to the given package.
9896     *
9897     * Note: exposed only for the shell command to allow moving packages explicitly to a
9898     *       definite state.
9899     */
9900    @Override
9901    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9902            boolean force) {
9903        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9904                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9905                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9906                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9907        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9908    }
9909
9910    /*package*/ boolean performDexOpt(DexoptOptions options) {
9911        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9912            return false;
9913        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9914            return false;
9915        }
9916
9917        if (options.isDexoptOnlySecondaryDex()) {
9918            return mDexManager.dexoptSecondaryDex(options);
9919        } else {
9920            int dexoptStatus = performDexOptWithStatus(options);
9921            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9922        }
9923    }
9924
9925    /**
9926     * Perform dexopt on the given package and return one of following result:
9927     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9928     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9929     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9930     */
9931    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9932        return performDexOptTraced(options);
9933    }
9934
9935    private int performDexOptTraced(DexoptOptions options) {
9936        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9937        try {
9938            return performDexOptInternal(options);
9939        } finally {
9940            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9941        }
9942    }
9943
9944    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9945    // if the package can now be considered up to date for the given filter.
9946    private int performDexOptInternal(DexoptOptions options) {
9947        PackageParser.Package p;
9948        synchronized (mPackages) {
9949            p = mPackages.get(options.getPackageName());
9950            if (p == null) {
9951                // Package could not be found. Report failure.
9952                return PackageDexOptimizer.DEX_OPT_FAILED;
9953            }
9954            mPackageUsage.maybeWriteAsync(mPackages);
9955            mCompilerStats.maybeWriteAsync();
9956        }
9957        long callingId = Binder.clearCallingIdentity();
9958        try {
9959            synchronized (mInstallLock) {
9960                return performDexOptInternalWithDependenciesLI(p, options);
9961            }
9962        } finally {
9963            Binder.restoreCallingIdentity(callingId);
9964        }
9965    }
9966
9967    public ArraySet<String> getOptimizablePackages() {
9968        ArraySet<String> pkgs = new ArraySet<String>();
9969        synchronized (mPackages) {
9970            for (PackageParser.Package p : mPackages.values()) {
9971                if (PackageDexOptimizer.canOptimizePackage(p)) {
9972                    pkgs.add(p.packageName);
9973                }
9974            }
9975        }
9976        return pkgs;
9977    }
9978
9979    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9980            DexoptOptions options) {
9981        // Select the dex optimizer based on the force parameter.
9982        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9983        //       allocate an object here.
9984        PackageDexOptimizer pdo = options.isForce()
9985                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9986                : mPackageDexOptimizer;
9987
9988        // Dexopt all dependencies first. Note: we ignore the return value and march on
9989        // on errors.
9990        // Note that we are going to call performDexOpt on those libraries as many times as
9991        // they are referenced in packages. When we do a batch of performDexOpt (for example
9992        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9993        // and the first package that uses the library will dexopt it. The
9994        // others will see that the compiled code for the library is up to date.
9995        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9996        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9997        if (!deps.isEmpty()) {
9998            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9999                    options.getCompilerFilter(), options.getSplitName(),
10000                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10001            for (PackageParser.Package depPackage : deps) {
10002                // TODO: Analyze and investigate if we (should) profile libraries.
10003                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10004                        getOrCreateCompilerPackageStats(depPackage),
10005                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10006            }
10007        }
10008        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10009                getOrCreateCompilerPackageStats(p),
10010                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10011    }
10012
10013    /**
10014     * Reconcile the information we have about the secondary dex files belonging to
10015     * {@code packagName} and the actual dex files. For all dex files that were
10016     * deleted, update the internal records and delete the generated oat files.
10017     */
10018    @Override
10019    public void reconcileSecondaryDexFiles(String packageName) {
10020        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10021            return;
10022        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10023            return;
10024        }
10025        mDexManager.reconcileSecondaryDexFiles(packageName);
10026    }
10027
10028    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10029    // a reference there.
10030    /*package*/ DexManager getDexManager() {
10031        return mDexManager;
10032    }
10033
10034    /**
10035     * Execute the background dexopt job immediately.
10036     */
10037    @Override
10038    public boolean runBackgroundDexoptJob() {
10039        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10040            return false;
10041        }
10042        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10043    }
10044
10045    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10046        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10047                || p.usesStaticLibraries != null) {
10048            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10049            Set<String> collectedNames = new HashSet<>();
10050            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10051
10052            retValue.remove(p);
10053
10054            return retValue;
10055        } else {
10056            return Collections.emptyList();
10057        }
10058    }
10059
10060    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10061            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10062        if (!collectedNames.contains(p.packageName)) {
10063            collectedNames.add(p.packageName);
10064            collected.add(p);
10065
10066            if (p.usesLibraries != null) {
10067                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10068                        null, collected, collectedNames);
10069            }
10070            if (p.usesOptionalLibraries != null) {
10071                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10072                        null, collected, collectedNames);
10073            }
10074            if (p.usesStaticLibraries != null) {
10075                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10076                        p.usesStaticLibrariesVersions, collected, collectedNames);
10077            }
10078        }
10079    }
10080
10081    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10082            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10083        final int libNameCount = libs.size();
10084        for (int i = 0; i < libNameCount; i++) {
10085            String libName = libs.get(i);
10086            int version = (versions != null && versions.length == libNameCount)
10087                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10088            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10089            if (libPkg != null) {
10090                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10091            }
10092        }
10093    }
10094
10095    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10096        synchronized (mPackages) {
10097            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10098            if (libEntry != null) {
10099                return mPackages.get(libEntry.apk);
10100            }
10101            return null;
10102        }
10103    }
10104
10105    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10106        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10107        if (versionedLib == null) {
10108            return null;
10109        }
10110        return versionedLib.get(version);
10111    }
10112
10113    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10114        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10115                pkg.staticSharedLibName);
10116        if (versionedLib == null) {
10117            return null;
10118        }
10119        int previousLibVersion = -1;
10120        final int versionCount = versionedLib.size();
10121        for (int i = 0; i < versionCount; i++) {
10122            final int libVersion = versionedLib.keyAt(i);
10123            if (libVersion < pkg.staticSharedLibVersion) {
10124                previousLibVersion = Math.max(previousLibVersion, libVersion);
10125            }
10126        }
10127        if (previousLibVersion >= 0) {
10128            return versionedLib.get(previousLibVersion);
10129        }
10130        return null;
10131    }
10132
10133    public void shutdown() {
10134        mPackageUsage.writeNow(mPackages);
10135        mCompilerStats.writeNow();
10136        mDexManager.writePackageDexUsageNow();
10137    }
10138
10139    @Override
10140    public void dumpProfiles(String packageName) {
10141        PackageParser.Package pkg;
10142        synchronized (mPackages) {
10143            pkg = mPackages.get(packageName);
10144            if (pkg == null) {
10145                throw new IllegalArgumentException("Unknown package: " + packageName);
10146            }
10147        }
10148        /* Only the shell, root, or the app user should be able to dump profiles. */
10149        int callingUid = Binder.getCallingUid();
10150        if (callingUid != Process.SHELL_UID &&
10151            callingUid != Process.ROOT_UID &&
10152            callingUid != pkg.applicationInfo.uid) {
10153            throw new SecurityException("dumpProfiles");
10154        }
10155
10156        synchronized (mInstallLock) {
10157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10158            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10159            try {
10160                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10161                String codePaths = TextUtils.join(";", allCodePaths);
10162                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10163            } catch (InstallerException e) {
10164                Slog.w(TAG, "Failed to dump profiles", e);
10165            }
10166            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10167        }
10168    }
10169
10170    @Override
10171    public void forceDexOpt(String packageName) {
10172        enforceSystemOrRoot("forceDexOpt");
10173
10174        PackageParser.Package pkg;
10175        synchronized (mPackages) {
10176            pkg = mPackages.get(packageName);
10177            if (pkg == null) {
10178                throw new IllegalArgumentException("Unknown package: " + packageName);
10179            }
10180        }
10181
10182        synchronized (mInstallLock) {
10183            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10184
10185            // Whoever is calling forceDexOpt wants a compiled package.
10186            // Don't use profiles since that may cause compilation to be skipped.
10187            final int res = performDexOptInternalWithDependenciesLI(
10188                    pkg,
10189                    new DexoptOptions(packageName,
10190                            getDefaultCompilerFilter(),
10191                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10192
10193            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10194            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10195                throw new IllegalStateException("Failed to dexopt: " + res);
10196            }
10197        }
10198    }
10199
10200    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10201        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10202            Slog.w(TAG, "Unable to update from " + oldPkg.name
10203                    + " to " + newPkg.packageName
10204                    + ": old package not in system partition");
10205            return false;
10206        } else if (mPackages.get(oldPkg.name) != null) {
10207            Slog.w(TAG, "Unable to update from " + oldPkg.name
10208                    + " to " + newPkg.packageName
10209                    + ": old package still exists");
10210            return false;
10211        }
10212        return true;
10213    }
10214
10215    void removeCodePathLI(File codePath) {
10216        if (codePath.isDirectory()) {
10217            try {
10218                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10219            } catch (InstallerException e) {
10220                Slog.w(TAG, "Failed to remove code path", e);
10221            }
10222        } else {
10223            codePath.delete();
10224        }
10225    }
10226
10227    private int[] resolveUserIds(int userId) {
10228        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10229    }
10230
10231    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10232        if (pkg == null) {
10233            Slog.wtf(TAG, "Package was null!", new Throwable());
10234            return;
10235        }
10236        clearAppDataLeafLIF(pkg, userId, flags);
10237        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10238        for (int i = 0; i < childCount; i++) {
10239            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10240        }
10241    }
10242
10243    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10244        final PackageSetting ps;
10245        synchronized (mPackages) {
10246            ps = mSettings.mPackages.get(pkg.packageName);
10247        }
10248        for (int realUserId : resolveUserIds(userId)) {
10249            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10250            try {
10251                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10252                        ceDataInode);
10253            } catch (InstallerException e) {
10254                Slog.w(TAG, String.valueOf(e));
10255            }
10256        }
10257    }
10258
10259    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10260        if (pkg == null) {
10261            Slog.wtf(TAG, "Package was null!", new Throwable());
10262            return;
10263        }
10264        destroyAppDataLeafLIF(pkg, userId, flags);
10265        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10266        for (int i = 0; i < childCount; i++) {
10267            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10268        }
10269    }
10270
10271    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10272        final PackageSetting ps;
10273        synchronized (mPackages) {
10274            ps = mSettings.mPackages.get(pkg.packageName);
10275        }
10276        for (int realUserId : resolveUserIds(userId)) {
10277            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10278            try {
10279                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10280                        ceDataInode);
10281            } catch (InstallerException e) {
10282                Slog.w(TAG, String.valueOf(e));
10283            }
10284            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10285        }
10286    }
10287
10288    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10289        if (pkg == null) {
10290            Slog.wtf(TAG, "Package was null!", new Throwable());
10291            return;
10292        }
10293        destroyAppProfilesLeafLIF(pkg);
10294        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10295        for (int i = 0; i < childCount; i++) {
10296            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10297        }
10298    }
10299
10300    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10301        try {
10302            mInstaller.destroyAppProfiles(pkg.packageName);
10303        } catch (InstallerException e) {
10304            Slog.w(TAG, String.valueOf(e));
10305        }
10306    }
10307
10308    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10309        if (pkg == null) {
10310            Slog.wtf(TAG, "Package was null!", new Throwable());
10311            return;
10312        }
10313        clearAppProfilesLeafLIF(pkg);
10314        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10315        for (int i = 0; i < childCount; i++) {
10316            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10317        }
10318    }
10319
10320    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10321        try {
10322            mInstaller.clearAppProfiles(pkg.packageName);
10323        } catch (InstallerException e) {
10324            Slog.w(TAG, String.valueOf(e));
10325        }
10326    }
10327
10328    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10329            long lastUpdateTime) {
10330        // Set parent install/update time
10331        PackageSetting ps = (PackageSetting) pkg.mExtras;
10332        if (ps != null) {
10333            ps.firstInstallTime = firstInstallTime;
10334            ps.lastUpdateTime = lastUpdateTime;
10335        }
10336        // Set children install/update time
10337        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10338        for (int i = 0; i < childCount; i++) {
10339            PackageParser.Package childPkg = pkg.childPackages.get(i);
10340            ps = (PackageSetting) childPkg.mExtras;
10341            if (ps != null) {
10342                ps.firstInstallTime = firstInstallTime;
10343                ps.lastUpdateTime = lastUpdateTime;
10344            }
10345        }
10346    }
10347
10348    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10349            PackageParser.Package changingLib) {
10350        if (file.path != null) {
10351            usesLibraryFiles.add(file.path);
10352            return;
10353        }
10354        PackageParser.Package p = mPackages.get(file.apk);
10355        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10356            // If we are doing this while in the middle of updating a library apk,
10357            // then we need to make sure to use that new apk for determining the
10358            // dependencies here.  (We haven't yet finished committing the new apk
10359            // to the package manager state.)
10360            if (p == null || p.packageName.equals(changingLib.packageName)) {
10361                p = changingLib;
10362            }
10363        }
10364        if (p != null) {
10365            usesLibraryFiles.addAll(p.getAllCodePaths());
10366            if (p.usesLibraryFiles != null) {
10367                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10368            }
10369        }
10370    }
10371
10372    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10373            PackageParser.Package changingLib) throws PackageManagerException {
10374        if (pkg == null) {
10375            return;
10376        }
10377        ArraySet<String> usesLibraryFiles = null;
10378        if (pkg.usesLibraries != null) {
10379            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10380                    null, null, pkg.packageName, changingLib, true, null);
10381        }
10382        if (pkg.usesStaticLibraries != null) {
10383            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10384                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10385                    pkg.packageName, changingLib, true, usesLibraryFiles);
10386        }
10387        if (pkg.usesOptionalLibraries != null) {
10388            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10389                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10390        }
10391        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10392            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10393        } else {
10394            pkg.usesLibraryFiles = null;
10395        }
10396    }
10397
10398    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10399            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10400            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10401            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10402            throws PackageManagerException {
10403        final int libCount = requestedLibraries.size();
10404        for (int i = 0; i < libCount; i++) {
10405            final String libName = requestedLibraries.get(i);
10406            final int libVersion = requiredVersions != null ? requiredVersions[i]
10407                    : SharedLibraryInfo.VERSION_UNDEFINED;
10408            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10409            if (libEntry == null) {
10410                if (required) {
10411                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10412                            "Package " + packageName + " requires unavailable shared library "
10413                                    + libName + "; failing!");
10414                } else if (DEBUG_SHARED_LIBRARIES) {
10415                    Slog.i(TAG, "Package " + packageName
10416                            + " desires unavailable shared library "
10417                            + libName + "; ignoring!");
10418                }
10419            } else {
10420                if (requiredVersions != null && requiredCertDigests != null) {
10421                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10422                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10423                            "Package " + packageName + " requires unavailable static shared"
10424                                    + " library " + libName + " version "
10425                                    + libEntry.info.getVersion() + "; failing!");
10426                    }
10427
10428                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10429                    if (libPkg == null) {
10430                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10431                                "Package " + packageName + " requires unavailable static shared"
10432                                        + " library; failing!");
10433                    }
10434
10435                    String expectedCertDigest = requiredCertDigests[i];
10436                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10437                                libPkg.mSignatures[0]);
10438                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10439                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10440                                "Package " + packageName + " requires differently signed" +
10441                                        " static shared library; failing!");
10442                    }
10443                }
10444
10445                if (outUsedLibraries == null) {
10446                    outUsedLibraries = new ArraySet<>();
10447                }
10448                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10449            }
10450        }
10451        return outUsedLibraries;
10452    }
10453
10454    private static boolean hasString(List<String> list, List<String> which) {
10455        if (list == null) {
10456            return false;
10457        }
10458        for (int i=list.size()-1; i>=0; i--) {
10459            for (int j=which.size()-1; j>=0; j--) {
10460                if (which.get(j).equals(list.get(i))) {
10461                    return true;
10462                }
10463            }
10464        }
10465        return false;
10466    }
10467
10468    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10469            PackageParser.Package changingPkg) {
10470        ArrayList<PackageParser.Package> res = null;
10471        for (PackageParser.Package pkg : mPackages.values()) {
10472            if (changingPkg != null
10473                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10474                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10475                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10476                            changingPkg.staticSharedLibName)) {
10477                return null;
10478            }
10479            if (res == null) {
10480                res = new ArrayList<>();
10481            }
10482            res.add(pkg);
10483            try {
10484                updateSharedLibrariesLPr(pkg, changingPkg);
10485            } catch (PackageManagerException e) {
10486                // If a system app update or an app and a required lib missing we
10487                // delete the package and for updated system apps keep the data as
10488                // it is better for the user to reinstall than to be in an limbo
10489                // state. Also libs disappearing under an app should never happen
10490                // - just in case.
10491                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10492                    final int flags = pkg.isUpdatedSystemApp()
10493                            ? PackageManager.DELETE_KEEP_DATA : 0;
10494                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10495                            flags , null, true, null);
10496                }
10497                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10498            }
10499        }
10500        return res;
10501    }
10502
10503    /**
10504     * Derive the value of the {@code cpuAbiOverride} based on the provided
10505     * value and an optional stored value from the package settings.
10506     */
10507    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10508        String cpuAbiOverride = null;
10509
10510        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10511            cpuAbiOverride = null;
10512        } else if (abiOverride != null) {
10513            cpuAbiOverride = abiOverride;
10514        } else if (settings != null) {
10515            cpuAbiOverride = settings.cpuAbiOverrideString;
10516        }
10517
10518        return cpuAbiOverride;
10519    }
10520
10521    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10522            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10523                    throws PackageManagerException {
10524        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10525        // If the package has children and this is the first dive in the function
10526        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10527        // whether all packages (parent and children) would be successfully scanned
10528        // before the actual scan since scanning mutates internal state and we want
10529        // to atomically install the package and its children.
10530        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10531            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10532                scanFlags |= SCAN_CHECK_ONLY;
10533            }
10534        } else {
10535            scanFlags &= ~SCAN_CHECK_ONLY;
10536        }
10537
10538        final PackageParser.Package scannedPkg;
10539        try {
10540            // Scan the parent
10541            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10542            // Scan the children
10543            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10544            for (int i = 0; i < childCount; i++) {
10545                PackageParser.Package childPkg = pkg.childPackages.get(i);
10546                scanPackageLI(childPkg, policyFlags,
10547                        scanFlags, currentTime, user);
10548            }
10549        } finally {
10550            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10551        }
10552
10553        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10554            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10555        }
10556
10557        return scannedPkg;
10558    }
10559
10560    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10561            int scanFlags, long currentTime, @Nullable UserHandle user)
10562                    throws PackageManagerException {
10563        boolean success = false;
10564        try {
10565            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10566                    currentTime, user);
10567            success = true;
10568            return res;
10569        } finally {
10570            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10571                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10572                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10573                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10574                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10575            }
10576        }
10577    }
10578
10579    /**
10580     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10581     */
10582    private static boolean apkHasCode(String fileName) {
10583        StrictJarFile jarFile = null;
10584        try {
10585            jarFile = new StrictJarFile(fileName,
10586                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10587            return jarFile.findEntry("classes.dex") != null;
10588        } catch (IOException ignore) {
10589        } finally {
10590            try {
10591                if (jarFile != null) {
10592                    jarFile.close();
10593                }
10594            } catch (IOException ignore) {}
10595        }
10596        return false;
10597    }
10598
10599    /**
10600     * Enforces code policy for the package. This ensures that if an APK has
10601     * declared hasCode="true" in its manifest that the APK actually contains
10602     * code.
10603     *
10604     * @throws PackageManagerException If bytecode could not be found when it should exist
10605     */
10606    private static void assertCodePolicy(PackageParser.Package pkg)
10607            throws PackageManagerException {
10608        final boolean shouldHaveCode =
10609                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10610        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10611            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10612                    "Package " + pkg.baseCodePath + " code is missing");
10613        }
10614
10615        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10616            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10617                final boolean splitShouldHaveCode =
10618                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10619                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10620                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10621                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10622                }
10623            }
10624        }
10625    }
10626
10627    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10628            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10629                    throws PackageManagerException {
10630        if (DEBUG_PACKAGE_SCANNING) {
10631            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10632                Log.d(TAG, "Scanning package " + pkg.packageName);
10633        }
10634
10635        applyPolicy(pkg, policyFlags);
10636
10637        assertPackageIsValid(pkg, policyFlags, scanFlags);
10638
10639        // Initialize package source and resource directories
10640        final File scanFile = new File(pkg.codePath);
10641        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10642        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10643
10644        SharedUserSetting suid = null;
10645        PackageSetting pkgSetting = null;
10646
10647        // Getting the package setting may have a side-effect, so if we
10648        // are only checking if scan would succeed, stash a copy of the
10649        // old setting to restore at the end.
10650        PackageSetting nonMutatedPs = null;
10651
10652        // We keep references to the derived CPU Abis from settings in oder to reuse
10653        // them in the case where we're not upgrading or booting for the first time.
10654        String primaryCpuAbiFromSettings = null;
10655        String secondaryCpuAbiFromSettings = null;
10656
10657        // writer
10658        synchronized (mPackages) {
10659            if (pkg.mSharedUserId != null) {
10660                // SIDE EFFECTS; may potentially allocate a new shared user
10661                suid = mSettings.getSharedUserLPw(
10662                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10663                if (DEBUG_PACKAGE_SCANNING) {
10664                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10665                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10666                                + "): packages=" + suid.packages);
10667                }
10668            }
10669
10670            // Check if we are renaming from an original package name.
10671            PackageSetting origPackage = null;
10672            String realName = null;
10673            if (pkg.mOriginalPackages != null) {
10674                // This package may need to be renamed to a previously
10675                // installed name.  Let's check on that...
10676                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10677                if (pkg.mOriginalPackages.contains(renamed)) {
10678                    // This package had originally been installed as the
10679                    // original name, and we have already taken care of
10680                    // transitioning to the new one.  Just update the new
10681                    // one to continue using the old name.
10682                    realName = pkg.mRealPackage;
10683                    if (!pkg.packageName.equals(renamed)) {
10684                        // Callers into this function may have already taken
10685                        // care of renaming the package; only do it here if
10686                        // it is not already done.
10687                        pkg.setPackageName(renamed);
10688                    }
10689                } else {
10690                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10691                        if ((origPackage = mSettings.getPackageLPr(
10692                                pkg.mOriginalPackages.get(i))) != null) {
10693                            // We do have the package already installed under its
10694                            // original name...  should we use it?
10695                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10696                                // New package is not compatible with original.
10697                                origPackage = null;
10698                                continue;
10699                            } else if (origPackage.sharedUser != null) {
10700                                // Make sure uid is compatible between packages.
10701                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10702                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10703                                            + " to " + pkg.packageName + ": old uid "
10704                                            + origPackage.sharedUser.name
10705                                            + " differs from " + pkg.mSharedUserId);
10706                                    origPackage = null;
10707                                    continue;
10708                                }
10709                                // TODO: Add case when shared user id is added [b/28144775]
10710                            } else {
10711                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10712                                        + pkg.packageName + " to old name " + origPackage.name);
10713                            }
10714                            break;
10715                        }
10716                    }
10717                }
10718            }
10719
10720            if (mTransferedPackages.contains(pkg.packageName)) {
10721                Slog.w(TAG, "Package " + pkg.packageName
10722                        + " was transferred to another, but its .apk remains");
10723            }
10724
10725            // See comments in nonMutatedPs declaration
10726            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10727                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10728                if (foundPs != null) {
10729                    nonMutatedPs = new PackageSetting(foundPs);
10730                }
10731            }
10732
10733            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10734                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10735                if (foundPs != null) {
10736                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10737                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10738                }
10739            }
10740
10741            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10742            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10743                PackageManagerService.reportSettingsProblem(Log.WARN,
10744                        "Package " + pkg.packageName + " shared user changed from "
10745                                + (pkgSetting.sharedUser != null
10746                                        ? pkgSetting.sharedUser.name : "<nothing>")
10747                                + " to "
10748                                + (suid != null ? suid.name : "<nothing>")
10749                                + "; replacing with new");
10750                pkgSetting = null;
10751            }
10752            final PackageSetting oldPkgSetting =
10753                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10754            final PackageSetting disabledPkgSetting =
10755                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10756
10757            String[] usesStaticLibraries = null;
10758            if (pkg.usesStaticLibraries != null) {
10759                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10760                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10761            }
10762
10763            if (pkgSetting == null) {
10764                final String parentPackageName = (pkg.parentPackage != null)
10765                        ? pkg.parentPackage.packageName : null;
10766                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10767                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10768                // REMOVE SharedUserSetting from method; update in a separate call
10769                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10770                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10771                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10772                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10773                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10774                        true /*allowInstall*/, instantApp, virtualPreload,
10775                        parentPackageName, pkg.getChildPackageNames(),
10776                        UserManagerService.getInstance(), usesStaticLibraries,
10777                        pkg.usesStaticLibrariesVersions);
10778                // SIDE EFFECTS; updates system state; move elsewhere
10779                if (origPackage != null) {
10780                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10781                }
10782                mSettings.addUserToSettingLPw(pkgSetting);
10783            } else {
10784                // REMOVE SharedUserSetting from method; update in a separate call.
10785                //
10786                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10787                // secondaryCpuAbi are not known at this point so we always update them
10788                // to null here, only to reset them at a later point.
10789                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10790                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10791                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10792                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10793                        UserManagerService.getInstance(), usesStaticLibraries,
10794                        pkg.usesStaticLibrariesVersions);
10795            }
10796            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10797            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10798
10799            // SIDE EFFECTS; modifies system state; move elsewhere
10800            if (pkgSetting.origPackage != null) {
10801                // If we are first transitioning from an original package,
10802                // fix up the new package's name now.  We need to do this after
10803                // looking up the package under its new name, so getPackageLP
10804                // can take care of fiddling things correctly.
10805                pkg.setPackageName(origPackage.name);
10806
10807                // File a report about this.
10808                String msg = "New package " + pkgSetting.realName
10809                        + " renamed to replace old package " + pkgSetting.name;
10810                reportSettingsProblem(Log.WARN, msg);
10811
10812                // Make a note of it.
10813                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10814                    mTransferedPackages.add(origPackage.name);
10815                }
10816
10817                // No longer need to retain this.
10818                pkgSetting.origPackage = null;
10819            }
10820
10821            // SIDE EFFECTS; modifies system state; move elsewhere
10822            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10823                // Make a note of it.
10824                mTransferedPackages.add(pkg.packageName);
10825            }
10826
10827            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10828                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10829            }
10830
10831            if ((scanFlags & SCAN_BOOTING) == 0
10832                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10833                // Check all shared libraries and map to their actual file path.
10834                // We only do this here for apps not on a system dir, because those
10835                // are the only ones that can fail an install due to this.  We
10836                // will take care of the system apps by updating all of their
10837                // library paths after the scan is done. Also during the initial
10838                // scan don't update any libs as we do this wholesale after all
10839                // apps are scanned to avoid dependency based scanning.
10840                updateSharedLibrariesLPr(pkg, null);
10841            }
10842
10843            if (mFoundPolicyFile) {
10844                SELinuxMMAC.assignSeInfoValue(pkg);
10845            }
10846            pkg.applicationInfo.uid = pkgSetting.appId;
10847            pkg.mExtras = pkgSetting;
10848
10849
10850            // Static shared libs have same package with different versions where
10851            // we internally use a synthetic package name to allow multiple versions
10852            // of the same package, therefore we need to compare signatures against
10853            // the package setting for the latest library version.
10854            PackageSetting signatureCheckPs = pkgSetting;
10855            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10856                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10857                if (libraryEntry != null) {
10858                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10859                }
10860            }
10861
10862            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10863                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10864                    // We just determined the app is signed correctly, so bring
10865                    // over the latest parsed certs.
10866                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10867                } else {
10868                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10869                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10870                                "Package " + pkg.packageName + " upgrade keys do not match the "
10871                                + "previously installed version");
10872                    } else {
10873                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10874                        String msg = "System package " + pkg.packageName
10875                                + " signature changed; retaining data.";
10876                        reportSettingsProblem(Log.WARN, msg);
10877                    }
10878                }
10879            } else {
10880                try {
10881                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10882                    verifySignaturesLP(signatureCheckPs, pkg);
10883                    // We just determined the app is signed correctly, so bring
10884                    // over the latest parsed certs.
10885                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10886                } catch (PackageManagerException e) {
10887                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10888                        throw e;
10889                    }
10890                    // The signature has changed, but this package is in the system
10891                    // image...  let's recover!
10892                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10893                    // However...  if this package is part of a shared user, but it
10894                    // doesn't match the signature of the shared user, let's fail.
10895                    // What this means is that you can't change the signatures
10896                    // associated with an overall shared user, which doesn't seem all
10897                    // that unreasonable.
10898                    if (signatureCheckPs.sharedUser != null) {
10899                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10900                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10901                            throw new PackageManagerException(
10902                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10903                                    "Signature mismatch for shared user: "
10904                                            + pkgSetting.sharedUser);
10905                        }
10906                    }
10907                    // File a report about this.
10908                    String msg = "System package " + pkg.packageName
10909                            + " signature changed; retaining data.";
10910                    reportSettingsProblem(Log.WARN, msg);
10911                }
10912            }
10913
10914            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10915                // This package wants to adopt ownership of permissions from
10916                // another package.
10917                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10918                    final String origName = pkg.mAdoptPermissions.get(i);
10919                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10920                    if (orig != null) {
10921                        if (verifyPackageUpdateLPr(orig, pkg)) {
10922                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10923                                    + pkg.packageName);
10924                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10925                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10926                        }
10927                    }
10928                }
10929            }
10930        }
10931
10932        pkg.applicationInfo.processName = fixProcessName(
10933                pkg.applicationInfo.packageName,
10934                pkg.applicationInfo.processName);
10935
10936        if (pkg != mPlatformPackage) {
10937            // Get all of our default paths setup
10938            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10939        }
10940
10941        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10942
10943        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10944            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10945                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10946                final boolean extractNativeLibs = !pkg.isLibrary();
10947                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10948                        mAppLib32InstallDir);
10949                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10950
10951                // Some system apps still use directory structure for native libraries
10952                // in which case we might end up not detecting abi solely based on apk
10953                // structure. Try to detect abi based on directory structure.
10954                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10955                        pkg.applicationInfo.primaryCpuAbi == null) {
10956                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10957                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10958                }
10959            } else {
10960                // This is not a first boot or an upgrade, don't bother deriving the
10961                // ABI during the scan. Instead, trust the value that was stored in the
10962                // package setting.
10963                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10964                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10965
10966                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10967
10968                if (DEBUG_ABI_SELECTION) {
10969                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10970                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10971                        pkg.applicationInfo.secondaryCpuAbi);
10972                }
10973            }
10974        } else {
10975            if ((scanFlags & SCAN_MOVE) != 0) {
10976                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10977                // but we already have this packages package info in the PackageSetting. We just
10978                // use that and derive the native library path based on the new codepath.
10979                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10980                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10981            }
10982
10983            // Set native library paths again. For moves, the path will be updated based on the
10984            // ABIs we've determined above. For non-moves, the path will be updated based on the
10985            // ABIs we determined during compilation, but the path will depend on the final
10986            // package path (after the rename away from the stage path).
10987            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10988        }
10989
10990        // This is a special case for the "system" package, where the ABI is
10991        // dictated by the zygote configuration (and init.rc). We should keep track
10992        // of this ABI so that we can deal with "normal" applications that run under
10993        // the same UID correctly.
10994        if (mPlatformPackage == pkg) {
10995            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10996                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10997        }
10998
10999        // If there's a mismatch between the abi-override in the package setting
11000        // and the abiOverride specified for the install. Warn about this because we
11001        // would've already compiled the app without taking the package setting into
11002        // account.
11003        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11004            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11005                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11006                        " for package " + pkg.packageName);
11007            }
11008        }
11009
11010        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11011        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11012        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11013
11014        // Copy the derived override back to the parsed package, so that we can
11015        // update the package settings accordingly.
11016        pkg.cpuAbiOverride = cpuAbiOverride;
11017
11018        if (DEBUG_ABI_SELECTION) {
11019            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11020                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11021                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11022        }
11023
11024        // Push the derived path down into PackageSettings so we know what to
11025        // clean up at uninstall time.
11026        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11027
11028        if (DEBUG_ABI_SELECTION) {
11029            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11030                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11031                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11032        }
11033
11034        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11035        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11036            // We don't do this here during boot because we can do it all
11037            // at once after scanning all existing packages.
11038            //
11039            // We also do this *before* we perform dexopt on this package, so that
11040            // we can avoid redundant dexopts, and also to make sure we've got the
11041            // code and package path correct.
11042            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11043        }
11044
11045        if (mFactoryTest && pkg.requestedPermissions.contains(
11046                android.Manifest.permission.FACTORY_TEST)) {
11047            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11048        }
11049
11050        if (isSystemApp(pkg)) {
11051            pkgSetting.isOrphaned = true;
11052        }
11053
11054        // Take care of first install / last update times.
11055        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11056        if (currentTime != 0) {
11057            if (pkgSetting.firstInstallTime == 0) {
11058                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11059            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11060                pkgSetting.lastUpdateTime = currentTime;
11061            }
11062        } else if (pkgSetting.firstInstallTime == 0) {
11063            // We need *something*.  Take time time stamp of the file.
11064            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11065        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11066            if (scanFileTime != pkgSetting.timeStamp) {
11067                // A package on the system image has changed; consider this
11068                // to be an update.
11069                pkgSetting.lastUpdateTime = scanFileTime;
11070            }
11071        }
11072        pkgSetting.setTimeStamp(scanFileTime);
11073
11074        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11075            if (nonMutatedPs != null) {
11076                synchronized (mPackages) {
11077                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11078                }
11079            }
11080        } else {
11081            final int userId = user == null ? 0 : user.getIdentifier();
11082            // Modify state for the given package setting
11083            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11084                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11085            if (pkgSetting.getInstantApp(userId)) {
11086                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11087            }
11088        }
11089        return pkg;
11090    }
11091
11092    /**
11093     * Applies policy to the parsed package based upon the given policy flags.
11094     * Ensures the package is in a good state.
11095     * <p>
11096     * Implementation detail: This method must NOT have any side effect. It would
11097     * ideally be static, but, it requires locks to read system state.
11098     */
11099    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11100        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11101            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11102            if (pkg.applicationInfo.isDirectBootAware()) {
11103                // we're direct boot aware; set for all components
11104                for (PackageParser.Service s : pkg.services) {
11105                    s.info.encryptionAware = s.info.directBootAware = true;
11106                }
11107                for (PackageParser.Provider p : pkg.providers) {
11108                    p.info.encryptionAware = p.info.directBootAware = true;
11109                }
11110                for (PackageParser.Activity a : pkg.activities) {
11111                    a.info.encryptionAware = a.info.directBootAware = true;
11112                }
11113                for (PackageParser.Activity r : pkg.receivers) {
11114                    r.info.encryptionAware = r.info.directBootAware = true;
11115                }
11116            }
11117            if (compressedFileExists(pkg.codePath)) {
11118                pkg.isStub = true;
11119            }
11120        } else {
11121            // Only allow system apps to be flagged as core apps.
11122            pkg.coreApp = false;
11123            // clear flags not applicable to regular apps
11124            pkg.applicationInfo.privateFlags &=
11125                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11126            pkg.applicationInfo.privateFlags &=
11127                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11128        }
11129        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11130
11131        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11132            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11133        }
11134
11135        if (!isSystemApp(pkg)) {
11136            // Only system apps can use these features.
11137            pkg.mOriginalPackages = null;
11138            pkg.mRealPackage = null;
11139            pkg.mAdoptPermissions = null;
11140        }
11141    }
11142
11143    /**
11144     * Asserts the parsed package is valid according to the given policy. If the
11145     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11146     * <p>
11147     * Implementation detail: This method must NOT have any side effects. It would
11148     * ideally be static, but, it requires locks to read system state.
11149     *
11150     * @throws PackageManagerException If the package fails any of the validation checks
11151     */
11152    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11153            throws PackageManagerException {
11154        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11155            assertCodePolicy(pkg);
11156        }
11157
11158        if (pkg.applicationInfo.getCodePath() == null ||
11159                pkg.applicationInfo.getResourcePath() == null) {
11160            // Bail out. The resource and code paths haven't been set.
11161            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11162                    "Code and resource paths haven't been set correctly");
11163        }
11164
11165        // Make sure we're not adding any bogus keyset info
11166        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11167        ksms.assertScannedPackageValid(pkg);
11168
11169        synchronized (mPackages) {
11170            // The special "android" package can only be defined once
11171            if (pkg.packageName.equals("android")) {
11172                if (mAndroidApplication != null) {
11173                    Slog.w(TAG, "*************************************************");
11174                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11175                    Slog.w(TAG, " codePath=" + pkg.codePath);
11176                    Slog.w(TAG, "*************************************************");
11177                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11178                            "Core android package being redefined.  Skipping.");
11179                }
11180            }
11181
11182            // A package name must be unique; don't allow duplicates
11183            if (mPackages.containsKey(pkg.packageName)) {
11184                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11185                        "Application package " + pkg.packageName
11186                        + " already installed.  Skipping duplicate.");
11187            }
11188
11189            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11190                // Static libs have a synthetic package name containing the version
11191                // but we still want the base name to be unique.
11192                if (mPackages.containsKey(pkg.manifestPackageName)) {
11193                    throw new PackageManagerException(
11194                            "Duplicate static shared lib provider package");
11195                }
11196
11197                // Static shared libraries should have at least O target SDK
11198                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11199                    throw new PackageManagerException(
11200                            "Packages declaring static-shared libs must target O SDK or higher");
11201                }
11202
11203                // Package declaring static a shared lib cannot be instant apps
11204                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11205                    throw new PackageManagerException(
11206                            "Packages declaring static-shared libs cannot be instant apps");
11207                }
11208
11209                // Package declaring static a shared lib cannot be renamed since the package
11210                // name is synthetic and apps can't code around package manager internals.
11211                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11212                    throw new PackageManagerException(
11213                            "Packages declaring static-shared libs cannot be renamed");
11214                }
11215
11216                // Package declaring static a shared lib cannot declare child packages
11217                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11218                    throw new PackageManagerException(
11219                            "Packages declaring static-shared libs cannot have child packages");
11220                }
11221
11222                // Package declaring static a shared lib cannot declare dynamic libs
11223                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11224                    throw new PackageManagerException(
11225                            "Packages declaring static-shared libs cannot declare dynamic libs");
11226                }
11227
11228                // Package declaring static a shared lib cannot declare shared users
11229                if (pkg.mSharedUserId != null) {
11230                    throw new PackageManagerException(
11231                            "Packages declaring static-shared libs cannot declare shared users");
11232                }
11233
11234                // Static shared libs cannot declare activities
11235                if (!pkg.activities.isEmpty()) {
11236                    throw new PackageManagerException(
11237                            "Static shared libs cannot declare activities");
11238                }
11239
11240                // Static shared libs cannot declare services
11241                if (!pkg.services.isEmpty()) {
11242                    throw new PackageManagerException(
11243                            "Static shared libs cannot declare services");
11244                }
11245
11246                // Static shared libs cannot declare providers
11247                if (!pkg.providers.isEmpty()) {
11248                    throw new PackageManagerException(
11249                            "Static shared libs cannot declare content providers");
11250                }
11251
11252                // Static shared libs cannot declare receivers
11253                if (!pkg.receivers.isEmpty()) {
11254                    throw new PackageManagerException(
11255                            "Static shared libs cannot declare broadcast receivers");
11256                }
11257
11258                // Static shared libs cannot declare permission groups
11259                if (!pkg.permissionGroups.isEmpty()) {
11260                    throw new PackageManagerException(
11261                            "Static shared libs cannot declare permission groups");
11262                }
11263
11264                // Static shared libs cannot declare permissions
11265                if (!pkg.permissions.isEmpty()) {
11266                    throw new PackageManagerException(
11267                            "Static shared libs cannot declare permissions");
11268                }
11269
11270                // Static shared libs cannot declare protected broadcasts
11271                if (pkg.protectedBroadcasts != null) {
11272                    throw new PackageManagerException(
11273                            "Static shared libs cannot declare protected broadcasts");
11274                }
11275
11276                // Static shared libs cannot be overlay targets
11277                if (pkg.mOverlayTarget != null) {
11278                    throw new PackageManagerException(
11279                            "Static shared libs cannot be overlay targets");
11280                }
11281
11282                // The version codes must be ordered as lib versions
11283                int minVersionCode = Integer.MIN_VALUE;
11284                int maxVersionCode = Integer.MAX_VALUE;
11285
11286                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11287                        pkg.staticSharedLibName);
11288                if (versionedLib != null) {
11289                    final int versionCount = versionedLib.size();
11290                    for (int i = 0; i < versionCount; i++) {
11291                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11292                        final int libVersionCode = libInfo.getDeclaringPackage()
11293                                .getVersionCode();
11294                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11295                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11296                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11297                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11298                        } else {
11299                            minVersionCode = maxVersionCode = libVersionCode;
11300                            break;
11301                        }
11302                    }
11303                }
11304                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11305                    throw new PackageManagerException("Static shared"
11306                            + " lib version codes must be ordered as lib versions");
11307                }
11308            }
11309
11310            // Only privileged apps and updated privileged apps can add child packages.
11311            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11312                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11313                    throw new PackageManagerException("Only privileged apps can add child "
11314                            + "packages. Ignoring package " + pkg.packageName);
11315                }
11316                final int childCount = pkg.childPackages.size();
11317                for (int i = 0; i < childCount; i++) {
11318                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11319                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11320                            childPkg.packageName)) {
11321                        throw new PackageManagerException("Can't override child of "
11322                                + "another disabled app. Ignoring package " + pkg.packageName);
11323                    }
11324                }
11325            }
11326
11327            // If we're only installing presumed-existing packages, require that the
11328            // scanned APK is both already known and at the path previously established
11329            // for it.  Previously unknown packages we pick up normally, but if we have an
11330            // a priori expectation about this package's install presence, enforce it.
11331            // With a singular exception for new system packages. When an OTA contains
11332            // a new system package, we allow the codepath to change from a system location
11333            // to the user-installed location. If we don't allow this change, any newer,
11334            // user-installed version of the application will be ignored.
11335            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11336                if (mExpectingBetter.containsKey(pkg.packageName)) {
11337                    logCriticalInfo(Log.WARN,
11338                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11339                } else {
11340                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11341                    if (known != null) {
11342                        if (DEBUG_PACKAGE_SCANNING) {
11343                            Log.d(TAG, "Examining " + pkg.codePath
11344                                    + " and requiring known paths " + known.codePathString
11345                                    + " & " + known.resourcePathString);
11346                        }
11347                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11348                                || !pkg.applicationInfo.getResourcePath().equals(
11349                                        known.resourcePathString)) {
11350                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11351                                    "Application package " + pkg.packageName
11352                                    + " found at " + pkg.applicationInfo.getCodePath()
11353                                    + " but expected at " + known.codePathString
11354                                    + "; ignoring.");
11355                        }
11356                    }
11357                }
11358            }
11359
11360            // Verify that this new package doesn't have any content providers
11361            // that conflict with existing packages.  Only do this if the
11362            // package isn't already installed, since we don't want to break
11363            // things that are installed.
11364            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11365                final int N = pkg.providers.size();
11366                int i;
11367                for (i=0; i<N; i++) {
11368                    PackageParser.Provider p = pkg.providers.get(i);
11369                    if (p.info.authority != null) {
11370                        String names[] = p.info.authority.split(";");
11371                        for (int j = 0; j < names.length; j++) {
11372                            if (mProvidersByAuthority.containsKey(names[j])) {
11373                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11374                                final String otherPackageName =
11375                                        ((other != null && other.getComponentName() != null) ?
11376                                                other.getComponentName().getPackageName() : "?");
11377                                throw new PackageManagerException(
11378                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11379                                        "Can't install because provider name " + names[j]
11380                                                + " (in package " + pkg.applicationInfo.packageName
11381                                                + ") is already used by " + otherPackageName);
11382                            }
11383                        }
11384                    }
11385                }
11386            }
11387        }
11388    }
11389
11390    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11391            int type, String declaringPackageName, int declaringVersionCode) {
11392        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11393        if (versionedLib == null) {
11394            versionedLib = new SparseArray<>();
11395            mSharedLibraries.put(name, versionedLib);
11396            if (type == SharedLibraryInfo.TYPE_STATIC) {
11397                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11398            }
11399        } else if (versionedLib.indexOfKey(version) >= 0) {
11400            return false;
11401        }
11402        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11403                version, type, declaringPackageName, declaringVersionCode);
11404        versionedLib.put(version, libEntry);
11405        return true;
11406    }
11407
11408    private boolean removeSharedLibraryLPw(String name, int version) {
11409        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11410        if (versionedLib == null) {
11411            return false;
11412        }
11413        final int libIdx = versionedLib.indexOfKey(version);
11414        if (libIdx < 0) {
11415            return false;
11416        }
11417        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11418        versionedLib.remove(version);
11419        if (versionedLib.size() <= 0) {
11420            mSharedLibraries.remove(name);
11421            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11422                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11423                        .getPackageName());
11424            }
11425        }
11426        return true;
11427    }
11428
11429    /**
11430     * Adds a scanned package to the system. When this method is finished, the package will
11431     * be available for query, resolution, etc...
11432     */
11433    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11434            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11435        final String pkgName = pkg.packageName;
11436        if (mCustomResolverComponentName != null &&
11437                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11438            setUpCustomResolverActivity(pkg);
11439        }
11440
11441        if (pkg.packageName.equals("android")) {
11442            synchronized (mPackages) {
11443                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11444                    // Set up information for our fall-back user intent resolution activity.
11445                    mPlatformPackage = pkg;
11446                    pkg.mVersionCode = mSdkVersion;
11447                    mAndroidApplication = pkg.applicationInfo;
11448                    if (!mResolverReplaced) {
11449                        mResolveActivity.applicationInfo = mAndroidApplication;
11450                        mResolveActivity.name = ResolverActivity.class.getName();
11451                        mResolveActivity.packageName = mAndroidApplication.packageName;
11452                        mResolveActivity.processName = "system:ui";
11453                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11454                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11455                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11456                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11457                        mResolveActivity.exported = true;
11458                        mResolveActivity.enabled = true;
11459                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11460                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11461                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11462                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11463                                | ActivityInfo.CONFIG_ORIENTATION
11464                                | ActivityInfo.CONFIG_KEYBOARD
11465                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11466                        mResolveInfo.activityInfo = mResolveActivity;
11467                        mResolveInfo.priority = 0;
11468                        mResolveInfo.preferredOrder = 0;
11469                        mResolveInfo.match = 0;
11470                        mResolveComponentName = new ComponentName(
11471                                mAndroidApplication.packageName, mResolveActivity.name);
11472                    }
11473                }
11474            }
11475        }
11476
11477        ArrayList<PackageParser.Package> clientLibPkgs = null;
11478        // writer
11479        synchronized (mPackages) {
11480            boolean hasStaticSharedLibs = false;
11481
11482            // Any app can add new static shared libraries
11483            if (pkg.staticSharedLibName != null) {
11484                // Static shared libs don't allow renaming as they have synthetic package
11485                // names to allow install of multiple versions, so use name from manifest.
11486                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11487                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11488                        pkg.manifestPackageName, pkg.mVersionCode)) {
11489                    hasStaticSharedLibs = true;
11490                } else {
11491                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11492                                + pkg.staticSharedLibName + " already exists; skipping");
11493                }
11494                // Static shared libs cannot be updated once installed since they
11495                // use synthetic package name which includes the version code, so
11496                // not need to update other packages's shared lib dependencies.
11497            }
11498
11499            if (!hasStaticSharedLibs
11500                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11501                // Only system apps can add new dynamic shared libraries.
11502                if (pkg.libraryNames != null) {
11503                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11504                        String name = pkg.libraryNames.get(i);
11505                        boolean allowed = false;
11506                        if (pkg.isUpdatedSystemApp()) {
11507                            // New library entries can only be added through the
11508                            // system image.  This is important to get rid of a lot
11509                            // of nasty edge cases: for example if we allowed a non-
11510                            // system update of the app to add a library, then uninstalling
11511                            // the update would make the library go away, and assumptions
11512                            // we made such as through app install filtering would now
11513                            // have allowed apps on the device which aren't compatible
11514                            // with it.  Better to just have the restriction here, be
11515                            // conservative, and create many fewer cases that can negatively
11516                            // impact the user experience.
11517                            final PackageSetting sysPs = mSettings
11518                                    .getDisabledSystemPkgLPr(pkg.packageName);
11519                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11520                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11521                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11522                                        allowed = true;
11523                                        break;
11524                                    }
11525                                }
11526                            }
11527                        } else {
11528                            allowed = true;
11529                        }
11530                        if (allowed) {
11531                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11532                                    SharedLibraryInfo.VERSION_UNDEFINED,
11533                                    SharedLibraryInfo.TYPE_DYNAMIC,
11534                                    pkg.packageName, pkg.mVersionCode)) {
11535                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11536                                        + name + " already exists; skipping");
11537                            }
11538                        } else {
11539                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11540                                    + name + " that is not declared on system image; skipping");
11541                        }
11542                    }
11543
11544                    if ((scanFlags & SCAN_BOOTING) == 0) {
11545                        // If we are not booting, we need to update any applications
11546                        // that are clients of our shared library.  If we are booting,
11547                        // this will all be done once the scan is complete.
11548                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11549                    }
11550                }
11551            }
11552        }
11553
11554        if ((scanFlags & SCAN_BOOTING) != 0) {
11555            // No apps can run during boot scan, so they don't need to be frozen
11556        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11557            // Caller asked to not kill app, so it's probably not frozen
11558        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11559            // Caller asked us to ignore frozen check for some reason; they
11560            // probably didn't know the package name
11561        } else {
11562            // We're doing major surgery on this package, so it better be frozen
11563            // right now to keep it from launching
11564            checkPackageFrozen(pkgName);
11565        }
11566
11567        // Also need to kill any apps that are dependent on the library.
11568        if (clientLibPkgs != null) {
11569            for (int i=0; i<clientLibPkgs.size(); i++) {
11570                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11571                killApplication(clientPkg.applicationInfo.packageName,
11572                        clientPkg.applicationInfo.uid, "update lib");
11573            }
11574        }
11575
11576        // writer
11577        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11578
11579        synchronized (mPackages) {
11580            // We don't expect installation to fail beyond this point
11581
11582            // Add the new setting to mSettings
11583            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11584            // Add the new setting to mPackages
11585            mPackages.put(pkg.applicationInfo.packageName, pkg);
11586            // Make sure we don't accidentally delete its data.
11587            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11588            while (iter.hasNext()) {
11589                PackageCleanItem item = iter.next();
11590                if (pkgName.equals(item.packageName)) {
11591                    iter.remove();
11592                }
11593            }
11594
11595            // Add the package's KeySets to the global KeySetManagerService
11596            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11597            ksms.addScannedPackageLPw(pkg);
11598
11599            int N = pkg.providers.size();
11600            StringBuilder r = null;
11601            int i;
11602            for (i=0; i<N; i++) {
11603                PackageParser.Provider p = pkg.providers.get(i);
11604                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11605                        p.info.processName);
11606                mProviders.addProvider(p);
11607                p.syncable = p.info.isSyncable;
11608                if (p.info.authority != null) {
11609                    String names[] = p.info.authority.split(";");
11610                    p.info.authority = null;
11611                    for (int j = 0; j < names.length; j++) {
11612                        if (j == 1 && p.syncable) {
11613                            // We only want the first authority for a provider to possibly be
11614                            // syncable, so if we already added this provider using a different
11615                            // authority clear the syncable flag. We copy the provider before
11616                            // changing it because the mProviders object contains a reference
11617                            // to a provider that we don't want to change.
11618                            // Only do this for the second authority since the resulting provider
11619                            // object can be the same for all future authorities for this provider.
11620                            p = new PackageParser.Provider(p);
11621                            p.syncable = false;
11622                        }
11623                        if (!mProvidersByAuthority.containsKey(names[j])) {
11624                            mProvidersByAuthority.put(names[j], p);
11625                            if (p.info.authority == null) {
11626                                p.info.authority = names[j];
11627                            } else {
11628                                p.info.authority = p.info.authority + ";" + names[j];
11629                            }
11630                            if (DEBUG_PACKAGE_SCANNING) {
11631                                if (chatty)
11632                                    Log.d(TAG, "Registered content provider: " + names[j]
11633                                            + ", className = " + p.info.name + ", isSyncable = "
11634                                            + p.info.isSyncable);
11635                            }
11636                        } else {
11637                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11638                            Slog.w(TAG, "Skipping provider name " + names[j] +
11639                                    " (in package " + pkg.applicationInfo.packageName +
11640                                    "): name already used by "
11641                                    + ((other != null && other.getComponentName() != null)
11642                                            ? other.getComponentName().getPackageName() : "?"));
11643                        }
11644                    }
11645                }
11646                if (chatty) {
11647                    if (r == null) {
11648                        r = new StringBuilder(256);
11649                    } else {
11650                        r.append(' ');
11651                    }
11652                    r.append(p.info.name);
11653                }
11654            }
11655            if (r != null) {
11656                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11657            }
11658
11659            N = pkg.services.size();
11660            r = null;
11661            for (i=0; i<N; i++) {
11662                PackageParser.Service s = pkg.services.get(i);
11663                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11664                        s.info.processName);
11665                mServices.addService(s);
11666                if (chatty) {
11667                    if (r == null) {
11668                        r = new StringBuilder(256);
11669                    } else {
11670                        r.append(' ');
11671                    }
11672                    r.append(s.info.name);
11673                }
11674            }
11675            if (r != null) {
11676                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11677            }
11678
11679            N = pkg.receivers.size();
11680            r = null;
11681            for (i=0; i<N; i++) {
11682                PackageParser.Activity a = pkg.receivers.get(i);
11683                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11684                        a.info.processName);
11685                mReceivers.addActivity(a, "receiver");
11686                if (chatty) {
11687                    if (r == null) {
11688                        r = new StringBuilder(256);
11689                    } else {
11690                        r.append(' ');
11691                    }
11692                    r.append(a.info.name);
11693                }
11694            }
11695            if (r != null) {
11696                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11697            }
11698
11699            N = pkg.activities.size();
11700            r = null;
11701            for (i=0; i<N; i++) {
11702                PackageParser.Activity a = pkg.activities.get(i);
11703                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11704                        a.info.processName);
11705                mActivities.addActivity(a, "activity");
11706                if (chatty) {
11707                    if (r == null) {
11708                        r = new StringBuilder(256);
11709                    } else {
11710                        r.append(' ');
11711                    }
11712                    r.append(a.info.name);
11713                }
11714            }
11715            if (r != null) {
11716                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11717            }
11718
11719            N = pkg.permissionGroups.size();
11720            r = null;
11721            for (i=0; i<N; i++) {
11722                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11723                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11724                final String curPackageName = cur == null ? null : cur.info.packageName;
11725                // Dont allow ephemeral apps to define new permission groups.
11726                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11727                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11728                            + pg.info.packageName
11729                            + " ignored: instant apps cannot define new permission groups.");
11730                    continue;
11731                }
11732                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11733                if (cur == null || isPackageUpdate) {
11734                    mPermissionGroups.put(pg.info.name, pg);
11735                    if (chatty) {
11736                        if (r == null) {
11737                            r = new StringBuilder(256);
11738                        } else {
11739                            r.append(' ');
11740                        }
11741                        if (isPackageUpdate) {
11742                            r.append("UPD:");
11743                        }
11744                        r.append(pg.info.name);
11745                    }
11746                } else {
11747                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11748                            + pg.info.packageName + " ignored: original from "
11749                            + cur.info.packageName);
11750                    if (chatty) {
11751                        if (r == null) {
11752                            r = new StringBuilder(256);
11753                        } else {
11754                            r.append(' ');
11755                        }
11756                        r.append("DUP:");
11757                        r.append(pg.info.name);
11758                    }
11759                }
11760            }
11761            if (r != null) {
11762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11763            }
11764
11765            N = pkg.permissions.size();
11766            r = null;
11767            for (i=0; i<N; i++) {
11768                PackageParser.Permission p = pkg.permissions.get(i);
11769
11770                // Dont allow ephemeral apps to define new permissions.
11771                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11772                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11773                            + p.info.packageName
11774                            + " ignored: instant apps cannot define new permissions.");
11775                    continue;
11776                }
11777
11778                // Assume by default that we did not install this permission into the system.
11779                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11780
11781                // Now that permission groups have a special meaning, we ignore permission
11782                // groups for legacy apps to prevent unexpected behavior. In particular,
11783                // permissions for one app being granted to someone just because they happen
11784                // to be in a group defined by another app (before this had no implications).
11785                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11786                    p.group = mPermissionGroups.get(p.info.group);
11787                    // Warn for a permission in an unknown group.
11788                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11789                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11790                                + p.info.packageName + " in an unknown group " + p.info.group);
11791                    }
11792                }
11793
11794                ArrayMap<String, BasePermission> permissionMap =
11795                        p.tree ? mSettings.mPermissionTrees
11796                                : mSettings.mPermissions;
11797                BasePermission bp = permissionMap.get(p.info.name);
11798
11799                // Allow system apps to redefine non-system permissions
11800                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11801                    final boolean currentOwnerIsSystem = (bp.perm != null
11802                            && isSystemApp(bp.perm.owner));
11803                    if (isSystemApp(p.owner)) {
11804                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11805                            // It's a built-in permission and no owner, take ownership now
11806                            bp.packageSetting = pkgSetting;
11807                            bp.perm = p;
11808                            bp.uid = pkg.applicationInfo.uid;
11809                            bp.sourcePackage = p.info.packageName;
11810                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11811                        } else if (!currentOwnerIsSystem) {
11812                            String msg = "New decl " + p.owner + " of permission  "
11813                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11814                            reportSettingsProblem(Log.WARN, msg);
11815                            bp = null;
11816                        }
11817                    }
11818                }
11819
11820                if (bp == null) {
11821                    bp = new BasePermission(p.info.name, p.info.packageName,
11822                            BasePermission.TYPE_NORMAL);
11823                    permissionMap.put(p.info.name, bp);
11824                }
11825
11826                if (bp.perm == null) {
11827                    if (bp.sourcePackage == null
11828                            || bp.sourcePackage.equals(p.info.packageName)) {
11829                        BasePermission tree = findPermissionTreeLP(p.info.name);
11830                        if (tree == null
11831                                || tree.sourcePackage.equals(p.info.packageName)) {
11832                            bp.packageSetting = pkgSetting;
11833                            bp.perm = p;
11834                            bp.uid = pkg.applicationInfo.uid;
11835                            bp.sourcePackage = p.info.packageName;
11836                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11837                            if (chatty) {
11838                                if (r == null) {
11839                                    r = new StringBuilder(256);
11840                                } else {
11841                                    r.append(' ');
11842                                }
11843                                r.append(p.info.name);
11844                            }
11845                        } else {
11846                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11847                                    + p.info.packageName + " ignored: base tree "
11848                                    + tree.name + " is from package "
11849                                    + tree.sourcePackage);
11850                        }
11851                    } else {
11852                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11853                                + p.info.packageName + " ignored: original from "
11854                                + bp.sourcePackage);
11855                    }
11856                } else if (chatty) {
11857                    if (r == null) {
11858                        r = new StringBuilder(256);
11859                    } else {
11860                        r.append(' ');
11861                    }
11862                    r.append("DUP:");
11863                    r.append(p.info.name);
11864                }
11865                if (bp.perm == p) {
11866                    bp.protectionLevel = p.info.protectionLevel;
11867                }
11868            }
11869
11870            if (r != null) {
11871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11872            }
11873
11874            N = pkg.instrumentation.size();
11875            r = null;
11876            for (i=0; i<N; i++) {
11877                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11878                a.info.packageName = pkg.applicationInfo.packageName;
11879                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11880                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11881                a.info.splitNames = pkg.splitNames;
11882                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11883                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11884                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11885                a.info.dataDir = pkg.applicationInfo.dataDir;
11886                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11887                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11888                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11889                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11890                mInstrumentation.put(a.getComponentName(), a);
11891                if (chatty) {
11892                    if (r == null) {
11893                        r = new StringBuilder(256);
11894                    } else {
11895                        r.append(' ');
11896                    }
11897                    r.append(a.info.name);
11898                }
11899            }
11900            if (r != null) {
11901                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11902            }
11903
11904            if (pkg.protectedBroadcasts != null) {
11905                N = pkg.protectedBroadcasts.size();
11906                synchronized (mProtectedBroadcasts) {
11907                    for (i = 0; i < N; i++) {
11908                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11909                    }
11910                }
11911            }
11912        }
11913
11914        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11915    }
11916
11917    /**
11918     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11919     * is derived purely on the basis of the contents of {@code scanFile} and
11920     * {@code cpuAbiOverride}.
11921     *
11922     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11923     */
11924    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11925                                 String cpuAbiOverride, boolean extractLibs,
11926                                 File appLib32InstallDir)
11927            throws PackageManagerException {
11928        // Give ourselves some initial paths; we'll come back for another
11929        // pass once we've determined ABI below.
11930        setNativeLibraryPaths(pkg, appLib32InstallDir);
11931
11932        // We would never need to extract libs for forward-locked and external packages,
11933        // since the container service will do it for us. We shouldn't attempt to
11934        // extract libs from system app when it was not updated.
11935        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11936                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11937            extractLibs = false;
11938        }
11939
11940        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11941        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11942
11943        NativeLibraryHelper.Handle handle = null;
11944        try {
11945            handle = NativeLibraryHelper.Handle.create(pkg);
11946            // TODO(multiArch): This can be null for apps that didn't go through the
11947            // usual installation process. We can calculate it again, like we
11948            // do during install time.
11949            //
11950            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11951            // unnecessary.
11952            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11953
11954            // Null out the abis so that they can be recalculated.
11955            pkg.applicationInfo.primaryCpuAbi = null;
11956            pkg.applicationInfo.secondaryCpuAbi = null;
11957            if (isMultiArch(pkg.applicationInfo)) {
11958                // Warn if we've set an abiOverride for multi-lib packages..
11959                // By definition, we need to copy both 32 and 64 bit libraries for
11960                // such packages.
11961                if (pkg.cpuAbiOverride != null
11962                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11963                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11964                }
11965
11966                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11967                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11968                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11969                    if (extractLibs) {
11970                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11971                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11972                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11973                                useIsaSpecificSubdirs);
11974                    } else {
11975                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11976                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11977                    }
11978                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11979                }
11980
11981                // Shared library native code should be in the APK zip aligned
11982                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11983                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11984                            "Shared library native lib extraction not supported");
11985                }
11986
11987                maybeThrowExceptionForMultiArchCopy(
11988                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11989
11990                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11991                    if (extractLibs) {
11992                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11993                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11994                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11995                                useIsaSpecificSubdirs);
11996                    } else {
11997                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11998                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11999                    }
12000                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12001                }
12002
12003                maybeThrowExceptionForMultiArchCopy(
12004                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12005
12006                if (abi64 >= 0) {
12007                    // Shared library native libs should be in the APK zip aligned
12008                    if (extractLibs && pkg.isLibrary()) {
12009                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12010                                "Shared library native lib extraction not supported");
12011                    }
12012                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12013                }
12014
12015                if (abi32 >= 0) {
12016                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12017                    if (abi64 >= 0) {
12018                        if (pkg.use32bitAbi) {
12019                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12020                            pkg.applicationInfo.primaryCpuAbi = abi;
12021                        } else {
12022                            pkg.applicationInfo.secondaryCpuAbi = abi;
12023                        }
12024                    } else {
12025                        pkg.applicationInfo.primaryCpuAbi = abi;
12026                    }
12027                }
12028            } else {
12029                String[] abiList = (cpuAbiOverride != null) ?
12030                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12031
12032                // Enable gross and lame hacks for apps that are built with old
12033                // SDK tools. We must scan their APKs for renderscript bitcode and
12034                // not launch them if it's present. Don't bother checking on devices
12035                // that don't have 64 bit support.
12036                boolean needsRenderScriptOverride = false;
12037                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12038                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12039                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12040                    needsRenderScriptOverride = true;
12041                }
12042
12043                final int copyRet;
12044                if (extractLibs) {
12045                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12046                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12047                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12048                } else {
12049                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12050                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12051                }
12052                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12053
12054                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12055                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12056                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12057                }
12058
12059                if (copyRet >= 0) {
12060                    // Shared libraries that have native libs must be multi-architecture
12061                    if (pkg.isLibrary()) {
12062                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12063                                "Shared library with native libs must be multiarch");
12064                    }
12065                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12066                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12067                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12068                } else if (needsRenderScriptOverride) {
12069                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12070                }
12071            }
12072        } catch (IOException ioe) {
12073            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12074        } finally {
12075            IoUtils.closeQuietly(handle);
12076        }
12077
12078        // Now that we've calculated the ABIs and determined if it's an internal app,
12079        // we will go ahead and populate the nativeLibraryPath.
12080        setNativeLibraryPaths(pkg, appLib32InstallDir);
12081    }
12082
12083    /**
12084     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12085     * i.e, so that all packages can be run inside a single process if required.
12086     *
12087     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12088     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12089     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12090     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12091     * updating a package that belongs to a shared user.
12092     *
12093     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12094     * adds unnecessary complexity.
12095     */
12096    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12097            PackageParser.Package scannedPackage) {
12098        String requiredInstructionSet = null;
12099        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12100            requiredInstructionSet = VMRuntime.getInstructionSet(
12101                     scannedPackage.applicationInfo.primaryCpuAbi);
12102        }
12103
12104        PackageSetting requirer = null;
12105        for (PackageSetting ps : packagesForUser) {
12106            // If packagesForUser contains scannedPackage, we skip it. This will happen
12107            // when scannedPackage is an update of an existing package. Without this check,
12108            // we will never be able to change the ABI of any package belonging to a shared
12109            // user, even if it's compatible with other packages.
12110            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12111                if (ps.primaryCpuAbiString == null) {
12112                    continue;
12113                }
12114
12115                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12116                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12117                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12118                    // this but there's not much we can do.
12119                    String errorMessage = "Instruction set mismatch, "
12120                            + ((requirer == null) ? "[caller]" : requirer)
12121                            + " requires " + requiredInstructionSet + " whereas " + ps
12122                            + " requires " + instructionSet;
12123                    Slog.w(TAG, errorMessage);
12124                }
12125
12126                if (requiredInstructionSet == null) {
12127                    requiredInstructionSet = instructionSet;
12128                    requirer = ps;
12129                }
12130            }
12131        }
12132
12133        if (requiredInstructionSet != null) {
12134            String adjustedAbi;
12135            if (requirer != null) {
12136                // requirer != null implies that either scannedPackage was null or that scannedPackage
12137                // did not require an ABI, in which case we have to adjust scannedPackage to match
12138                // the ABI of the set (which is the same as requirer's ABI)
12139                adjustedAbi = requirer.primaryCpuAbiString;
12140                if (scannedPackage != null) {
12141                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12142                }
12143            } else {
12144                // requirer == null implies that we're updating all ABIs in the set to
12145                // match scannedPackage.
12146                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12147            }
12148
12149            for (PackageSetting ps : packagesForUser) {
12150                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12151                    if (ps.primaryCpuAbiString != null) {
12152                        continue;
12153                    }
12154
12155                    ps.primaryCpuAbiString = adjustedAbi;
12156                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12157                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12158                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12159                        if (DEBUG_ABI_SELECTION) {
12160                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12161                                    + " (requirer="
12162                                    + (requirer != null ? requirer.pkg : "null")
12163                                    + ", scannedPackage="
12164                                    + (scannedPackage != null ? scannedPackage : "null")
12165                                    + ")");
12166                        }
12167                        try {
12168                            mInstaller.rmdex(ps.codePathString,
12169                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12170                        } catch (InstallerException ignored) {
12171                        }
12172                    }
12173                }
12174            }
12175        }
12176    }
12177
12178    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12179        synchronized (mPackages) {
12180            mResolverReplaced = true;
12181            // Set up information for custom user intent resolution activity.
12182            mResolveActivity.applicationInfo = pkg.applicationInfo;
12183            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12184            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12185            mResolveActivity.processName = pkg.applicationInfo.packageName;
12186            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12187            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12188                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12189            mResolveActivity.theme = 0;
12190            mResolveActivity.exported = true;
12191            mResolveActivity.enabled = true;
12192            mResolveInfo.activityInfo = mResolveActivity;
12193            mResolveInfo.priority = 0;
12194            mResolveInfo.preferredOrder = 0;
12195            mResolveInfo.match = 0;
12196            mResolveComponentName = mCustomResolverComponentName;
12197            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12198                    mResolveComponentName);
12199        }
12200    }
12201
12202    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12203        if (installerActivity == null) {
12204            if (DEBUG_EPHEMERAL) {
12205                Slog.d(TAG, "Clear ephemeral installer activity");
12206            }
12207            mInstantAppInstallerActivity = null;
12208            return;
12209        }
12210
12211        if (DEBUG_EPHEMERAL) {
12212            Slog.d(TAG, "Set ephemeral installer activity: "
12213                    + installerActivity.getComponentName());
12214        }
12215        // Set up information for ephemeral installer activity
12216        mInstantAppInstallerActivity = installerActivity;
12217        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12218                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12219        mInstantAppInstallerActivity.exported = true;
12220        mInstantAppInstallerActivity.enabled = true;
12221        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12222        mInstantAppInstallerInfo.priority = 0;
12223        mInstantAppInstallerInfo.preferredOrder = 1;
12224        mInstantAppInstallerInfo.isDefault = true;
12225        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12226                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12227    }
12228
12229    private static String calculateBundledApkRoot(final String codePathString) {
12230        final File codePath = new File(codePathString);
12231        final File codeRoot;
12232        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12233            codeRoot = Environment.getRootDirectory();
12234        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12235            codeRoot = Environment.getOemDirectory();
12236        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12237            codeRoot = Environment.getVendorDirectory();
12238        } else {
12239            // Unrecognized code path; take its top real segment as the apk root:
12240            // e.g. /something/app/blah.apk => /something
12241            try {
12242                File f = codePath.getCanonicalFile();
12243                File parent = f.getParentFile();    // non-null because codePath is a file
12244                File tmp;
12245                while ((tmp = parent.getParentFile()) != null) {
12246                    f = parent;
12247                    parent = tmp;
12248                }
12249                codeRoot = f;
12250                Slog.w(TAG, "Unrecognized code path "
12251                        + codePath + " - using " + codeRoot);
12252            } catch (IOException e) {
12253                // Can't canonicalize the code path -- shenanigans?
12254                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12255                return Environment.getRootDirectory().getPath();
12256            }
12257        }
12258        return codeRoot.getPath();
12259    }
12260
12261    /**
12262     * Derive and set the location of native libraries for the given package,
12263     * which varies depending on where and how the package was installed.
12264     */
12265    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12266        final ApplicationInfo info = pkg.applicationInfo;
12267        final String codePath = pkg.codePath;
12268        final File codeFile = new File(codePath);
12269        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12270        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12271
12272        info.nativeLibraryRootDir = null;
12273        info.nativeLibraryRootRequiresIsa = false;
12274        info.nativeLibraryDir = null;
12275        info.secondaryNativeLibraryDir = null;
12276
12277        if (isApkFile(codeFile)) {
12278            // Monolithic install
12279            if (bundledApp) {
12280                // If "/system/lib64/apkname" exists, assume that is the per-package
12281                // native library directory to use; otherwise use "/system/lib/apkname".
12282                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12283                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12284                        getPrimaryInstructionSet(info));
12285
12286                // This is a bundled system app so choose the path based on the ABI.
12287                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12288                // is just the default path.
12289                final String apkName = deriveCodePathName(codePath);
12290                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12291                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12292                        apkName).getAbsolutePath();
12293
12294                if (info.secondaryCpuAbi != null) {
12295                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12296                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12297                            secondaryLibDir, apkName).getAbsolutePath();
12298                }
12299            } else if (asecApp) {
12300                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12301                        .getAbsolutePath();
12302            } else {
12303                final String apkName = deriveCodePathName(codePath);
12304                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12305                        .getAbsolutePath();
12306            }
12307
12308            info.nativeLibraryRootRequiresIsa = false;
12309            info.nativeLibraryDir = info.nativeLibraryRootDir;
12310        } else {
12311            // Cluster install
12312            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12313            info.nativeLibraryRootRequiresIsa = true;
12314
12315            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12316                    getPrimaryInstructionSet(info)).getAbsolutePath();
12317
12318            if (info.secondaryCpuAbi != null) {
12319                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12320                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12321            }
12322        }
12323    }
12324
12325    /**
12326     * Calculate the abis and roots for a bundled app. These can uniquely
12327     * be determined from the contents of the system partition, i.e whether
12328     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12329     * of this information, and instead assume that the system was built
12330     * sensibly.
12331     */
12332    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12333                                           PackageSetting pkgSetting) {
12334        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12335
12336        // If "/system/lib64/apkname" exists, assume that is the per-package
12337        // native library directory to use; otherwise use "/system/lib/apkname".
12338        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12339        setBundledAppAbi(pkg, apkRoot, apkName);
12340        // pkgSetting might be null during rescan following uninstall of updates
12341        // to a bundled app, so accommodate that possibility.  The settings in
12342        // that case will be established later from the parsed package.
12343        //
12344        // If the settings aren't null, sync them up with what we've just derived.
12345        // note that apkRoot isn't stored in the package settings.
12346        if (pkgSetting != null) {
12347            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12348            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12349        }
12350    }
12351
12352    /**
12353     * Deduces the ABI of a bundled app and sets the relevant fields on the
12354     * parsed pkg object.
12355     *
12356     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12357     *        under which system libraries are installed.
12358     * @param apkName the name of the installed package.
12359     */
12360    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12361        final File codeFile = new File(pkg.codePath);
12362
12363        final boolean has64BitLibs;
12364        final boolean has32BitLibs;
12365        if (isApkFile(codeFile)) {
12366            // Monolithic install
12367            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12368            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12369        } else {
12370            // Cluster install
12371            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12372            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12373                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12374                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12375                has64BitLibs = (new File(rootDir, isa)).exists();
12376            } else {
12377                has64BitLibs = false;
12378            }
12379            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12380                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12381                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12382                has32BitLibs = (new File(rootDir, isa)).exists();
12383            } else {
12384                has32BitLibs = false;
12385            }
12386        }
12387
12388        if (has64BitLibs && !has32BitLibs) {
12389            // The package has 64 bit libs, but not 32 bit libs. Its primary
12390            // ABI should be 64 bit. We can safely assume here that the bundled
12391            // native libraries correspond to the most preferred ABI in the list.
12392
12393            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12394            pkg.applicationInfo.secondaryCpuAbi = null;
12395        } else if (has32BitLibs && !has64BitLibs) {
12396            // The package has 32 bit libs but not 64 bit libs. Its primary
12397            // ABI should be 32 bit.
12398
12399            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12400            pkg.applicationInfo.secondaryCpuAbi = null;
12401        } else if (has32BitLibs && has64BitLibs) {
12402            // The application has both 64 and 32 bit bundled libraries. We check
12403            // here that the app declares multiArch support, and warn if it doesn't.
12404            //
12405            // We will be lenient here and record both ABIs. The primary will be the
12406            // ABI that's higher on the list, i.e, a device that's configured to prefer
12407            // 64 bit apps will see a 64 bit primary ABI,
12408
12409            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12410                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12411            }
12412
12413            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12414                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12415                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12416            } else {
12417                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12418                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12419            }
12420        } else {
12421            pkg.applicationInfo.primaryCpuAbi = null;
12422            pkg.applicationInfo.secondaryCpuAbi = null;
12423        }
12424    }
12425
12426    private void killApplication(String pkgName, int appId, String reason) {
12427        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12428    }
12429
12430    private void killApplication(String pkgName, int appId, int userId, String reason) {
12431        // Request the ActivityManager to kill the process(only for existing packages)
12432        // so that we do not end up in a confused state while the user is still using the older
12433        // version of the application while the new one gets installed.
12434        final long token = Binder.clearCallingIdentity();
12435        try {
12436            IActivityManager am = ActivityManager.getService();
12437            if (am != null) {
12438                try {
12439                    am.killApplication(pkgName, appId, userId, reason);
12440                } catch (RemoteException e) {
12441                }
12442            }
12443        } finally {
12444            Binder.restoreCallingIdentity(token);
12445        }
12446    }
12447
12448    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12449        // Remove the parent package setting
12450        PackageSetting ps = (PackageSetting) pkg.mExtras;
12451        if (ps != null) {
12452            removePackageLI(ps, chatty);
12453        }
12454        // Remove the child package setting
12455        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12456        for (int i = 0; i < childCount; i++) {
12457            PackageParser.Package childPkg = pkg.childPackages.get(i);
12458            ps = (PackageSetting) childPkg.mExtras;
12459            if (ps != null) {
12460                removePackageLI(ps, chatty);
12461            }
12462        }
12463    }
12464
12465    void removePackageLI(PackageSetting ps, boolean chatty) {
12466        if (DEBUG_INSTALL) {
12467            if (chatty)
12468                Log.d(TAG, "Removing package " + ps.name);
12469        }
12470
12471        // writer
12472        synchronized (mPackages) {
12473            mPackages.remove(ps.name);
12474            final PackageParser.Package pkg = ps.pkg;
12475            if (pkg != null) {
12476                cleanPackageDataStructuresLILPw(pkg, chatty);
12477            }
12478        }
12479    }
12480
12481    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12482        if (DEBUG_INSTALL) {
12483            if (chatty)
12484                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12485        }
12486
12487        // writer
12488        synchronized (mPackages) {
12489            // Remove the parent package
12490            mPackages.remove(pkg.applicationInfo.packageName);
12491            cleanPackageDataStructuresLILPw(pkg, chatty);
12492
12493            // Remove the child packages
12494            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12495            for (int i = 0; i < childCount; i++) {
12496                PackageParser.Package childPkg = pkg.childPackages.get(i);
12497                mPackages.remove(childPkg.applicationInfo.packageName);
12498                cleanPackageDataStructuresLILPw(childPkg, chatty);
12499            }
12500        }
12501    }
12502
12503    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12504        int N = pkg.providers.size();
12505        StringBuilder r = null;
12506        int i;
12507        for (i=0; i<N; i++) {
12508            PackageParser.Provider p = pkg.providers.get(i);
12509            mProviders.removeProvider(p);
12510            if (p.info.authority == null) {
12511
12512                /* There was another ContentProvider with this authority when
12513                 * this app was installed so this authority is null,
12514                 * Ignore it as we don't have to unregister the provider.
12515                 */
12516                continue;
12517            }
12518            String names[] = p.info.authority.split(";");
12519            for (int j = 0; j < names.length; j++) {
12520                if (mProvidersByAuthority.get(names[j]) == p) {
12521                    mProvidersByAuthority.remove(names[j]);
12522                    if (DEBUG_REMOVE) {
12523                        if (chatty)
12524                            Log.d(TAG, "Unregistered content provider: " + names[j]
12525                                    + ", className = " + p.info.name + ", isSyncable = "
12526                                    + p.info.isSyncable);
12527                    }
12528                }
12529            }
12530            if (DEBUG_REMOVE && chatty) {
12531                if (r == null) {
12532                    r = new StringBuilder(256);
12533                } else {
12534                    r.append(' ');
12535                }
12536                r.append(p.info.name);
12537            }
12538        }
12539        if (r != null) {
12540            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12541        }
12542
12543        N = pkg.services.size();
12544        r = null;
12545        for (i=0; i<N; i++) {
12546            PackageParser.Service s = pkg.services.get(i);
12547            mServices.removeService(s);
12548            if (chatty) {
12549                if (r == null) {
12550                    r = new StringBuilder(256);
12551                } else {
12552                    r.append(' ');
12553                }
12554                r.append(s.info.name);
12555            }
12556        }
12557        if (r != null) {
12558            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12559        }
12560
12561        N = pkg.receivers.size();
12562        r = null;
12563        for (i=0; i<N; i++) {
12564            PackageParser.Activity a = pkg.receivers.get(i);
12565            mReceivers.removeActivity(a, "receiver");
12566            if (DEBUG_REMOVE && chatty) {
12567                if (r == null) {
12568                    r = new StringBuilder(256);
12569                } else {
12570                    r.append(' ');
12571                }
12572                r.append(a.info.name);
12573            }
12574        }
12575        if (r != null) {
12576            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12577        }
12578
12579        N = pkg.activities.size();
12580        r = null;
12581        for (i=0; i<N; i++) {
12582            PackageParser.Activity a = pkg.activities.get(i);
12583            mActivities.removeActivity(a, "activity");
12584            if (DEBUG_REMOVE && chatty) {
12585                if (r == null) {
12586                    r = new StringBuilder(256);
12587                } else {
12588                    r.append(' ');
12589                }
12590                r.append(a.info.name);
12591            }
12592        }
12593        if (r != null) {
12594            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12595        }
12596
12597        N = pkg.permissions.size();
12598        r = null;
12599        for (i=0; i<N; i++) {
12600            PackageParser.Permission p = pkg.permissions.get(i);
12601            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12602            if (bp == null) {
12603                bp = mSettings.mPermissionTrees.get(p.info.name);
12604            }
12605            if (bp != null && bp.perm == p) {
12606                bp.perm = null;
12607                if (DEBUG_REMOVE && chatty) {
12608                    if (r == null) {
12609                        r = new StringBuilder(256);
12610                    } else {
12611                        r.append(' ');
12612                    }
12613                    r.append(p.info.name);
12614                }
12615            }
12616            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12617                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12618                if (appOpPkgs != null) {
12619                    appOpPkgs.remove(pkg.packageName);
12620                }
12621            }
12622        }
12623        if (r != null) {
12624            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12625        }
12626
12627        N = pkg.requestedPermissions.size();
12628        r = null;
12629        for (i=0; i<N; i++) {
12630            String perm = pkg.requestedPermissions.get(i);
12631            BasePermission bp = mSettings.mPermissions.get(perm);
12632            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12633                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12634                if (appOpPkgs != null) {
12635                    appOpPkgs.remove(pkg.packageName);
12636                    if (appOpPkgs.isEmpty()) {
12637                        mAppOpPermissionPackages.remove(perm);
12638                    }
12639                }
12640            }
12641        }
12642        if (r != null) {
12643            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12644        }
12645
12646        N = pkg.instrumentation.size();
12647        r = null;
12648        for (i=0; i<N; i++) {
12649            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12650            mInstrumentation.remove(a.getComponentName());
12651            if (DEBUG_REMOVE && chatty) {
12652                if (r == null) {
12653                    r = new StringBuilder(256);
12654                } else {
12655                    r.append(' ');
12656                }
12657                r.append(a.info.name);
12658            }
12659        }
12660        if (r != null) {
12661            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12662        }
12663
12664        r = null;
12665        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12666            // Only system apps can hold shared libraries.
12667            if (pkg.libraryNames != null) {
12668                for (i = 0; i < pkg.libraryNames.size(); i++) {
12669                    String name = pkg.libraryNames.get(i);
12670                    if (removeSharedLibraryLPw(name, 0)) {
12671                        if (DEBUG_REMOVE && chatty) {
12672                            if (r == null) {
12673                                r = new StringBuilder(256);
12674                            } else {
12675                                r.append(' ');
12676                            }
12677                            r.append(name);
12678                        }
12679                    }
12680                }
12681            }
12682        }
12683
12684        r = null;
12685
12686        // Any package can hold static shared libraries.
12687        if (pkg.staticSharedLibName != null) {
12688            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12689                if (DEBUG_REMOVE && chatty) {
12690                    if (r == null) {
12691                        r = new StringBuilder(256);
12692                    } else {
12693                        r.append(' ');
12694                    }
12695                    r.append(pkg.staticSharedLibName);
12696                }
12697            }
12698        }
12699
12700        if (r != null) {
12701            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12702        }
12703    }
12704
12705    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12706        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12707            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12708                return true;
12709            }
12710        }
12711        return false;
12712    }
12713
12714    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12715    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12716    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12717
12718    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12719        // Update the parent permissions
12720        updatePermissionsLPw(pkg.packageName, pkg, flags);
12721        // Update the child permissions
12722        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12723        for (int i = 0; i < childCount; i++) {
12724            PackageParser.Package childPkg = pkg.childPackages.get(i);
12725            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12726        }
12727    }
12728
12729    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12730            int flags) {
12731        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12732        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12733    }
12734
12735    private void updatePermissionsLPw(String changingPkg,
12736            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12737        // Make sure there are no dangling permission trees.
12738        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12739        while (it.hasNext()) {
12740            final BasePermission bp = it.next();
12741            if (bp.packageSetting == null) {
12742                // We may not yet have parsed the package, so just see if
12743                // we still know about its settings.
12744                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12745            }
12746            if (bp.packageSetting == null) {
12747                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12748                        + " from package " + bp.sourcePackage);
12749                it.remove();
12750            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12751                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12752                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12753                            + " from package " + bp.sourcePackage);
12754                    flags |= UPDATE_PERMISSIONS_ALL;
12755                    it.remove();
12756                }
12757            }
12758        }
12759
12760        // Make sure all dynamic permissions have been assigned to a package,
12761        // and make sure there are no dangling permissions.
12762        it = mSettings.mPermissions.values().iterator();
12763        while (it.hasNext()) {
12764            final BasePermission bp = it.next();
12765            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12766                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12767                        + bp.name + " pkg=" + bp.sourcePackage
12768                        + " info=" + bp.pendingInfo);
12769                if (bp.packageSetting == null && bp.pendingInfo != null) {
12770                    final BasePermission tree = findPermissionTreeLP(bp.name);
12771                    if (tree != null && tree.perm != null) {
12772                        bp.packageSetting = tree.packageSetting;
12773                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12774                                new PermissionInfo(bp.pendingInfo));
12775                        bp.perm.info.packageName = tree.perm.info.packageName;
12776                        bp.perm.info.name = bp.name;
12777                        bp.uid = tree.uid;
12778                    }
12779                }
12780            }
12781            if (bp.packageSetting == null) {
12782                // We may not yet have parsed the package, so just see if
12783                // we still know about its settings.
12784                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12785            }
12786            if (bp.packageSetting == null) {
12787                Slog.w(TAG, "Removing dangling permission: " + bp.name
12788                        + " from package " + bp.sourcePackage);
12789                it.remove();
12790            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12791                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12792                    Slog.i(TAG, "Removing old permission: " + bp.name
12793                            + " from package " + bp.sourcePackage);
12794                    flags |= UPDATE_PERMISSIONS_ALL;
12795                    it.remove();
12796                }
12797            }
12798        }
12799
12800        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12801        // Now update the permissions for all packages, in particular
12802        // replace the granted permissions of the system packages.
12803        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12804            for (PackageParser.Package pkg : mPackages.values()) {
12805                if (pkg != pkgInfo) {
12806                    // Only replace for packages on requested volume
12807                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12808                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12809                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12810                    grantPermissionsLPw(pkg, replace, changingPkg);
12811                }
12812            }
12813        }
12814
12815        if (pkgInfo != null) {
12816            // Only replace for packages on requested volume
12817            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12818            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12819                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12820            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12821        }
12822        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12823    }
12824
12825    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12826            String packageOfInterest) {
12827        // IMPORTANT: There are two types of permissions: install and runtime.
12828        // Install time permissions are granted when the app is installed to
12829        // all device users and users added in the future. Runtime permissions
12830        // are granted at runtime explicitly to specific users. Normal and signature
12831        // protected permissions are install time permissions. Dangerous permissions
12832        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12833        // otherwise they are runtime permissions. This function does not manage
12834        // runtime permissions except for the case an app targeting Lollipop MR1
12835        // being upgraded to target a newer SDK, in which case dangerous permissions
12836        // are transformed from install time to runtime ones.
12837
12838        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12839        if (ps == null) {
12840            return;
12841        }
12842
12843        PermissionsState permissionsState = ps.getPermissionsState();
12844        PermissionsState origPermissions = permissionsState;
12845
12846        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12847
12848        boolean runtimePermissionsRevoked = false;
12849        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12850
12851        boolean changedInstallPermission = false;
12852
12853        if (replace) {
12854            ps.installPermissionsFixed = false;
12855            if (!ps.isSharedUser()) {
12856                origPermissions = new PermissionsState(permissionsState);
12857                permissionsState.reset();
12858            } else {
12859                // We need to know only about runtime permission changes since the
12860                // calling code always writes the install permissions state but
12861                // the runtime ones are written only if changed. The only cases of
12862                // changed runtime permissions here are promotion of an install to
12863                // runtime and revocation of a runtime from a shared user.
12864                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12865                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12866                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12867                    runtimePermissionsRevoked = true;
12868                }
12869            }
12870        }
12871
12872        permissionsState.setGlobalGids(mGlobalGids);
12873
12874        final int N = pkg.requestedPermissions.size();
12875        for (int i=0; i<N; i++) {
12876            final String name = pkg.requestedPermissions.get(i);
12877            final BasePermission bp = mSettings.mPermissions.get(name);
12878            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12879                    >= Build.VERSION_CODES.M;
12880
12881            if (DEBUG_INSTALL) {
12882                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12883            }
12884
12885            if (bp == null || bp.packageSetting == null) {
12886                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12887                    if (DEBUG_PERMISSIONS) {
12888                        Slog.i(TAG, "Unknown permission " + name
12889                                + " in package " + pkg.packageName);
12890                    }
12891                }
12892                continue;
12893            }
12894
12895
12896            // Limit ephemeral apps to ephemeral allowed permissions.
12897            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12898                if (DEBUG_PERMISSIONS) {
12899                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12900                            + pkg.packageName);
12901                }
12902                continue;
12903            }
12904
12905            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12906                if (DEBUG_PERMISSIONS) {
12907                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12908                            + pkg.packageName);
12909                }
12910                continue;
12911            }
12912
12913            final String perm = bp.name;
12914            boolean allowedSig = false;
12915            int grant = GRANT_DENIED;
12916
12917            // Keep track of app op permissions.
12918            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12919                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12920                if (pkgs == null) {
12921                    pkgs = new ArraySet<>();
12922                    mAppOpPermissionPackages.put(bp.name, pkgs);
12923                }
12924                pkgs.add(pkg.packageName);
12925            }
12926
12927            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12928            switch (level) {
12929                case PermissionInfo.PROTECTION_NORMAL: {
12930                    // For all apps normal permissions are install time ones.
12931                    grant = GRANT_INSTALL;
12932                } break;
12933
12934                case PermissionInfo.PROTECTION_DANGEROUS: {
12935                    // If a permission review is required for legacy apps we represent
12936                    // their permissions as always granted runtime ones since we need
12937                    // to keep the review required permission flag per user while an
12938                    // install permission's state is shared across all users.
12939                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12940                        // For legacy apps dangerous permissions are install time ones.
12941                        grant = GRANT_INSTALL;
12942                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12943                        // For legacy apps that became modern, install becomes runtime.
12944                        grant = GRANT_UPGRADE;
12945                    } else if (mPromoteSystemApps
12946                            && isSystemApp(ps)
12947                            && mExistingSystemPackages.contains(ps.name)) {
12948                        // For legacy system apps, install becomes runtime.
12949                        // We cannot check hasInstallPermission() for system apps since those
12950                        // permissions were granted implicitly and not persisted pre-M.
12951                        grant = GRANT_UPGRADE;
12952                    } else {
12953                        // For modern apps keep runtime permissions unchanged.
12954                        grant = GRANT_RUNTIME;
12955                    }
12956                } break;
12957
12958                case PermissionInfo.PROTECTION_SIGNATURE: {
12959                    // For all apps signature permissions are install time ones.
12960                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12961                    if (allowedSig) {
12962                        grant = GRANT_INSTALL;
12963                    }
12964                } break;
12965            }
12966
12967            if (DEBUG_PERMISSIONS) {
12968                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12969            }
12970
12971            if (grant != GRANT_DENIED) {
12972                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12973                    // If this is an existing, non-system package, then
12974                    // we can't add any new permissions to it.
12975                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12976                        // Except...  if this is a permission that was added
12977                        // to the platform (note: need to only do this when
12978                        // updating the platform).
12979                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12980                            grant = GRANT_DENIED;
12981                        }
12982                    }
12983                }
12984
12985                switch (grant) {
12986                    case GRANT_INSTALL: {
12987                        // Revoke this as runtime permission to handle the case of
12988                        // a runtime permission being downgraded to an install one.
12989                        // Also in permission review mode we keep dangerous permissions
12990                        // for legacy apps
12991                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12992                            if (origPermissions.getRuntimePermissionState(
12993                                    bp.name, userId) != null) {
12994                                // Revoke the runtime permission and clear the flags.
12995                                origPermissions.revokeRuntimePermission(bp, userId);
12996                                origPermissions.updatePermissionFlags(bp, userId,
12997                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12998                                // If we revoked a permission permission, we have to write.
12999                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13000                                        changedRuntimePermissionUserIds, userId);
13001                            }
13002                        }
13003                        // Grant an install permission.
13004                        if (permissionsState.grantInstallPermission(bp) !=
13005                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13006                            changedInstallPermission = true;
13007                        }
13008                    } break;
13009
13010                    case GRANT_RUNTIME: {
13011                        // Grant previously granted runtime permissions.
13012                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13013                            PermissionState permissionState = origPermissions
13014                                    .getRuntimePermissionState(bp.name, userId);
13015                            int flags = permissionState != null
13016                                    ? permissionState.getFlags() : 0;
13017                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13018                                // Don't propagate the permission in a permission review mode if
13019                                // the former was revoked, i.e. marked to not propagate on upgrade.
13020                                // Note that in a permission review mode install permissions are
13021                                // represented as constantly granted runtime ones since we need to
13022                                // keep a per user state associated with the permission. Also the
13023                                // revoke on upgrade flag is no longer applicable and is reset.
13024                                final boolean revokeOnUpgrade = (flags & PackageManager
13025                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13026                                if (revokeOnUpgrade) {
13027                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13028                                    // Since we changed the flags, we have to write.
13029                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13030                                            changedRuntimePermissionUserIds, userId);
13031                                }
13032                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13033                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13034                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13035                                        // If we cannot put the permission as it was,
13036                                        // we have to write.
13037                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13038                                                changedRuntimePermissionUserIds, userId);
13039                                    }
13040                                }
13041
13042                                // If the app supports runtime permissions no need for a review.
13043                                if (mPermissionReviewRequired
13044                                        && appSupportsRuntimePermissions
13045                                        && (flags & PackageManager
13046                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13047                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13048                                    // Since we changed the flags, we have to write.
13049                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13050                                            changedRuntimePermissionUserIds, userId);
13051                                }
13052                            } else if (mPermissionReviewRequired
13053                                    && !appSupportsRuntimePermissions) {
13054                                // For legacy apps that need a permission review, every new
13055                                // runtime permission is granted but it is pending a review.
13056                                // We also need to review only platform defined runtime
13057                                // permissions as these are the only ones the platform knows
13058                                // how to disable the API to simulate revocation as legacy
13059                                // apps don't expect to run with revoked permissions.
13060                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13061                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13062                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13063                                        // We changed the flags, hence have to write.
13064                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13065                                                changedRuntimePermissionUserIds, userId);
13066                                    }
13067                                }
13068                                if (permissionsState.grantRuntimePermission(bp, userId)
13069                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13070                                    // We changed the permission, hence have to write.
13071                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13072                                            changedRuntimePermissionUserIds, userId);
13073                                }
13074                            }
13075                            // Propagate the permission flags.
13076                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13077                        }
13078                    } break;
13079
13080                    case GRANT_UPGRADE: {
13081                        // Grant runtime permissions for a previously held install permission.
13082                        PermissionState permissionState = origPermissions
13083                                .getInstallPermissionState(bp.name);
13084                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13085
13086                        if (origPermissions.revokeInstallPermission(bp)
13087                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13088                            // We will be transferring the permission flags, so clear them.
13089                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13090                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13091                            changedInstallPermission = true;
13092                        }
13093
13094                        // If the permission is not to be promoted to runtime we ignore it and
13095                        // also its other flags as they are not applicable to install permissions.
13096                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13097                            for (int userId : currentUserIds) {
13098                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13099                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13100                                    // Transfer the permission flags.
13101                                    permissionsState.updatePermissionFlags(bp, userId,
13102                                            flags, flags);
13103                                    // If we granted the permission, we have to write.
13104                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13105                                            changedRuntimePermissionUserIds, userId);
13106                                }
13107                            }
13108                        }
13109                    } break;
13110
13111                    default: {
13112                        if (packageOfInterest == null
13113                                || packageOfInterest.equals(pkg.packageName)) {
13114                            if (DEBUG_PERMISSIONS) {
13115                                Slog.i(TAG, "Not granting permission " + perm
13116                                        + " to package " + pkg.packageName
13117                                        + " because it was previously installed without");
13118                            }
13119                        }
13120                    } break;
13121                }
13122            } else {
13123                if (permissionsState.revokeInstallPermission(bp) !=
13124                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13125                    // Also drop the permission flags.
13126                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13127                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13128                    changedInstallPermission = true;
13129                    Slog.i(TAG, "Un-granting permission " + perm
13130                            + " from package " + pkg.packageName
13131                            + " (protectionLevel=" + bp.protectionLevel
13132                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13133                            + ")");
13134                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13135                    // Don't print warning for app op permissions, since it is fine for them
13136                    // not to be granted, there is a UI for the user to decide.
13137                    if (DEBUG_PERMISSIONS
13138                            && (packageOfInterest == null
13139                                    || packageOfInterest.equals(pkg.packageName))) {
13140                        Slog.i(TAG, "Not granting permission " + perm
13141                                + " to package " + pkg.packageName
13142                                + " (protectionLevel=" + bp.protectionLevel
13143                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13144                                + ")");
13145                    }
13146                }
13147            }
13148        }
13149
13150        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13151                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13152            // This is the first that we have heard about this package, so the
13153            // permissions we have now selected are fixed until explicitly
13154            // changed.
13155            ps.installPermissionsFixed = true;
13156        }
13157
13158        // Persist the runtime permissions state for users with changes. If permissions
13159        // were revoked because no app in the shared user declares them we have to
13160        // write synchronously to avoid losing runtime permissions state.
13161        for (int userId : changedRuntimePermissionUserIds) {
13162            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13163        }
13164    }
13165
13166    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13167        boolean allowed = false;
13168        final int NP = PackageParser.NEW_PERMISSIONS.length;
13169        for (int ip=0; ip<NP; ip++) {
13170            final PackageParser.NewPermissionInfo npi
13171                    = PackageParser.NEW_PERMISSIONS[ip];
13172            if (npi.name.equals(perm)
13173                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13174                allowed = true;
13175                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13176                        + pkg.packageName);
13177                break;
13178            }
13179        }
13180        return allowed;
13181    }
13182
13183    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13184            BasePermission bp, PermissionsState origPermissions) {
13185        boolean privilegedPermission = (bp.protectionLevel
13186                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13187        boolean privappPermissionsDisable =
13188                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13189        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13190        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13191        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13192                && !platformPackage && platformPermission) {
13193            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13194                    .getPrivAppPermissions(pkg.packageName);
13195            final boolean whitelisted =
13196                    allowedPermissions != null && allowedPermissions.contains(perm);
13197            if (!whitelisted) {
13198                Slog.w(TAG, "Privileged permission " + perm + " for package "
13199                        + pkg.packageName + " - not in privapp-permissions whitelist");
13200                // Only report violations for apps on system image
13201                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13202                    // it's only a reportable violation if the permission isn't explicitly denied
13203                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13204                            .getPrivAppDenyPermissions(pkg.packageName);
13205                    final boolean permissionViolation =
13206                            deniedPermissions == null || !deniedPermissions.contains(perm);
13207                    if (permissionViolation) {
13208                        if (mPrivappPermissionsViolations == null) {
13209                            mPrivappPermissionsViolations = new ArraySet<>();
13210                        }
13211                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13212                    } else {
13213                        return false;
13214                    }
13215                }
13216                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13217                    return false;
13218                }
13219            }
13220        }
13221        boolean allowed = (compareSignatures(
13222                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13223                        == PackageManager.SIGNATURE_MATCH)
13224                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13225                        == PackageManager.SIGNATURE_MATCH);
13226        if (!allowed && privilegedPermission) {
13227            if (isSystemApp(pkg)) {
13228                // For updated system applications, a system permission
13229                // is granted only if it had been defined by the original application.
13230                if (pkg.isUpdatedSystemApp()) {
13231                    final PackageSetting sysPs = mSettings
13232                            .getDisabledSystemPkgLPr(pkg.packageName);
13233                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13234                        // If the original was granted this permission, we take
13235                        // that grant decision as read and propagate it to the
13236                        // update.
13237                        if (sysPs.isPrivileged()) {
13238                            allowed = true;
13239                        }
13240                    } else {
13241                        // The system apk may have been updated with an older
13242                        // version of the one on the data partition, but which
13243                        // granted a new system permission that it didn't have
13244                        // before.  In this case we do want to allow the app to
13245                        // now get the new permission if the ancestral apk is
13246                        // privileged to get it.
13247                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13248                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13249                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13250                                    allowed = true;
13251                                    break;
13252                                }
13253                            }
13254                        }
13255                        // Also if a privileged parent package on the system image or any of
13256                        // its children requested a privileged permission, the updated child
13257                        // packages can also get the permission.
13258                        if (pkg.parentPackage != null) {
13259                            final PackageSetting disabledSysParentPs = mSettings
13260                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13261                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13262                                    && disabledSysParentPs.isPrivileged()) {
13263                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13264                                    allowed = true;
13265                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13266                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13267                                    for (int i = 0; i < count; i++) {
13268                                        PackageParser.Package disabledSysChildPkg =
13269                                                disabledSysParentPs.pkg.childPackages.get(i);
13270                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13271                                                perm)) {
13272                                            allowed = true;
13273                                            break;
13274                                        }
13275                                    }
13276                                }
13277                            }
13278                        }
13279                    }
13280                } else {
13281                    allowed = isPrivilegedApp(pkg);
13282                }
13283            }
13284        }
13285        if (!allowed) {
13286            if (!allowed && (bp.protectionLevel
13287                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13288                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13289                // If this was a previously normal/dangerous permission that got moved
13290                // to a system permission as part of the runtime permission redesign, then
13291                // we still want to blindly grant it to old apps.
13292                allowed = true;
13293            }
13294            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13295                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13296                // If this permission is to be granted to the system installer and
13297                // this app is an installer, then it gets the permission.
13298                allowed = true;
13299            }
13300            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13301                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13302                // If this permission is to be granted to the system verifier and
13303                // this app is a verifier, then it gets the permission.
13304                allowed = true;
13305            }
13306            if (!allowed && (bp.protectionLevel
13307                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13308                    && isSystemApp(pkg)) {
13309                // Any pre-installed system app is allowed to get this permission.
13310                allowed = true;
13311            }
13312            if (!allowed && (bp.protectionLevel
13313                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13314                // For development permissions, a development permission
13315                // is granted only if it was already granted.
13316                allowed = origPermissions.hasInstallPermission(perm);
13317            }
13318            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13319                    && pkg.packageName.equals(mSetupWizardPackage)) {
13320                // If this permission is to be granted to the system setup wizard and
13321                // this app is a setup wizard, then it gets the permission.
13322                allowed = true;
13323            }
13324        }
13325        return allowed;
13326    }
13327
13328    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13329        final int permCount = pkg.requestedPermissions.size();
13330        for (int j = 0; j < permCount; j++) {
13331            String requestedPermission = pkg.requestedPermissions.get(j);
13332            if (permission.equals(requestedPermission)) {
13333                return true;
13334            }
13335        }
13336        return false;
13337    }
13338
13339    final class ActivityIntentResolver
13340            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13341        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13342                boolean defaultOnly, int userId) {
13343            if (!sUserManager.exists(userId)) return null;
13344            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13345            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13346        }
13347
13348        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13349                int userId) {
13350            if (!sUserManager.exists(userId)) return null;
13351            mFlags = flags;
13352            return super.queryIntent(intent, resolvedType,
13353                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13354                    userId);
13355        }
13356
13357        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13358                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13359            if (!sUserManager.exists(userId)) return null;
13360            if (packageActivities == null) {
13361                return null;
13362            }
13363            mFlags = flags;
13364            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13365            final int N = packageActivities.size();
13366            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13367                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13368
13369            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13370            for (int i = 0; i < N; ++i) {
13371                intentFilters = packageActivities.get(i).intents;
13372                if (intentFilters != null && intentFilters.size() > 0) {
13373                    PackageParser.ActivityIntentInfo[] array =
13374                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13375                    intentFilters.toArray(array);
13376                    listCut.add(array);
13377                }
13378            }
13379            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13380        }
13381
13382        /**
13383         * Finds a privileged activity that matches the specified activity names.
13384         */
13385        private PackageParser.Activity findMatchingActivity(
13386                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13387            for (PackageParser.Activity sysActivity : activityList) {
13388                if (sysActivity.info.name.equals(activityInfo.name)) {
13389                    return sysActivity;
13390                }
13391                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13392                    return sysActivity;
13393                }
13394                if (sysActivity.info.targetActivity != null) {
13395                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13396                        return sysActivity;
13397                    }
13398                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13399                        return sysActivity;
13400                    }
13401                }
13402            }
13403            return null;
13404        }
13405
13406        public class IterGenerator<E> {
13407            public Iterator<E> generate(ActivityIntentInfo info) {
13408                return null;
13409            }
13410        }
13411
13412        public class ActionIterGenerator extends IterGenerator<String> {
13413            @Override
13414            public Iterator<String> generate(ActivityIntentInfo info) {
13415                return info.actionsIterator();
13416            }
13417        }
13418
13419        public class CategoriesIterGenerator extends IterGenerator<String> {
13420            @Override
13421            public Iterator<String> generate(ActivityIntentInfo info) {
13422                return info.categoriesIterator();
13423            }
13424        }
13425
13426        public class SchemesIterGenerator extends IterGenerator<String> {
13427            @Override
13428            public Iterator<String> generate(ActivityIntentInfo info) {
13429                return info.schemesIterator();
13430            }
13431        }
13432
13433        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13434            @Override
13435            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13436                return info.authoritiesIterator();
13437            }
13438        }
13439
13440        /**
13441         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13442         * MODIFIED. Do not pass in a list that should not be changed.
13443         */
13444        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13445                IterGenerator<T> generator, Iterator<T> searchIterator) {
13446            // loop through the set of actions; every one must be found in the intent filter
13447            while (searchIterator.hasNext()) {
13448                // we must have at least one filter in the list to consider a match
13449                if (intentList.size() == 0) {
13450                    break;
13451                }
13452
13453                final T searchAction = searchIterator.next();
13454
13455                // loop through the set of intent filters
13456                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13457                while (intentIter.hasNext()) {
13458                    final ActivityIntentInfo intentInfo = intentIter.next();
13459                    boolean selectionFound = false;
13460
13461                    // loop through the intent filter's selection criteria; at least one
13462                    // of them must match the searched criteria
13463                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13464                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13465                        final T intentSelection = intentSelectionIter.next();
13466                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13467                            selectionFound = true;
13468                            break;
13469                        }
13470                    }
13471
13472                    // the selection criteria wasn't found in this filter's set; this filter
13473                    // is not a potential match
13474                    if (!selectionFound) {
13475                        intentIter.remove();
13476                    }
13477                }
13478            }
13479        }
13480
13481        private boolean isProtectedAction(ActivityIntentInfo filter) {
13482            final Iterator<String> actionsIter = filter.actionsIterator();
13483            while (actionsIter != null && actionsIter.hasNext()) {
13484                final String filterAction = actionsIter.next();
13485                if (PROTECTED_ACTIONS.contains(filterAction)) {
13486                    return true;
13487                }
13488            }
13489            return false;
13490        }
13491
13492        /**
13493         * Adjusts the priority of the given intent filter according to policy.
13494         * <p>
13495         * <ul>
13496         * <li>The priority for non privileged applications is capped to '0'</li>
13497         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13498         * <li>The priority for unbundled updates to privileged applications is capped to the
13499         *      priority defined on the system partition</li>
13500         * </ul>
13501         * <p>
13502         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13503         * allowed to obtain any priority on any action.
13504         */
13505        private void adjustPriority(
13506                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13507            // nothing to do; priority is fine as-is
13508            if (intent.getPriority() <= 0) {
13509                return;
13510            }
13511
13512            final ActivityInfo activityInfo = intent.activity.info;
13513            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13514
13515            final boolean privilegedApp =
13516                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13517            if (!privilegedApp) {
13518                // non-privileged applications can never define a priority >0
13519                if (DEBUG_FILTERS) {
13520                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13521                            + " package: " + applicationInfo.packageName
13522                            + " activity: " + intent.activity.className
13523                            + " origPrio: " + intent.getPriority());
13524                }
13525                intent.setPriority(0);
13526                return;
13527            }
13528
13529            if (systemActivities == null) {
13530                // the system package is not disabled; we're parsing the system partition
13531                if (isProtectedAction(intent)) {
13532                    if (mDeferProtectedFilters) {
13533                        // We can't deal with these just yet. No component should ever obtain a
13534                        // >0 priority for a protected actions, with ONE exception -- the setup
13535                        // wizard. The setup wizard, however, cannot be known until we're able to
13536                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13537                        // until all intent filters have been processed. Chicken, meet egg.
13538                        // Let the filter temporarily have a high priority and rectify the
13539                        // priorities after all system packages have been scanned.
13540                        mProtectedFilters.add(intent);
13541                        if (DEBUG_FILTERS) {
13542                            Slog.i(TAG, "Protected action; save for later;"
13543                                    + " package: " + applicationInfo.packageName
13544                                    + " activity: " + intent.activity.className
13545                                    + " origPrio: " + intent.getPriority());
13546                        }
13547                        return;
13548                    } else {
13549                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13550                            Slog.i(TAG, "No setup wizard;"
13551                                + " All protected intents capped to priority 0");
13552                        }
13553                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13554                            if (DEBUG_FILTERS) {
13555                                Slog.i(TAG, "Found setup wizard;"
13556                                    + " allow priority " + intent.getPriority() + ";"
13557                                    + " package: " + intent.activity.info.packageName
13558                                    + " activity: " + intent.activity.className
13559                                    + " priority: " + intent.getPriority());
13560                            }
13561                            // setup wizard gets whatever it wants
13562                            return;
13563                        }
13564                        if (DEBUG_FILTERS) {
13565                            Slog.i(TAG, "Protected action; cap priority to 0;"
13566                                    + " package: " + intent.activity.info.packageName
13567                                    + " activity: " + intent.activity.className
13568                                    + " origPrio: " + intent.getPriority());
13569                        }
13570                        intent.setPriority(0);
13571                        return;
13572                    }
13573                }
13574                // privileged apps on the system image get whatever priority they request
13575                return;
13576            }
13577
13578            // privileged app unbundled update ... try to find the same activity
13579            final PackageParser.Activity foundActivity =
13580                    findMatchingActivity(systemActivities, activityInfo);
13581            if (foundActivity == null) {
13582                // this is a new activity; it cannot obtain >0 priority
13583                if (DEBUG_FILTERS) {
13584                    Slog.i(TAG, "New activity; cap priority to 0;"
13585                            + " package: " + applicationInfo.packageName
13586                            + " activity: " + intent.activity.className
13587                            + " origPrio: " + intent.getPriority());
13588                }
13589                intent.setPriority(0);
13590                return;
13591            }
13592
13593            // found activity, now check for filter equivalence
13594
13595            // a shallow copy is enough; we modify the list, not its contents
13596            final List<ActivityIntentInfo> intentListCopy =
13597                    new ArrayList<>(foundActivity.intents);
13598            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13599
13600            // find matching action subsets
13601            final Iterator<String> actionsIterator = intent.actionsIterator();
13602            if (actionsIterator != null) {
13603                getIntentListSubset(
13604                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13605                if (intentListCopy.size() == 0) {
13606                    // no more intents to match; we're not equivalent
13607                    if (DEBUG_FILTERS) {
13608                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13609                                + " package: " + applicationInfo.packageName
13610                                + " activity: " + intent.activity.className
13611                                + " origPrio: " + intent.getPriority());
13612                    }
13613                    intent.setPriority(0);
13614                    return;
13615                }
13616            }
13617
13618            // find matching category subsets
13619            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13620            if (categoriesIterator != null) {
13621                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13622                        categoriesIterator);
13623                if (intentListCopy.size() == 0) {
13624                    // no more intents to match; we're not equivalent
13625                    if (DEBUG_FILTERS) {
13626                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13627                                + " package: " + applicationInfo.packageName
13628                                + " activity: " + intent.activity.className
13629                                + " origPrio: " + intent.getPriority());
13630                    }
13631                    intent.setPriority(0);
13632                    return;
13633                }
13634            }
13635
13636            // find matching schemes subsets
13637            final Iterator<String> schemesIterator = intent.schemesIterator();
13638            if (schemesIterator != null) {
13639                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13640                        schemesIterator);
13641                if (intentListCopy.size() == 0) {
13642                    // no more intents to match; we're not equivalent
13643                    if (DEBUG_FILTERS) {
13644                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13645                                + " package: " + applicationInfo.packageName
13646                                + " activity: " + intent.activity.className
13647                                + " origPrio: " + intent.getPriority());
13648                    }
13649                    intent.setPriority(0);
13650                    return;
13651                }
13652            }
13653
13654            // find matching authorities subsets
13655            final Iterator<IntentFilter.AuthorityEntry>
13656                    authoritiesIterator = intent.authoritiesIterator();
13657            if (authoritiesIterator != null) {
13658                getIntentListSubset(intentListCopy,
13659                        new AuthoritiesIterGenerator(),
13660                        authoritiesIterator);
13661                if (intentListCopy.size() == 0) {
13662                    // no more intents to match; we're not equivalent
13663                    if (DEBUG_FILTERS) {
13664                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13665                                + " package: " + applicationInfo.packageName
13666                                + " activity: " + intent.activity.className
13667                                + " origPrio: " + intent.getPriority());
13668                    }
13669                    intent.setPriority(0);
13670                    return;
13671                }
13672            }
13673
13674            // we found matching filter(s); app gets the max priority of all intents
13675            int cappedPriority = 0;
13676            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13677                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13678            }
13679            if (intent.getPriority() > cappedPriority) {
13680                if (DEBUG_FILTERS) {
13681                    Slog.i(TAG, "Found matching filter(s);"
13682                            + " cap priority to " + cappedPriority + ";"
13683                            + " package: " + applicationInfo.packageName
13684                            + " activity: " + intent.activity.className
13685                            + " origPrio: " + intent.getPriority());
13686                }
13687                intent.setPriority(cappedPriority);
13688                return;
13689            }
13690            // all this for nothing; the requested priority was <= what was on the system
13691        }
13692
13693        public final void addActivity(PackageParser.Activity a, String type) {
13694            mActivities.put(a.getComponentName(), a);
13695            if (DEBUG_SHOW_INFO)
13696                Log.v(
13697                TAG, "  " + type + " " +
13698                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13699            if (DEBUG_SHOW_INFO)
13700                Log.v(TAG, "    Class=" + a.info.name);
13701            final int NI = a.intents.size();
13702            for (int j=0; j<NI; j++) {
13703                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13704                if ("activity".equals(type)) {
13705                    final PackageSetting ps =
13706                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13707                    final List<PackageParser.Activity> systemActivities =
13708                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13709                    adjustPriority(systemActivities, intent);
13710                }
13711                if (DEBUG_SHOW_INFO) {
13712                    Log.v(TAG, "    IntentFilter:");
13713                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13714                }
13715                if (!intent.debugCheck()) {
13716                    Log.w(TAG, "==> For Activity " + a.info.name);
13717                }
13718                addFilter(intent);
13719            }
13720        }
13721
13722        public final void removeActivity(PackageParser.Activity a, String type) {
13723            mActivities.remove(a.getComponentName());
13724            if (DEBUG_SHOW_INFO) {
13725                Log.v(TAG, "  " + type + " "
13726                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13727                                : a.info.name) + ":");
13728                Log.v(TAG, "    Class=" + a.info.name);
13729            }
13730            final int NI = a.intents.size();
13731            for (int j=0; j<NI; j++) {
13732                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13733                if (DEBUG_SHOW_INFO) {
13734                    Log.v(TAG, "    IntentFilter:");
13735                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13736                }
13737                removeFilter(intent);
13738            }
13739        }
13740
13741        @Override
13742        protected boolean allowFilterResult(
13743                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13744            ActivityInfo filterAi = filter.activity.info;
13745            for (int i=dest.size()-1; i>=0; i--) {
13746                ActivityInfo destAi = dest.get(i).activityInfo;
13747                if (destAi.name == filterAi.name
13748                        && destAi.packageName == filterAi.packageName) {
13749                    return false;
13750                }
13751            }
13752            return true;
13753        }
13754
13755        @Override
13756        protected ActivityIntentInfo[] newArray(int size) {
13757            return new ActivityIntentInfo[size];
13758        }
13759
13760        @Override
13761        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13762            if (!sUserManager.exists(userId)) return true;
13763            PackageParser.Package p = filter.activity.owner;
13764            if (p != null) {
13765                PackageSetting ps = (PackageSetting)p.mExtras;
13766                if (ps != null) {
13767                    // System apps are never considered stopped for purposes of
13768                    // filtering, because there may be no way for the user to
13769                    // actually re-launch them.
13770                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13771                            && ps.getStopped(userId);
13772                }
13773            }
13774            return false;
13775        }
13776
13777        @Override
13778        protected boolean isPackageForFilter(String packageName,
13779                PackageParser.ActivityIntentInfo info) {
13780            return packageName.equals(info.activity.owner.packageName);
13781        }
13782
13783        @Override
13784        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13785                int match, int userId) {
13786            if (!sUserManager.exists(userId)) return null;
13787            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13788                return null;
13789            }
13790            final PackageParser.Activity activity = info.activity;
13791            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13792            if (ps == null) {
13793                return null;
13794            }
13795            final PackageUserState userState = ps.readUserState(userId);
13796            ActivityInfo ai =
13797                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13798            if (ai == null) {
13799                return null;
13800            }
13801            final boolean matchExplicitlyVisibleOnly =
13802                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13803            final boolean matchVisibleToInstantApp =
13804                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13805            final boolean componentVisible =
13806                    matchVisibleToInstantApp
13807                    && info.isVisibleToInstantApp()
13808                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13809            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13810            // throw out filters that aren't visible to ephemeral apps
13811            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13812                return null;
13813            }
13814            // throw out instant app filters if we're not explicitly requesting them
13815            if (!matchInstantApp && userState.instantApp) {
13816                return null;
13817            }
13818            // throw out instant app filters if updates are available; will trigger
13819            // instant app resolution
13820            if (userState.instantApp && ps.isUpdateAvailable()) {
13821                return null;
13822            }
13823            final ResolveInfo res = new ResolveInfo();
13824            res.activityInfo = ai;
13825            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13826                res.filter = info;
13827            }
13828            if (info != null) {
13829                res.handleAllWebDataURI = info.handleAllWebDataURI();
13830            }
13831            res.priority = info.getPriority();
13832            res.preferredOrder = activity.owner.mPreferredOrder;
13833            //System.out.println("Result: " + res.activityInfo.className +
13834            //                   " = " + res.priority);
13835            res.match = match;
13836            res.isDefault = info.hasDefault;
13837            res.labelRes = info.labelRes;
13838            res.nonLocalizedLabel = info.nonLocalizedLabel;
13839            if (userNeedsBadging(userId)) {
13840                res.noResourceId = true;
13841            } else {
13842                res.icon = info.icon;
13843            }
13844            res.iconResourceId = info.icon;
13845            res.system = res.activityInfo.applicationInfo.isSystemApp();
13846            res.isInstantAppAvailable = userState.instantApp;
13847            return res;
13848        }
13849
13850        @Override
13851        protected void sortResults(List<ResolveInfo> results) {
13852            Collections.sort(results, mResolvePrioritySorter);
13853        }
13854
13855        @Override
13856        protected void dumpFilter(PrintWriter out, String prefix,
13857                PackageParser.ActivityIntentInfo filter) {
13858            out.print(prefix); out.print(
13859                    Integer.toHexString(System.identityHashCode(filter.activity)));
13860                    out.print(' ');
13861                    filter.activity.printComponentShortName(out);
13862                    out.print(" filter ");
13863                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13864        }
13865
13866        @Override
13867        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13868            return filter.activity;
13869        }
13870
13871        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13872            PackageParser.Activity activity = (PackageParser.Activity)label;
13873            out.print(prefix); out.print(
13874                    Integer.toHexString(System.identityHashCode(activity)));
13875                    out.print(' ');
13876                    activity.printComponentShortName(out);
13877            if (count > 1) {
13878                out.print(" ("); out.print(count); out.print(" filters)");
13879            }
13880            out.println();
13881        }
13882
13883        // Keys are String (activity class name), values are Activity.
13884        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13885                = new ArrayMap<ComponentName, PackageParser.Activity>();
13886        private int mFlags;
13887    }
13888
13889    private final class ServiceIntentResolver
13890            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13891        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13892                boolean defaultOnly, int userId) {
13893            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13894            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13895        }
13896
13897        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13898                int userId) {
13899            if (!sUserManager.exists(userId)) return null;
13900            mFlags = flags;
13901            return super.queryIntent(intent, resolvedType,
13902                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13903                    userId);
13904        }
13905
13906        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13907                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13908            if (!sUserManager.exists(userId)) return null;
13909            if (packageServices == null) {
13910                return null;
13911            }
13912            mFlags = flags;
13913            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13914            final int N = packageServices.size();
13915            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13916                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13917
13918            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13919            for (int i = 0; i < N; ++i) {
13920                intentFilters = packageServices.get(i).intents;
13921                if (intentFilters != null && intentFilters.size() > 0) {
13922                    PackageParser.ServiceIntentInfo[] array =
13923                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13924                    intentFilters.toArray(array);
13925                    listCut.add(array);
13926                }
13927            }
13928            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13929        }
13930
13931        public final void addService(PackageParser.Service s) {
13932            mServices.put(s.getComponentName(), s);
13933            if (DEBUG_SHOW_INFO) {
13934                Log.v(TAG, "  "
13935                        + (s.info.nonLocalizedLabel != null
13936                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13937                Log.v(TAG, "    Class=" + s.info.name);
13938            }
13939            final int NI = s.intents.size();
13940            int j;
13941            for (j=0; j<NI; j++) {
13942                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13943                if (DEBUG_SHOW_INFO) {
13944                    Log.v(TAG, "    IntentFilter:");
13945                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13946                }
13947                if (!intent.debugCheck()) {
13948                    Log.w(TAG, "==> For Service " + s.info.name);
13949                }
13950                addFilter(intent);
13951            }
13952        }
13953
13954        public final void removeService(PackageParser.Service s) {
13955            mServices.remove(s.getComponentName());
13956            if (DEBUG_SHOW_INFO) {
13957                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13958                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13959                Log.v(TAG, "    Class=" + s.info.name);
13960            }
13961            final int NI = s.intents.size();
13962            int j;
13963            for (j=0; j<NI; j++) {
13964                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13965                if (DEBUG_SHOW_INFO) {
13966                    Log.v(TAG, "    IntentFilter:");
13967                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13968                }
13969                removeFilter(intent);
13970            }
13971        }
13972
13973        @Override
13974        protected boolean allowFilterResult(
13975                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13976            ServiceInfo filterSi = filter.service.info;
13977            for (int i=dest.size()-1; i>=0; i--) {
13978                ServiceInfo destAi = dest.get(i).serviceInfo;
13979                if (destAi.name == filterSi.name
13980                        && destAi.packageName == filterSi.packageName) {
13981                    return false;
13982                }
13983            }
13984            return true;
13985        }
13986
13987        @Override
13988        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13989            return new PackageParser.ServiceIntentInfo[size];
13990        }
13991
13992        @Override
13993        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13994            if (!sUserManager.exists(userId)) return true;
13995            PackageParser.Package p = filter.service.owner;
13996            if (p != null) {
13997                PackageSetting ps = (PackageSetting)p.mExtras;
13998                if (ps != null) {
13999                    // System apps are never considered stopped for purposes of
14000                    // filtering, because there may be no way for the user to
14001                    // actually re-launch them.
14002                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14003                            && ps.getStopped(userId);
14004                }
14005            }
14006            return false;
14007        }
14008
14009        @Override
14010        protected boolean isPackageForFilter(String packageName,
14011                PackageParser.ServiceIntentInfo info) {
14012            return packageName.equals(info.service.owner.packageName);
14013        }
14014
14015        @Override
14016        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14017                int match, int userId) {
14018            if (!sUserManager.exists(userId)) return null;
14019            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14020            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14021                return null;
14022            }
14023            final PackageParser.Service service = info.service;
14024            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14025            if (ps == null) {
14026                return null;
14027            }
14028            final PackageUserState userState = ps.readUserState(userId);
14029            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14030                    userState, userId);
14031            if (si == null) {
14032                return null;
14033            }
14034            final boolean matchVisibleToInstantApp =
14035                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14036            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14037            // throw out filters that aren't visible to ephemeral apps
14038            if (matchVisibleToInstantApp
14039                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14040                return null;
14041            }
14042            // throw out ephemeral filters if we're not explicitly requesting them
14043            if (!isInstantApp && userState.instantApp) {
14044                return null;
14045            }
14046            // throw out instant app filters if updates are available; will trigger
14047            // instant app resolution
14048            if (userState.instantApp && ps.isUpdateAvailable()) {
14049                return null;
14050            }
14051            final ResolveInfo res = new ResolveInfo();
14052            res.serviceInfo = si;
14053            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14054                res.filter = filter;
14055            }
14056            res.priority = info.getPriority();
14057            res.preferredOrder = service.owner.mPreferredOrder;
14058            res.match = match;
14059            res.isDefault = info.hasDefault;
14060            res.labelRes = info.labelRes;
14061            res.nonLocalizedLabel = info.nonLocalizedLabel;
14062            res.icon = info.icon;
14063            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14064            return res;
14065        }
14066
14067        @Override
14068        protected void sortResults(List<ResolveInfo> results) {
14069            Collections.sort(results, mResolvePrioritySorter);
14070        }
14071
14072        @Override
14073        protected void dumpFilter(PrintWriter out, String prefix,
14074                PackageParser.ServiceIntentInfo filter) {
14075            out.print(prefix); out.print(
14076                    Integer.toHexString(System.identityHashCode(filter.service)));
14077                    out.print(' ');
14078                    filter.service.printComponentShortName(out);
14079                    out.print(" filter ");
14080                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14081        }
14082
14083        @Override
14084        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14085            return filter.service;
14086        }
14087
14088        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14089            PackageParser.Service service = (PackageParser.Service)label;
14090            out.print(prefix); out.print(
14091                    Integer.toHexString(System.identityHashCode(service)));
14092                    out.print(' ');
14093                    service.printComponentShortName(out);
14094            if (count > 1) {
14095                out.print(" ("); out.print(count); out.print(" filters)");
14096            }
14097            out.println();
14098        }
14099
14100//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14101//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14102//            final List<ResolveInfo> retList = Lists.newArrayList();
14103//            while (i.hasNext()) {
14104//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14105//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14106//                    retList.add(resolveInfo);
14107//                }
14108//            }
14109//            return retList;
14110//        }
14111
14112        // Keys are String (activity class name), values are Activity.
14113        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14114                = new ArrayMap<ComponentName, PackageParser.Service>();
14115        private int mFlags;
14116    }
14117
14118    private final class ProviderIntentResolver
14119            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14120        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14121                boolean defaultOnly, int userId) {
14122            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14123            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14124        }
14125
14126        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14127                int userId) {
14128            if (!sUserManager.exists(userId))
14129                return null;
14130            mFlags = flags;
14131            return super.queryIntent(intent, resolvedType,
14132                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14133                    userId);
14134        }
14135
14136        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14137                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14138            if (!sUserManager.exists(userId))
14139                return null;
14140            if (packageProviders == null) {
14141                return null;
14142            }
14143            mFlags = flags;
14144            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14145            final int N = packageProviders.size();
14146            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14147                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14148
14149            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14150            for (int i = 0; i < N; ++i) {
14151                intentFilters = packageProviders.get(i).intents;
14152                if (intentFilters != null && intentFilters.size() > 0) {
14153                    PackageParser.ProviderIntentInfo[] array =
14154                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14155                    intentFilters.toArray(array);
14156                    listCut.add(array);
14157                }
14158            }
14159            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14160        }
14161
14162        public final void addProvider(PackageParser.Provider p) {
14163            if (mProviders.containsKey(p.getComponentName())) {
14164                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14165                return;
14166            }
14167
14168            mProviders.put(p.getComponentName(), p);
14169            if (DEBUG_SHOW_INFO) {
14170                Log.v(TAG, "  "
14171                        + (p.info.nonLocalizedLabel != null
14172                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14173                Log.v(TAG, "    Class=" + p.info.name);
14174            }
14175            final int NI = p.intents.size();
14176            int j;
14177            for (j = 0; j < NI; j++) {
14178                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14179                if (DEBUG_SHOW_INFO) {
14180                    Log.v(TAG, "    IntentFilter:");
14181                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14182                }
14183                if (!intent.debugCheck()) {
14184                    Log.w(TAG, "==> For Provider " + p.info.name);
14185                }
14186                addFilter(intent);
14187            }
14188        }
14189
14190        public final void removeProvider(PackageParser.Provider p) {
14191            mProviders.remove(p.getComponentName());
14192            if (DEBUG_SHOW_INFO) {
14193                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14194                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14195                Log.v(TAG, "    Class=" + p.info.name);
14196            }
14197            final int NI = p.intents.size();
14198            int j;
14199            for (j = 0; j < NI; j++) {
14200                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14201                if (DEBUG_SHOW_INFO) {
14202                    Log.v(TAG, "    IntentFilter:");
14203                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14204                }
14205                removeFilter(intent);
14206            }
14207        }
14208
14209        @Override
14210        protected boolean allowFilterResult(
14211                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14212            ProviderInfo filterPi = filter.provider.info;
14213            for (int i = dest.size() - 1; i >= 0; i--) {
14214                ProviderInfo destPi = dest.get(i).providerInfo;
14215                if (destPi.name == filterPi.name
14216                        && destPi.packageName == filterPi.packageName) {
14217                    return false;
14218                }
14219            }
14220            return true;
14221        }
14222
14223        @Override
14224        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14225            return new PackageParser.ProviderIntentInfo[size];
14226        }
14227
14228        @Override
14229        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14230            if (!sUserManager.exists(userId))
14231                return true;
14232            PackageParser.Package p = filter.provider.owner;
14233            if (p != null) {
14234                PackageSetting ps = (PackageSetting) p.mExtras;
14235                if (ps != null) {
14236                    // System apps are never considered stopped for purposes of
14237                    // filtering, because there may be no way for the user to
14238                    // actually re-launch them.
14239                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14240                            && ps.getStopped(userId);
14241                }
14242            }
14243            return false;
14244        }
14245
14246        @Override
14247        protected boolean isPackageForFilter(String packageName,
14248                PackageParser.ProviderIntentInfo info) {
14249            return packageName.equals(info.provider.owner.packageName);
14250        }
14251
14252        @Override
14253        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14254                int match, int userId) {
14255            if (!sUserManager.exists(userId))
14256                return null;
14257            final PackageParser.ProviderIntentInfo info = filter;
14258            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14259                return null;
14260            }
14261            final PackageParser.Provider provider = info.provider;
14262            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14263            if (ps == null) {
14264                return null;
14265            }
14266            final PackageUserState userState = ps.readUserState(userId);
14267            final boolean matchVisibleToInstantApp =
14268                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14269            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14270            // throw out filters that aren't visible to instant applications
14271            if (matchVisibleToInstantApp
14272                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14273                return null;
14274            }
14275            // throw out instant application filters if we're not explicitly requesting them
14276            if (!isInstantApp && userState.instantApp) {
14277                return null;
14278            }
14279            // throw out instant application filters if updates are available; will trigger
14280            // instant application resolution
14281            if (userState.instantApp && ps.isUpdateAvailable()) {
14282                return null;
14283            }
14284            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14285                    userState, userId);
14286            if (pi == null) {
14287                return null;
14288            }
14289            final ResolveInfo res = new ResolveInfo();
14290            res.providerInfo = pi;
14291            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14292                res.filter = filter;
14293            }
14294            res.priority = info.getPriority();
14295            res.preferredOrder = provider.owner.mPreferredOrder;
14296            res.match = match;
14297            res.isDefault = info.hasDefault;
14298            res.labelRes = info.labelRes;
14299            res.nonLocalizedLabel = info.nonLocalizedLabel;
14300            res.icon = info.icon;
14301            res.system = res.providerInfo.applicationInfo.isSystemApp();
14302            return res;
14303        }
14304
14305        @Override
14306        protected void sortResults(List<ResolveInfo> results) {
14307            Collections.sort(results, mResolvePrioritySorter);
14308        }
14309
14310        @Override
14311        protected void dumpFilter(PrintWriter out, String prefix,
14312                PackageParser.ProviderIntentInfo filter) {
14313            out.print(prefix);
14314            out.print(
14315                    Integer.toHexString(System.identityHashCode(filter.provider)));
14316            out.print(' ');
14317            filter.provider.printComponentShortName(out);
14318            out.print(" filter ");
14319            out.println(Integer.toHexString(System.identityHashCode(filter)));
14320        }
14321
14322        @Override
14323        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14324            return filter.provider;
14325        }
14326
14327        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14328            PackageParser.Provider provider = (PackageParser.Provider)label;
14329            out.print(prefix); out.print(
14330                    Integer.toHexString(System.identityHashCode(provider)));
14331                    out.print(' ');
14332                    provider.printComponentShortName(out);
14333            if (count > 1) {
14334                out.print(" ("); out.print(count); out.print(" filters)");
14335            }
14336            out.println();
14337        }
14338
14339        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14340                = new ArrayMap<ComponentName, PackageParser.Provider>();
14341        private int mFlags;
14342    }
14343
14344    static final class EphemeralIntentResolver
14345            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14346        /**
14347         * The result that has the highest defined order. Ordering applies on a
14348         * per-package basis. Mapping is from package name to Pair of order and
14349         * EphemeralResolveInfo.
14350         * <p>
14351         * NOTE: This is implemented as a field variable for convenience and efficiency.
14352         * By having a field variable, we're able to track filter ordering as soon as
14353         * a non-zero order is defined. Otherwise, multiple loops across the result set
14354         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14355         * this needs to be contained entirely within {@link #filterResults}.
14356         */
14357        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14358
14359        @Override
14360        protected AuxiliaryResolveInfo[] newArray(int size) {
14361            return new AuxiliaryResolveInfo[size];
14362        }
14363
14364        @Override
14365        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14366            return true;
14367        }
14368
14369        @Override
14370        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14371                int userId) {
14372            if (!sUserManager.exists(userId)) {
14373                return null;
14374            }
14375            final String packageName = responseObj.resolveInfo.getPackageName();
14376            final Integer order = responseObj.getOrder();
14377            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14378                    mOrderResult.get(packageName);
14379            // ordering is enabled and this item's order isn't high enough
14380            if (lastOrderResult != null && lastOrderResult.first >= order) {
14381                return null;
14382            }
14383            final InstantAppResolveInfo res = responseObj.resolveInfo;
14384            if (order > 0) {
14385                // non-zero order, enable ordering
14386                mOrderResult.put(packageName, new Pair<>(order, res));
14387            }
14388            return responseObj;
14389        }
14390
14391        @Override
14392        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14393            // only do work if ordering is enabled [most of the time it won't be]
14394            if (mOrderResult.size() == 0) {
14395                return;
14396            }
14397            int resultSize = results.size();
14398            for (int i = 0; i < resultSize; i++) {
14399                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14400                final String packageName = info.getPackageName();
14401                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14402                if (savedInfo == null) {
14403                    // package doesn't having ordering
14404                    continue;
14405                }
14406                if (savedInfo.second == info) {
14407                    // circled back to the highest ordered item; remove from order list
14408                    mOrderResult.remove(packageName);
14409                    if (mOrderResult.size() == 0) {
14410                        // no more ordered items
14411                        break;
14412                    }
14413                    continue;
14414                }
14415                // item has a worse order, remove it from the result list
14416                results.remove(i);
14417                resultSize--;
14418                i--;
14419            }
14420        }
14421    }
14422
14423    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14424            new Comparator<ResolveInfo>() {
14425        public int compare(ResolveInfo r1, ResolveInfo r2) {
14426            int v1 = r1.priority;
14427            int v2 = r2.priority;
14428            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14429            if (v1 != v2) {
14430                return (v1 > v2) ? -1 : 1;
14431            }
14432            v1 = r1.preferredOrder;
14433            v2 = r2.preferredOrder;
14434            if (v1 != v2) {
14435                return (v1 > v2) ? -1 : 1;
14436            }
14437            if (r1.isDefault != r2.isDefault) {
14438                return r1.isDefault ? -1 : 1;
14439            }
14440            v1 = r1.match;
14441            v2 = r2.match;
14442            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14443            if (v1 != v2) {
14444                return (v1 > v2) ? -1 : 1;
14445            }
14446            if (r1.system != r2.system) {
14447                return r1.system ? -1 : 1;
14448            }
14449            if (r1.activityInfo != null) {
14450                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14451            }
14452            if (r1.serviceInfo != null) {
14453                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14454            }
14455            if (r1.providerInfo != null) {
14456                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14457            }
14458            return 0;
14459        }
14460    };
14461
14462    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14463            new Comparator<ProviderInfo>() {
14464        public int compare(ProviderInfo p1, ProviderInfo p2) {
14465            final int v1 = p1.initOrder;
14466            final int v2 = p2.initOrder;
14467            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14468        }
14469    };
14470
14471    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14472            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14473            final int[] userIds) {
14474        mHandler.post(new Runnable() {
14475            @Override
14476            public void run() {
14477                try {
14478                    final IActivityManager am = ActivityManager.getService();
14479                    if (am == null) return;
14480                    final int[] resolvedUserIds;
14481                    if (userIds == null) {
14482                        resolvedUserIds = am.getRunningUserIds();
14483                    } else {
14484                        resolvedUserIds = userIds;
14485                    }
14486                    for (int id : resolvedUserIds) {
14487                        final Intent intent = new Intent(action,
14488                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14489                        if (extras != null) {
14490                            intent.putExtras(extras);
14491                        }
14492                        if (targetPkg != null) {
14493                            intent.setPackage(targetPkg);
14494                        }
14495                        // Modify the UID when posting to other users
14496                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14497                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14498                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14499                            intent.putExtra(Intent.EXTRA_UID, uid);
14500                        }
14501                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14502                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14503                        if (DEBUG_BROADCASTS) {
14504                            RuntimeException here = new RuntimeException("here");
14505                            here.fillInStackTrace();
14506                            Slog.d(TAG, "Sending to user " + id + ": "
14507                                    + intent.toShortString(false, true, false, false)
14508                                    + " " + intent.getExtras(), here);
14509                        }
14510                        am.broadcastIntent(null, intent, null, finishedReceiver,
14511                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14512                                null, finishedReceiver != null, false, id);
14513                    }
14514                } catch (RemoteException ex) {
14515                }
14516            }
14517        });
14518    }
14519
14520    /**
14521     * Check if the external storage media is available. This is true if there
14522     * is a mounted external storage medium or if the external storage is
14523     * emulated.
14524     */
14525    private boolean isExternalMediaAvailable() {
14526        return mMediaMounted || Environment.isExternalStorageEmulated();
14527    }
14528
14529    @Override
14530    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14531        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14532            return null;
14533        }
14534        // writer
14535        synchronized (mPackages) {
14536            if (!isExternalMediaAvailable()) {
14537                // If the external storage is no longer mounted at this point,
14538                // the caller may not have been able to delete all of this
14539                // packages files and can not delete any more.  Bail.
14540                return null;
14541            }
14542            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14543            if (lastPackage != null) {
14544                pkgs.remove(lastPackage);
14545            }
14546            if (pkgs.size() > 0) {
14547                return pkgs.get(0);
14548            }
14549        }
14550        return null;
14551    }
14552
14553    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14554        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14555                userId, andCode ? 1 : 0, packageName);
14556        if (mSystemReady) {
14557            msg.sendToTarget();
14558        } else {
14559            if (mPostSystemReadyMessages == null) {
14560                mPostSystemReadyMessages = new ArrayList<>();
14561            }
14562            mPostSystemReadyMessages.add(msg);
14563        }
14564    }
14565
14566    void startCleaningPackages() {
14567        // reader
14568        if (!isExternalMediaAvailable()) {
14569            return;
14570        }
14571        synchronized (mPackages) {
14572            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14573                return;
14574            }
14575        }
14576        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14577        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14578        IActivityManager am = ActivityManager.getService();
14579        if (am != null) {
14580            int dcsUid = -1;
14581            synchronized (mPackages) {
14582                if (!mDefaultContainerWhitelisted) {
14583                    mDefaultContainerWhitelisted = true;
14584                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14585                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14586                }
14587            }
14588            try {
14589                if (dcsUid > 0) {
14590                    am.backgroundWhitelistUid(dcsUid);
14591                }
14592                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14593                        UserHandle.USER_SYSTEM);
14594            } catch (RemoteException e) {
14595            }
14596        }
14597    }
14598
14599    @Override
14600    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14601            int installFlags, String installerPackageName, int userId) {
14602        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14603
14604        final int callingUid = Binder.getCallingUid();
14605        enforceCrossUserPermission(callingUid, userId,
14606                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14607
14608        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14609            try {
14610                if (observer != null) {
14611                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14612                }
14613            } catch (RemoteException re) {
14614            }
14615            return;
14616        }
14617
14618        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14619            installFlags |= PackageManager.INSTALL_FROM_ADB;
14620
14621        } else {
14622            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14623            // about installerPackageName.
14624
14625            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14626            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14627        }
14628
14629        UserHandle user;
14630        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14631            user = UserHandle.ALL;
14632        } else {
14633            user = new UserHandle(userId);
14634        }
14635
14636        // Only system components can circumvent runtime permissions when installing.
14637        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14638                && mContext.checkCallingOrSelfPermission(Manifest.permission
14639                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14640            throw new SecurityException("You need the "
14641                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14642                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14643        }
14644
14645        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14646                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14647            throw new IllegalArgumentException(
14648                    "New installs into ASEC containers no longer supported");
14649        }
14650
14651        final File originFile = new File(originPath);
14652        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14653
14654        final Message msg = mHandler.obtainMessage(INIT_COPY);
14655        final VerificationInfo verificationInfo = new VerificationInfo(
14656                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14657        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14658                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14659                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14660                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14661        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14662        msg.obj = params;
14663
14664        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14665                System.identityHashCode(msg.obj));
14666        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14667                System.identityHashCode(msg.obj));
14668
14669        mHandler.sendMessage(msg);
14670    }
14671
14672
14673    /**
14674     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14675     * it is acting on behalf on an enterprise or the user).
14676     *
14677     * Note that the ordering of the conditionals in this method is important. The checks we perform
14678     * are as follows, in this order:
14679     *
14680     * 1) If the install is being performed by a system app, we can trust the app to have set the
14681     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14682     *    what it is.
14683     * 2) If the install is being performed by a device or profile owner app, the install reason
14684     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14685     *    set the install reason correctly. If the app targets an older SDK version where install
14686     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14687     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14688     * 3) In all other cases, the install is being performed by a regular app that is neither part
14689     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14690     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14691     *    set to enterprise policy and if so, change it to unknown instead.
14692     */
14693    private int fixUpInstallReason(String installerPackageName, int installerUid,
14694            int installReason) {
14695        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14696                == PERMISSION_GRANTED) {
14697            // If the install is being performed by a system app, we trust that app to have set the
14698            // install reason correctly.
14699            return installReason;
14700        }
14701
14702        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14703            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14704        if (dpm != null) {
14705            ComponentName owner = null;
14706            try {
14707                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14708                if (owner == null) {
14709                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14710                }
14711            } catch (RemoteException e) {
14712            }
14713            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14714                // If the install is being performed by a device or profile owner, the install
14715                // reason should be enterprise policy.
14716                return PackageManager.INSTALL_REASON_POLICY;
14717            }
14718        }
14719
14720        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14721            // If the install is being performed by a regular app (i.e. neither system app nor
14722            // device or profile owner), we have no reason to believe that the app is acting on
14723            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14724            // change it to unknown instead.
14725            return PackageManager.INSTALL_REASON_UNKNOWN;
14726        }
14727
14728        // If the install is being performed by a regular app and the install reason was set to any
14729        // value but enterprise policy, leave the install reason unchanged.
14730        return installReason;
14731    }
14732
14733    void installStage(String packageName, File stagedDir, String stagedCid,
14734            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14735            String installerPackageName, int installerUid, UserHandle user,
14736            Certificate[][] certificates) {
14737        if (DEBUG_EPHEMERAL) {
14738            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14739                Slog.d(TAG, "Ephemeral install of " + packageName);
14740            }
14741        }
14742        final VerificationInfo verificationInfo = new VerificationInfo(
14743                sessionParams.originatingUri, sessionParams.referrerUri,
14744                sessionParams.originatingUid, installerUid);
14745
14746        final OriginInfo origin;
14747        if (stagedDir != null) {
14748            origin = OriginInfo.fromStagedFile(stagedDir);
14749        } else {
14750            origin = OriginInfo.fromStagedContainer(stagedCid);
14751        }
14752
14753        final Message msg = mHandler.obtainMessage(INIT_COPY);
14754        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14755                sessionParams.installReason);
14756        final InstallParams params = new InstallParams(origin, null, observer,
14757                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14758                verificationInfo, user, sessionParams.abiOverride,
14759                sessionParams.grantedRuntimePermissions, certificates, installReason);
14760        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14761        msg.obj = params;
14762
14763        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14764                System.identityHashCode(msg.obj));
14765        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14766                System.identityHashCode(msg.obj));
14767
14768        mHandler.sendMessage(msg);
14769    }
14770
14771    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14772            int userId) {
14773        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14774        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14775                false /*startReceiver*/, pkgSetting.appId, userId);
14776
14777        // Send a session commit broadcast
14778        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14779        info.installReason = pkgSetting.getInstallReason(userId);
14780        info.appPackageName = packageName;
14781        sendSessionCommitBroadcast(info, userId);
14782    }
14783
14784    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14785            boolean includeStopped, int appId, int... userIds) {
14786        if (ArrayUtils.isEmpty(userIds)) {
14787            return;
14788        }
14789        Bundle extras = new Bundle(1);
14790        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14791        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14792
14793        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14794                packageName, extras, 0, null, null, userIds);
14795        if (sendBootCompleted) {
14796            mHandler.post(() -> {
14797                        for (int userId : userIds) {
14798                            sendBootCompletedBroadcastToSystemApp(
14799                                    packageName, includeStopped, userId);
14800                        }
14801                    }
14802            );
14803        }
14804    }
14805
14806    /**
14807     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14808     * automatically without needing an explicit launch.
14809     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14810     */
14811    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14812            int userId) {
14813        // If user is not running, the app didn't miss any broadcast
14814        if (!mUserManagerInternal.isUserRunning(userId)) {
14815            return;
14816        }
14817        final IActivityManager am = ActivityManager.getService();
14818        try {
14819            // Deliver LOCKED_BOOT_COMPLETED first
14820            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14821                    .setPackage(packageName);
14822            if (includeStopped) {
14823                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14824            }
14825            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14826            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14827                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14828
14829            // Deliver BOOT_COMPLETED only if user is unlocked
14830            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14831                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14832                if (includeStopped) {
14833                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14834                }
14835                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14836                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14837            }
14838        } catch (RemoteException e) {
14839            throw e.rethrowFromSystemServer();
14840        }
14841    }
14842
14843    @Override
14844    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14845            int userId) {
14846        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14847        PackageSetting pkgSetting;
14848        final int callingUid = Binder.getCallingUid();
14849        enforceCrossUserPermission(callingUid, userId,
14850                true /* requireFullPermission */, true /* checkShell */,
14851                "setApplicationHiddenSetting for user " + userId);
14852
14853        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14854            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14855            return false;
14856        }
14857
14858        long callingId = Binder.clearCallingIdentity();
14859        try {
14860            boolean sendAdded = false;
14861            boolean sendRemoved = false;
14862            // writer
14863            synchronized (mPackages) {
14864                pkgSetting = mSettings.mPackages.get(packageName);
14865                if (pkgSetting == null) {
14866                    return false;
14867                }
14868                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14869                    return false;
14870                }
14871                // Do not allow "android" is being disabled
14872                if ("android".equals(packageName)) {
14873                    Slog.w(TAG, "Cannot hide package: android");
14874                    return false;
14875                }
14876                // Cannot hide static shared libs as they are considered
14877                // a part of the using app (emulating static linking). Also
14878                // static libs are installed always on internal storage.
14879                PackageParser.Package pkg = mPackages.get(packageName);
14880                if (pkg != null && pkg.staticSharedLibName != null) {
14881                    Slog.w(TAG, "Cannot hide package: " + packageName
14882                            + " providing static shared library: "
14883                            + pkg.staticSharedLibName);
14884                    return false;
14885                }
14886                // Only allow protected packages to hide themselves.
14887                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14888                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14889                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14890                    return false;
14891                }
14892
14893                if (pkgSetting.getHidden(userId) != hidden) {
14894                    pkgSetting.setHidden(hidden, userId);
14895                    mSettings.writePackageRestrictionsLPr(userId);
14896                    if (hidden) {
14897                        sendRemoved = true;
14898                    } else {
14899                        sendAdded = true;
14900                    }
14901                }
14902            }
14903            if (sendAdded) {
14904                sendPackageAddedForUser(packageName, pkgSetting, userId);
14905                return true;
14906            }
14907            if (sendRemoved) {
14908                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14909                        "hiding pkg");
14910                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14911                return true;
14912            }
14913        } finally {
14914            Binder.restoreCallingIdentity(callingId);
14915        }
14916        return false;
14917    }
14918
14919    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14920            int userId) {
14921        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14922        info.removedPackage = packageName;
14923        info.installerPackageName = pkgSetting.installerPackageName;
14924        info.removedUsers = new int[] {userId};
14925        info.broadcastUsers = new int[] {userId};
14926        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14927        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14928    }
14929
14930    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14931        if (pkgList.length > 0) {
14932            Bundle extras = new Bundle(1);
14933            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14934
14935            sendPackageBroadcast(
14936                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14937                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14938                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14939                    new int[] {userId});
14940        }
14941    }
14942
14943    /**
14944     * Returns true if application is not found or there was an error. Otherwise it returns
14945     * the hidden state of the package for the given user.
14946     */
14947    @Override
14948    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14949        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14950        final int callingUid = Binder.getCallingUid();
14951        enforceCrossUserPermission(callingUid, userId,
14952                true /* requireFullPermission */, false /* checkShell */,
14953                "getApplicationHidden for user " + userId);
14954        PackageSetting ps;
14955        long callingId = Binder.clearCallingIdentity();
14956        try {
14957            // writer
14958            synchronized (mPackages) {
14959                ps = mSettings.mPackages.get(packageName);
14960                if (ps == null) {
14961                    return true;
14962                }
14963                if (filterAppAccessLPr(ps, callingUid, userId)) {
14964                    return true;
14965                }
14966                return ps.getHidden(userId);
14967            }
14968        } finally {
14969            Binder.restoreCallingIdentity(callingId);
14970        }
14971    }
14972
14973    /**
14974     * @hide
14975     */
14976    @Override
14977    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14978            int installReason) {
14979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14980                null);
14981        PackageSetting pkgSetting;
14982        final int callingUid = Binder.getCallingUid();
14983        enforceCrossUserPermission(callingUid, userId,
14984                true /* requireFullPermission */, true /* checkShell */,
14985                "installExistingPackage for user " + userId);
14986        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14987            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14988        }
14989
14990        long callingId = Binder.clearCallingIdentity();
14991        try {
14992            boolean installed = false;
14993            final boolean instantApp =
14994                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14995            final boolean fullApp =
14996                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14997
14998            // writer
14999            synchronized (mPackages) {
15000                pkgSetting = mSettings.mPackages.get(packageName);
15001                if (pkgSetting == null) {
15002                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15003                }
15004                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15005                    // only allow the existing package to be used if it's installed as a full
15006                    // application for at least one user
15007                    boolean installAllowed = false;
15008                    for (int checkUserId : sUserManager.getUserIds()) {
15009                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15010                        if (installAllowed) {
15011                            break;
15012                        }
15013                    }
15014                    if (!installAllowed) {
15015                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15016                    }
15017                }
15018                if (!pkgSetting.getInstalled(userId)) {
15019                    pkgSetting.setInstalled(true, userId);
15020                    pkgSetting.setHidden(false, userId);
15021                    pkgSetting.setInstallReason(installReason, userId);
15022                    mSettings.writePackageRestrictionsLPr(userId);
15023                    mSettings.writeKernelMappingLPr(pkgSetting);
15024                    installed = true;
15025                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15026                    // upgrade app from instant to full; we don't allow app downgrade
15027                    installed = true;
15028                }
15029                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15030            }
15031
15032            if (installed) {
15033                if (pkgSetting.pkg != null) {
15034                    synchronized (mInstallLock) {
15035                        // We don't need to freeze for a brand new install
15036                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15037                    }
15038                }
15039                sendPackageAddedForUser(packageName, pkgSetting, userId);
15040                synchronized (mPackages) {
15041                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15042                }
15043            }
15044        } finally {
15045            Binder.restoreCallingIdentity(callingId);
15046        }
15047
15048        return PackageManager.INSTALL_SUCCEEDED;
15049    }
15050
15051    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15052            boolean instantApp, boolean fullApp) {
15053        // no state specified; do nothing
15054        if (!instantApp && !fullApp) {
15055            return;
15056        }
15057        if (userId != UserHandle.USER_ALL) {
15058            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15059                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15060            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15061                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15062            }
15063        } else {
15064            for (int currentUserId : sUserManager.getUserIds()) {
15065                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15066                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15067                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15068                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15069                }
15070            }
15071        }
15072    }
15073
15074    boolean isUserRestricted(int userId, String restrictionKey) {
15075        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15076        if (restrictions.getBoolean(restrictionKey, false)) {
15077            Log.w(TAG, "User is restricted: " + restrictionKey);
15078            return true;
15079        }
15080        return false;
15081    }
15082
15083    @Override
15084    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15085            int userId) {
15086        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15087        final int callingUid = Binder.getCallingUid();
15088        enforceCrossUserPermission(callingUid, userId,
15089                true /* requireFullPermission */, true /* checkShell */,
15090                "setPackagesSuspended for user " + userId);
15091
15092        if (ArrayUtils.isEmpty(packageNames)) {
15093            return packageNames;
15094        }
15095
15096        // List of package names for whom the suspended state has changed.
15097        List<String> changedPackages = new ArrayList<>(packageNames.length);
15098        // List of package names for whom the suspended state is not set as requested in this
15099        // method.
15100        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15101        long callingId = Binder.clearCallingIdentity();
15102        try {
15103            for (int i = 0; i < packageNames.length; i++) {
15104                String packageName = packageNames[i];
15105                boolean changed = false;
15106                final int appId;
15107                synchronized (mPackages) {
15108                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15109                    if (pkgSetting == null
15110                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15111                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15112                                + "\". Skipping suspending/un-suspending.");
15113                        unactionedPackages.add(packageName);
15114                        continue;
15115                    }
15116                    appId = pkgSetting.appId;
15117                    if (pkgSetting.getSuspended(userId) != suspended) {
15118                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15119                            unactionedPackages.add(packageName);
15120                            continue;
15121                        }
15122                        pkgSetting.setSuspended(suspended, userId);
15123                        mSettings.writePackageRestrictionsLPr(userId);
15124                        changed = true;
15125                        changedPackages.add(packageName);
15126                    }
15127                }
15128
15129                if (changed && suspended) {
15130                    killApplication(packageName, UserHandle.getUid(userId, appId),
15131                            "suspending package");
15132                }
15133            }
15134        } finally {
15135            Binder.restoreCallingIdentity(callingId);
15136        }
15137
15138        if (!changedPackages.isEmpty()) {
15139            sendPackagesSuspendedForUser(changedPackages.toArray(
15140                    new String[changedPackages.size()]), userId, suspended);
15141        }
15142
15143        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15144    }
15145
15146    @Override
15147    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15148        final int callingUid = Binder.getCallingUid();
15149        enforceCrossUserPermission(callingUid, userId,
15150                true /* requireFullPermission */, false /* checkShell */,
15151                "isPackageSuspendedForUser for user " + userId);
15152        synchronized (mPackages) {
15153            final PackageSetting ps = mSettings.mPackages.get(packageName);
15154            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15155                throw new IllegalArgumentException("Unknown target package: " + packageName);
15156            }
15157            return ps.getSuspended(userId);
15158        }
15159    }
15160
15161    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15162        if (isPackageDeviceAdmin(packageName, userId)) {
15163            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15164                    + "\": has an active device admin");
15165            return false;
15166        }
15167
15168        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15169        if (packageName.equals(activeLauncherPackageName)) {
15170            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15171                    + "\": contains the active launcher");
15172            return false;
15173        }
15174
15175        if (packageName.equals(mRequiredInstallerPackage)) {
15176            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15177                    + "\": required for package installation");
15178            return false;
15179        }
15180
15181        if (packageName.equals(mRequiredUninstallerPackage)) {
15182            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15183                    + "\": required for package uninstallation");
15184            return false;
15185        }
15186
15187        if (packageName.equals(mRequiredVerifierPackage)) {
15188            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15189                    + "\": required for package verification");
15190            return false;
15191        }
15192
15193        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15194            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15195                    + "\": is the default dialer");
15196            return false;
15197        }
15198
15199        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15200            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15201                    + "\": protected package");
15202            return false;
15203        }
15204
15205        // Cannot suspend static shared libs as they are considered
15206        // a part of the using app (emulating static linking). Also
15207        // static libs are installed always on internal storage.
15208        PackageParser.Package pkg = mPackages.get(packageName);
15209        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15210            Slog.w(TAG, "Cannot suspend package: " + packageName
15211                    + " providing static shared library: "
15212                    + pkg.staticSharedLibName);
15213            return false;
15214        }
15215
15216        return true;
15217    }
15218
15219    private String getActiveLauncherPackageName(int userId) {
15220        Intent intent = new Intent(Intent.ACTION_MAIN);
15221        intent.addCategory(Intent.CATEGORY_HOME);
15222        ResolveInfo resolveInfo = resolveIntent(
15223                intent,
15224                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15225                PackageManager.MATCH_DEFAULT_ONLY,
15226                userId);
15227
15228        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15229    }
15230
15231    private String getDefaultDialerPackageName(int userId) {
15232        synchronized (mPackages) {
15233            return mSettings.getDefaultDialerPackageNameLPw(userId);
15234        }
15235    }
15236
15237    @Override
15238    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15239        mContext.enforceCallingOrSelfPermission(
15240                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15241                "Only package verification agents can verify applications");
15242
15243        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15244        final PackageVerificationResponse response = new PackageVerificationResponse(
15245                verificationCode, Binder.getCallingUid());
15246        msg.arg1 = id;
15247        msg.obj = response;
15248        mHandler.sendMessage(msg);
15249    }
15250
15251    @Override
15252    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15253            long millisecondsToDelay) {
15254        mContext.enforceCallingOrSelfPermission(
15255                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15256                "Only package verification agents can extend verification timeouts");
15257
15258        final PackageVerificationState state = mPendingVerification.get(id);
15259        final PackageVerificationResponse response = new PackageVerificationResponse(
15260                verificationCodeAtTimeout, Binder.getCallingUid());
15261
15262        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15263            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15264        }
15265        if (millisecondsToDelay < 0) {
15266            millisecondsToDelay = 0;
15267        }
15268        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15269                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15270            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15271        }
15272
15273        if ((state != null) && !state.timeoutExtended()) {
15274            state.extendTimeout();
15275
15276            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15277            msg.arg1 = id;
15278            msg.obj = response;
15279            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15280        }
15281    }
15282
15283    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15284            int verificationCode, UserHandle user) {
15285        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15286        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15287        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15288        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15289        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15290
15291        mContext.sendBroadcastAsUser(intent, user,
15292                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15293    }
15294
15295    private ComponentName matchComponentForVerifier(String packageName,
15296            List<ResolveInfo> receivers) {
15297        ActivityInfo targetReceiver = null;
15298
15299        final int NR = receivers.size();
15300        for (int i = 0; i < NR; i++) {
15301            final ResolveInfo info = receivers.get(i);
15302            if (info.activityInfo == null) {
15303                continue;
15304            }
15305
15306            if (packageName.equals(info.activityInfo.packageName)) {
15307                targetReceiver = info.activityInfo;
15308                break;
15309            }
15310        }
15311
15312        if (targetReceiver == null) {
15313            return null;
15314        }
15315
15316        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15317    }
15318
15319    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15320            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15321        if (pkgInfo.verifiers.length == 0) {
15322            return null;
15323        }
15324
15325        final int N = pkgInfo.verifiers.length;
15326        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15327        for (int i = 0; i < N; i++) {
15328            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15329
15330            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15331                    receivers);
15332            if (comp == null) {
15333                continue;
15334            }
15335
15336            final int verifierUid = getUidForVerifier(verifierInfo);
15337            if (verifierUid == -1) {
15338                continue;
15339            }
15340
15341            if (DEBUG_VERIFY) {
15342                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15343                        + " with the correct signature");
15344            }
15345            sufficientVerifiers.add(comp);
15346            verificationState.addSufficientVerifier(verifierUid);
15347        }
15348
15349        return sufficientVerifiers;
15350    }
15351
15352    private int getUidForVerifier(VerifierInfo verifierInfo) {
15353        synchronized (mPackages) {
15354            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15355            if (pkg == null) {
15356                return -1;
15357            } else if (pkg.mSignatures.length != 1) {
15358                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15359                        + " has more than one signature; ignoring");
15360                return -1;
15361            }
15362
15363            /*
15364             * If the public key of the package's signature does not match
15365             * our expected public key, then this is a different package and
15366             * we should skip.
15367             */
15368
15369            final byte[] expectedPublicKey;
15370            try {
15371                final Signature verifierSig = pkg.mSignatures[0];
15372                final PublicKey publicKey = verifierSig.getPublicKey();
15373                expectedPublicKey = publicKey.getEncoded();
15374            } catch (CertificateException e) {
15375                return -1;
15376            }
15377
15378            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15379
15380            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15381                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15382                        + " does not have the expected public key; ignoring");
15383                return -1;
15384            }
15385
15386            return pkg.applicationInfo.uid;
15387        }
15388    }
15389
15390    @Override
15391    public void finishPackageInstall(int token, boolean didLaunch) {
15392        enforceSystemOrRoot("Only the system is allowed to finish installs");
15393
15394        if (DEBUG_INSTALL) {
15395            Slog.v(TAG, "BM finishing package install for " + token);
15396        }
15397        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15398
15399        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15400        mHandler.sendMessage(msg);
15401    }
15402
15403    /**
15404     * Get the verification agent timeout.  Used for both the APK verifier and the
15405     * intent filter verifier.
15406     *
15407     * @return verification timeout in milliseconds
15408     */
15409    private long getVerificationTimeout() {
15410        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15411                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15412                DEFAULT_VERIFICATION_TIMEOUT);
15413    }
15414
15415    /**
15416     * Get the default verification agent response code.
15417     *
15418     * @return default verification response code
15419     */
15420    private int getDefaultVerificationResponse(UserHandle user) {
15421        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15422            return PackageManager.VERIFICATION_REJECT;
15423        }
15424        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15425                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15426                DEFAULT_VERIFICATION_RESPONSE);
15427    }
15428
15429    /**
15430     * Check whether or not package verification has been enabled.
15431     *
15432     * @return true if verification should be performed
15433     */
15434    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15435        if (!DEFAULT_VERIFY_ENABLE) {
15436            return false;
15437        }
15438
15439        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15440
15441        // Check if installing from ADB
15442        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15443            // Do not run verification in a test harness environment
15444            if (ActivityManager.isRunningInTestHarness()) {
15445                return false;
15446            }
15447            if (ensureVerifyAppsEnabled) {
15448                return true;
15449            }
15450            // Check if the developer does not want package verification for ADB installs
15451            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15452                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15453                return false;
15454            }
15455        } else {
15456            // only when not installed from ADB, skip verification for instant apps when
15457            // the installer and verifier are the same.
15458            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15459                if (mInstantAppInstallerActivity != null
15460                        && mInstantAppInstallerActivity.packageName.equals(
15461                                mRequiredVerifierPackage)) {
15462                    try {
15463                        mContext.getSystemService(AppOpsManager.class)
15464                                .checkPackage(installerUid, mRequiredVerifierPackage);
15465                        if (DEBUG_VERIFY) {
15466                            Slog.i(TAG, "disable verification for instant app");
15467                        }
15468                        return false;
15469                    } catch (SecurityException ignore) { }
15470                }
15471            }
15472        }
15473
15474        if (ensureVerifyAppsEnabled) {
15475            return true;
15476        }
15477
15478        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15479                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15480    }
15481
15482    @Override
15483    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15484            throws RemoteException {
15485        mContext.enforceCallingOrSelfPermission(
15486                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15487                "Only intentfilter verification agents can verify applications");
15488
15489        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15490        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15491                Binder.getCallingUid(), verificationCode, failedDomains);
15492        msg.arg1 = id;
15493        msg.obj = response;
15494        mHandler.sendMessage(msg);
15495    }
15496
15497    @Override
15498    public int getIntentVerificationStatus(String packageName, int userId) {
15499        final int callingUid = Binder.getCallingUid();
15500        if (UserHandle.getUserId(callingUid) != userId) {
15501            mContext.enforceCallingOrSelfPermission(
15502                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15503                    "getIntentVerificationStatus" + userId);
15504        }
15505        if (getInstantAppPackageName(callingUid) != null) {
15506            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15507        }
15508        synchronized (mPackages) {
15509            final PackageSetting ps = mSettings.mPackages.get(packageName);
15510            if (ps == null
15511                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15512                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15513            }
15514            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15515        }
15516    }
15517
15518    @Override
15519    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15520        mContext.enforceCallingOrSelfPermission(
15521                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15522
15523        boolean result = false;
15524        synchronized (mPackages) {
15525            final PackageSetting ps = mSettings.mPackages.get(packageName);
15526            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15527                return false;
15528            }
15529            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15530        }
15531        if (result) {
15532            scheduleWritePackageRestrictionsLocked(userId);
15533        }
15534        return result;
15535    }
15536
15537    @Override
15538    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15539            String packageName) {
15540        final int callingUid = Binder.getCallingUid();
15541        if (getInstantAppPackageName(callingUid) != null) {
15542            return ParceledListSlice.emptyList();
15543        }
15544        synchronized (mPackages) {
15545            final PackageSetting ps = mSettings.mPackages.get(packageName);
15546            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15547                return ParceledListSlice.emptyList();
15548            }
15549            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15550        }
15551    }
15552
15553    @Override
15554    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15555        if (TextUtils.isEmpty(packageName)) {
15556            return ParceledListSlice.emptyList();
15557        }
15558        final int callingUid = Binder.getCallingUid();
15559        final int callingUserId = UserHandle.getUserId(callingUid);
15560        synchronized (mPackages) {
15561            PackageParser.Package pkg = mPackages.get(packageName);
15562            if (pkg == null || pkg.activities == null) {
15563                return ParceledListSlice.emptyList();
15564            }
15565            if (pkg.mExtras == null) {
15566                return ParceledListSlice.emptyList();
15567            }
15568            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15569            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15570                return ParceledListSlice.emptyList();
15571            }
15572            final int count = pkg.activities.size();
15573            ArrayList<IntentFilter> result = new ArrayList<>();
15574            for (int n=0; n<count; n++) {
15575                PackageParser.Activity activity = pkg.activities.get(n);
15576                if (activity.intents != null && activity.intents.size() > 0) {
15577                    result.addAll(activity.intents);
15578                }
15579            }
15580            return new ParceledListSlice<>(result);
15581        }
15582    }
15583
15584    @Override
15585    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15586        mContext.enforceCallingOrSelfPermission(
15587                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15588        if (UserHandle.getCallingUserId() != userId) {
15589            mContext.enforceCallingOrSelfPermission(
15590                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15591        }
15592
15593        synchronized (mPackages) {
15594            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15595            if (packageName != null) {
15596                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15597                        packageName, userId);
15598            }
15599            return result;
15600        }
15601    }
15602
15603    @Override
15604    public String getDefaultBrowserPackageName(int userId) {
15605        if (UserHandle.getCallingUserId() != userId) {
15606            mContext.enforceCallingOrSelfPermission(
15607                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15608        }
15609        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15610            return null;
15611        }
15612        synchronized (mPackages) {
15613            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15614        }
15615    }
15616
15617    /**
15618     * Get the "allow unknown sources" setting.
15619     *
15620     * @return the current "allow unknown sources" setting
15621     */
15622    private int getUnknownSourcesSettings() {
15623        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15624                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15625                -1);
15626    }
15627
15628    @Override
15629    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15630        final int callingUid = Binder.getCallingUid();
15631        if (getInstantAppPackageName(callingUid) != null) {
15632            return;
15633        }
15634        // writer
15635        synchronized (mPackages) {
15636            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15637            if (targetPackageSetting == null
15638                    || filterAppAccessLPr(
15639                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15640                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15641            }
15642
15643            PackageSetting installerPackageSetting;
15644            if (installerPackageName != null) {
15645                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15646                if (installerPackageSetting == null) {
15647                    throw new IllegalArgumentException("Unknown installer package: "
15648                            + installerPackageName);
15649                }
15650            } else {
15651                installerPackageSetting = null;
15652            }
15653
15654            Signature[] callerSignature;
15655            Object obj = mSettings.getUserIdLPr(callingUid);
15656            if (obj != null) {
15657                if (obj instanceof SharedUserSetting) {
15658                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15659                } else if (obj instanceof PackageSetting) {
15660                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15661                } else {
15662                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15663                }
15664            } else {
15665                throw new SecurityException("Unknown calling UID: " + callingUid);
15666            }
15667
15668            // Verify: can't set installerPackageName to a package that is
15669            // not signed with the same cert as the caller.
15670            if (installerPackageSetting != null) {
15671                if (compareSignatures(callerSignature,
15672                        installerPackageSetting.signatures.mSignatures)
15673                        != PackageManager.SIGNATURE_MATCH) {
15674                    throw new SecurityException(
15675                            "Caller does not have same cert as new installer package "
15676                            + installerPackageName);
15677                }
15678            }
15679
15680            // Verify: if target already has an installer package, it must
15681            // be signed with the same cert as the caller.
15682            if (targetPackageSetting.installerPackageName != null) {
15683                PackageSetting setting = mSettings.mPackages.get(
15684                        targetPackageSetting.installerPackageName);
15685                // If the currently set package isn't valid, then it's always
15686                // okay to change it.
15687                if (setting != null) {
15688                    if (compareSignatures(callerSignature,
15689                            setting.signatures.mSignatures)
15690                            != PackageManager.SIGNATURE_MATCH) {
15691                        throw new SecurityException(
15692                                "Caller does not have same cert as old installer package "
15693                                + targetPackageSetting.installerPackageName);
15694                    }
15695                }
15696            }
15697
15698            // Okay!
15699            targetPackageSetting.installerPackageName = installerPackageName;
15700            if (installerPackageName != null) {
15701                mSettings.mInstallerPackages.add(installerPackageName);
15702            }
15703            scheduleWriteSettingsLocked();
15704        }
15705    }
15706
15707    @Override
15708    public void setApplicationCategoryHint(String packageName, int categoryHint,
15709            String callerPackageName) {
15710        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15711            throw new SecurityException("Instant applications don't have access to this method");
15712        }
15713        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15714                callerPackageName);
15715        synchronized (mPackages) {
15716            PackageSetting ps = mSettings.mPackages.get(packageName);
15717            if (ps == null) {
15718                throw new IllegalArgumentException("Unknown target package " + packageName);
15719            }
15720            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15721                throw new IllegalArgumentException("Unknown target package " + packageName);
15722            }
15723            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15724                throw new IllegalArgumentException("Calling package " + callerPackageName
15725                        + " is not installer for " + packageName);
15726            }
15727
15728            if (ps.categoryHint != categoryHint) {
15729                ps.categoryHint = categoryHint;
15730                scheduleWriteSettingsLocked();
15731            }
15732        }
15733    }
15734
15735    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15736        // Queue up an async operation since the package installation may take a little while.
15737        mHandler.post(new Runnable() {
15738            public void run() {
15739                mHandler.removeCallbacks(this);
15740                 // Result object to be returned
15741                PackageInstalledInfo res = new PackageInstalledInfo();
15742                res.setReturnCode(currentStatus);
15743                res.uid = -1;
15744                res.pkg = null;
15745                res.removedInfo = null;
15746                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15747                    args.doPreInstall(res.returnCode);
15748                    synchronized (mInstallLock) {
15749                        installPackageTracedLI(args, res);
15750                    }
15751                    args.doPostInstall(res.returnCode, res.uid);
15752                }
15753
15754                // A restore should be performed at this point if (a) the install
15755                // succeeded, (b) the operation is not an update, and (c) the new
15756                // package has not opted out of backup participation.
15757                final boolean update = res.removedInfo != null
15758                        && res.removedInfo.removedPackage != null;
15759                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15760                boolean doRestore = !update
15761                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15762
15763                // Set up the post-install work request bookkeeping.  This will be used
15764                // and cleaned up by the post-install event handling regardless of whether
15765                // there's a restore pass performed.  Token values are >= 1.
15766                int token;
15767                if (mNextInstallToken < 0) mNextInstallToken = 1;
15768                token = mNextInstallToken++;
15769
15770                PostInstallData data = new PostInstallData(args, res);
15771                mRunningInstalls.put(token, data);
15772                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15773
15774                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15775                    // Pass responsibility to the Backup Manager.  It will perform a
15776                    // restore if appropriate, then pass responsibility back to the
15777                    // Package Manager to run the post-install observer callbacks
15778                    // and broadcasts.
15779                    IBackupManager bm = IBackupManager.Stub.asInterface(
15780                            ServiceManager.getService(Context.BACKUP_SERVICE));
15781                    if (bm != null) {
15782                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15783                                + " to BM for possible restore");
15784                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15785                        try {
15786                            // TODO: http://b/22388012
15787                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15788                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15789                            } else {
15790                                doRestore = false;
15791                            }
15792                        } catch (RemoteException e) {
15793                            // can't happen; the backup manager is local
15794                        } catch (Exception e) {
15795                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15796                            doRestore = false;
15797                        }
15798                    } else {
15799                        Slog.e(TAG, "Backup Manager not found!");
15800                        doRestore = false;
15801                    }
15802                }
15803
15804                if (!doRestore) {
15805                    // No restore possible, or the Backup Manager was mysteriously not
15806                    // available -- just fire the post-install work request directly.
15807                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15808
15809                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15810
15811                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15812                    mHandler.sendMessage(msg);
15813                }
15814            }
15815        });
15816    }
15817
15818    /**
15819     * Callback from PackageSettings whenever an app is first transitioned out of the
15820     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15821     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15822     * here whether the app is the target of an ongoing install, and only send the
15823     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15824     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15825     * handling.
15826     */
15827    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15828        // Serialize this with the rest of the install-process message chain.  In the
15829        // restore-at-install case, this Runnable will necessarily run before the
15830        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15831        // are coherent.  In the non-restore case, the app has already completed install
15832        // and been launched through some other means, so it is not in a problematic
15833        // state for observers to see the FIRST_LAUNCH signal.
15834        mHandler.post(new Runnable() {
15835            @Override
15836            public void run() {
15837                for (int i = 0; i < mRunningInstalls.size(); i++) {
15838                    final PostInstallData data = mRunningInstalls.valueAt(i);
15839                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15840                        continue;
15841                    }
15842                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15843                        // right package; but is it for the right user?
15844                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15845                            if (userId == data.res.newUsers[uIndex]) {
15846                                if (DEBUG_BACKUP) {
15847                                    Slog.i(TAG, "Package " + pkgName
15848                                            + " being restored so deferring FIRST_LAUNCH");
15849                                }
15850                                return;
15851                            }
15852                        }
15853                    }
15854                }
15855                // didn't find it, so not being restored
15856                if (DEBUG_BACKUP) {
15857                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15858                }
15859                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15860            }
15861        });
15862    }
15863
15864    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15865        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15866                installerPkg, null, userIds);
15867    }
15868
15869    private abstract class HandlerParams {
15870        private static final int MAX_RETRIES = 4;
15871
15872        /**
15873         * Number of times startCopy() has been attempted and had a non-fatal
15874         * error.
15875         */
15876        private int mRetries = 0;
15877
15878        /** User handle for the user requesting the information or installation. */
15879        private final UserHandle mUser;
15880        String traceMethod;
15881        int traceCookie;
15882
15883        HandlerParams(UserHandle user) {
15884            mUser = user;
15885        }
15886
15887        UserHandle getUser() {
15888            return mUser;
15889        }
15890
15891        HandlerParams setTraceMethod(String traceMethod) {
15892            this.traceMethod = traceMethod;
15893            return this;
15894        }
15895
15896        HandlerParams setTraceCookie(int traceCookie) {
15897            this.traceCookie = traceCookie;
15898            return this;
15899        }
15900
15901        final boolean startCopy() {
15902            boolean res;
15903            try {
15904                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15905
15906                if (++mRetries > MAX_RETRIES) {
15907                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15908                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15909                    handleServiceError();
15910                    return false;
15911                } else {
15912                    handleStartCopy();
15913                    res = true;
15914                }
15915            } catch (RemoteException e) {
15916                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15917                mHandler.sendEmptyMessage(MCS_RECONNECT);
15918                res = false;
15919            }
15920            handleReturnCode();
15921            return res;
15922        }
15923
15924        final void serviceError() {
15925            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15926            handleServiceError();
15927            handleReturnCode();
15928        }
15929
15930        abstract void handleStartCopy() throws RemoteException;
15931        abstract void handleServiceError();
15932        abstract void handleReturnCode();
15933    }
15934
15935    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15936        for (File path : paths) {
15937            try {
15938                mcs.clearDirectory(path.getAbsolutePath());
15939            } catch (RemoteException e) {
15940            }
15941        }
15942    }
15943
15944    static class OriginInfo {
15945        /**
15946         * Location where install is coming from, before it has been
15947         * copied/renamed into place. This could be a single monolithic APK
15948         * file, or a cluster directory. This location may be untrusted.
15949         */
15950        final File file;
15951        final String cid;
15952
15953        /**
15954         * Flag indicating that {@link #file} or {@link #cid} has already been
15955         * staged, meaning downstream users don't need to defensively copy the
15956         * contents.
15957         */
15958        final boolean staged;
15959
15960        /**
15961         * Flag indicating that {@link #file} or {@link #cid} is an already
15962         * installed app that is being moved.
15963         */
15964        final boolean existing;
15965
15966        final String resolvedPath;
15967        final File resolvedFile;
15968
15969        static OriginInfo fromNothing() {
15970            return new OriginInfo(null, null, false, false);
15971        }
15972
15973        static OriginInfo fromUntrustedFile(File file) {
15974            return new OriginInfo(file, null, false, false);
15975        }
15976
15977        static OriginInfo fromExistingFile(File file) {
15978            return new OriginInfo(file, null, false, true);
15979        }
15980
15981        static OriginInfo fromStagedFile(File file) {
15982            return new OriginInfo(file, null, true, false);
15983        }
15984
15985        static OriginInfo fromStagedContainer(String cid) {
15986            return new OriginInfo(null, cid, true, false);
15987        }
15988
15989        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15990            this.file = file;
15991            this.cid = cid;
15992            this.staged = staged;
15993            this.existing = existing;
15994
15995            if (cid != null) {
15996                resolvedPath = PackageHelper.getSdDir(cid);
15997                resolvedFile = new File(resolvedPath);
15998            } else if (file != null) {
15999                resolvedPath = file.getAbsolutePath();
16000                resolvedFile = file;
16001            } else {
16002                resolvedPath = null;
16003                resolvedFile = null;
16004            }
16005        }
16006    }
16007
16008    static class MoveInfo {
16009        final int moveId;
16010        final String fromUuid;
16011        final String toUuid;
16012        final String packageName;
16013        final String dataAppName;
16014        final int appId;
16015        final String seinfo;
16016        final int targetSdkVersion;
16017
16018        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16019                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16020            this.moveId = moveId;
16021            this.fromUuid = fromUuid;
16022            this.toUuid = toUuid;
16023            this.packageName = packageName;
16024            this.dataAppName = dataAppName;
16025            this.appId = appId;
16026            this.seinfo = seinfo;
16027            this.targetSdkVersion = targetSdkVersion;
16028        }
16029    }
16030
16031    static class VerificationInfo {
16032        /** A constant used to indicate that a uid value is not present. */
16033        public static final int NO_UID = -1;
16034
16035        /** URI referencing where the package was downloaded from. */
16036        final Uri originatingUri;
16037
16038        /** HTTP referrer URI associated with the originatingURI. */
16039        final Uri referrer;
16040
16041        /** UID of the application that the install request originated from. */
16042        final int originatingUid;
16043
16044        /** UID of application requesting the install */
16045        final int installerUid;
16046
16047        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16048            this.originatingUri = originatingUri;
16049            this.referrer = referrer;
16050            this.originatingUid = originatingUid;
16051            this.installerUid = installerUid;
16052        }
16053    }
16054
16055    class InstallParams extends HandlerParams {
16056        final OriginInfo origin;
16057        final MoveInfo move;
16058        final IPackageInstallObserver2 observer;
16059        int installFlags;
16060        final String installerPackageName;
16061        final String volumeUuid;
16062        private InstallArgs mArgs;
16063        private int mRet;
16064        final String packageAbiOverride;
16065        final String[] grantedRuntimePermissions;
16066        final VerificationInfo verificationInfo;
16067        final Certificate[][] certificates;
16068        final int installReason;
16069
16070        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16071                int installFlags, String installerPackageName, String volumeUuid,
16072                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16073                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16074            super(user);
16075            this.origin = origin;
16076            this.move = move;
16077            this.observer = observer;
16078            this.installFlags = installFlags;
16079            this.installerPackageName = installerPackageName;
16080            this.volumeUuid = volumeUuid;
16081            this.verificationInfo = verificationInfo;
16082            this.packageAbiOverride = packageAbiOverride;
16083            this.grantedRuntimePermissions = grantedPermissions;
16084            this.certificates = certificates;
16085            this.installReason = installReason;
16086        }
16087
16088        @Override
16089        public String toString() {
16090            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16091                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16092        }
16093
16094        private int installLocationPolicy(PackageInfoLite pkgLite) {
16095            String packageName = pkgLite.packageName;
16096            int installLocation = pkgLite.installLocation;
16097            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16098            // reader
16099            synchronized (mPackages) {
16100                // Currently installed package which the new package is attempting to replace or
16101                // null if no such package is installed.
16102                PackageParser.Package installedPkg = mPackages.get(packageName);
16103                // Package which currently owns the data which the new package will own if installed.
16104                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16105                // will be null whereas dataOwnerPkg will contain information about the package
16106                // which was uninstalled while keeping its data.
16107                PackageParser.Package dataOwnerPkg = installedPkg;
16108                if (dataOwnerPkg  == null) {
16109                    PackageSetting ps = mSettings.mPackages.get(packageName);
16110                    if (ps != null) {
16111                        dataOwnerPkg = ps.pkg;
16112                    }
16113                }
16114
16115                if (dataOwnerPkg != null) {
16116                    // If installed, the package will get access to data left on the device by its
16117                    // predecessor. As a security measure, this is permited only if this is not a
16118                    // version downgrade or if the predecessor package is marked as debuggable and
16119                    // a downgrade is explicitly requested.
16120                    //
16121                    // On debuggable platform builds, downgrades are permitted even for
16122                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16123                    // not offer security guarantees and thus it's OK to disable some security
16124                    // mechanisms to make debugging/testing easier on those builds. However, even on
16125                    // debuggable builds downgrades of packages are permitted only if requested via
16126                    // installFlags. This is because we aim to keep the behavior of debuggable
16127                    // platform builds as close as possible to the behavior of non-debuggable
16128                    // platform builds.
16129                    final boolean downgradeRequested =
16130                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16131                    final boolean packageDebuggable =
16132                                (dataOwnerPkg.applicationInfo.flags
16133                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16134                    final boolean downgradePermitted =
16135                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16136                    if (!downgradePermitted) {
16137                        try {
16138                            checkDowngrade(dataOwnerPkg, pkgLite);
16139                        } catch (PackageManagerException e) {
16140                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16141                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16142                        }
16143                    }
16144                }
16145
16146                if (installedPkg != null) {
16147                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16148                        // Check for updated system application.
16149                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16150                            if (onSd) {
16151                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16152                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16153                            }
16154                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16155                        } else {
16156                            if (onSd) {
16157                                // Install flag overrides everything.
16158                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16159                            }
16160                            // If current upgrade specifies particular preference
16161                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16162                                // Application explicitly specified internal.
16163                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16164                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16165                                // App explictly prefers external. Let policy decide
16166                            } else {
16167                                // Prefer previous location
16168                                if (isExternal(installedPkg)) {
16169                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16170                                }
16171                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16172                            }
16173                        }
16174                    } else {
16175                        // Invalid install. Return error code
16176                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16177                    }
16178                }
16179            }
16180            // All the special cases have been taken care of.
16181            // Return result based on recommended install location.
16182            if (onSd) {
16183                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16184            }
16185            return pkgLite.recommendedInstallLocation;
16186        }
16187
16188        /*
16189         * Invoke remote method to get package information and install
16190         * location values. Override install location based on default
16191         * policy if needed and then create install arguments based
16192         * on the install location.
16193         */
16194        public void handleStartCopy() throws RemoteException {
16195            int ret = PackageManager.INSTALL_SUCCEEDED;
16196
16197            // If we're already staged, we've firmly committed to an install location
16198            if (origin.staged) {
16199                if (origin.file != null) {
16200                    installFlags |= PackageManager.INSTALL_INTERNAL;
16201                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16202                } else if (origin.cid != null) {
16203                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16204                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16205                } else {
16206                    throw new IllegalStateException("Invalid stage location");
16207                }
16208            }
16209
16210            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16211            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16212            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16213            PackageInfoLite pkgLite = null;
16214
16215            if (onInt && onSd) {
16216                // Check if both bits are set.
16217                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16218                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16219            } else if (onSd && ephemeral) {
16220                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16221                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16222            } else {
16223                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16224                        packageAbiOverride);
16225
16226                if (DEBUG_EPHEMERAL && ephemeral) {
16227                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16228                }
16229
16230                /*
16231                 * If we have too little free space, try to free cache
16232                 * before giving up.
16233                 */
16234                if (!origin.staged && pkgLite.recommendedInstallLocation
16235                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16236                    // TODO: focus freeing disk space on the target device
16237                    final StorageManager storage = StorageManager.from(mContext);
16238                    final long lowThreshold = storage.getStorageLowBytes(
16239                            Environment.getDataDirectory());
16240
16241                    final long sizeBytes = mContainerService.calculateInstalledSize(
16242                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16243
16244                    try {
16245                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16246                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16247                                installFlags, packageAbiOverride);
16248                    } catch (InstallerException e) {
16249                        Slog.w(TAG, "Failed to free cache", e);
16250                    }
16251
16252                    /*
16253                     * The cache free must have deleted the file we
16254                     * downloaded to install.
16255                     *
16256                     * TODO: fix the "freeCache" call to not delete
16257                     *       the file we care about.
16258                     */
16259                    if (pkgLite.recommendedInstallLocation
16260                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16261                        pkgLite.recommendedInstallLocation
16262                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16263                    }
16264                }
16265            }
16266
16267            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16268                int loc = pkgLite.recommendedInstallLocation;
16269                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16270                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16271                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16272                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16273                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16274                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16275                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16276                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16277                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16278                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16279                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16280                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16281                } else {
16282                    // Override with defaults if needed.
16283                    loc = installLocationPolicy(pkgLite);
16284                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16285                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16286                    } else if (!onSd && !onInt) {
16287                        // Override install location with flags
16288                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16289                            // Set the flag to install on external media.
16290                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16291                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16292                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16293                            if (DEBUG_EPHEMERAL) {
16294                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16295                            }
16296                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16297                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16298                                    |PackageManager.INSTALL_INTERNAL);
16299                        } else {
16300                            // Make sure the flag for installing on external
16301                            // media is unset
16302                            installFlags |= PackageManager.INSTALL_INTERNAL;
16303                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16304                        }
16305                    }
16306                }
16307            }
16308
16309            final InstallArgs args = createInstallArgs(this);
16310            mArgs = args;
16311
16312            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16313                // TODO: http://b/22976637
16314                // Apps installed for "all" users use the device owner to verify the app
16315                UserHandle verifierUser = getUser();
16316                if (verifierUser == UserHandle.ALL) {
16317                    verifierUser = UserHandle.SYSTEM;
16318                }
16319
16320                /*
16321                 * Determine if we have any installed package verifiers. If we
16322                 * do, then we'll defer to them to verify the packages.
16323                 */
16324                final int requiredUid = mRequiredVerifierPackage == null ? -1
16325                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16326                                verifierUser.getIdentifier());
16327                final int installerUid =
16328                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16329                if (!origin.existing && requiredUid != -1
16330                        && isVerificationEnabled(
16331                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16332                    final Intent verification = new Intent(
16333                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16334                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16335                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16336                            PACKAGE_MIME_TYPE);
16337                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16338
16339                    // Query all live verifiers based on current user state
16340                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16341                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16342                            false /*allowDynamicSplits*/);
16343
16344                    if (DEBUG_VERIFY) {
16345                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16346                                + verification.toString() + " with " + pkgLite.verifiers.length
16347                                + " optional verifiers");
16348                    }
16349
16350                    final int verificationId = mPendingVerificationToken++;
16351
16352                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16353
16354                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16355                            installerPackageName);
16356
16357                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16358                            installFlags);
16359
16360                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16361                            pkgLite.packageName);
16362
16363                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16364                            pkgLite.versionCode);
16365
16366                    if (verificationInfo != null) {
16367                        if (verificationInfo.originatingUri != null) {
16368                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16369                                    verificationInfo.originatingUri);
16370                        }
16371                        if (verificationInfo.referrer != null) {
16372                            verification.putExtra(Intent.EXTRA_REFERRER,
16373                                    verificationInfo.referrer);
16374                        }
16375                        if (verificationInfo.originatingUid >= 0) {
16376                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16377                                    verificationInfo.originatingUid);
16378                        }
16379                        if (verificationInfo.installerUid >= 0) {
16380                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16381                                    verificationInfo.installerUid);
16382                        }
16383                    }
16384
16385                    final PackageVerificationState verificationState = new PackageVerificationState(
16386                            requiredUid, args);
16387
16388                    mPendingVerification.append(verificationId, verificationState);
16389
16390                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16391                            receivers, verificationState);
16392
16393                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16394                    final long idleDuration = getVerificationTimeout();
16395
16396                    /*
16397                     * If any sufficient verifiers were listed in the package
16398                     * manifest, attempt to ask them.
16399                     */
16400                    if (sufficientVerifiers != null) {
16401                        final int N = sufficientVerifiers.size();
16402                        if (N == 0) {
16403                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16404                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16405                        } else {
16406                            for (int i = 0; i < N; i++) {
16407                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16408                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16409                                        verifierComponent.getPackageName(), idleDuration,
16410                                        verifierUser.getIdentifier(), false, "package verifier");
16411
16412                                final Intent sufficientIntent = new Intent(verification);
16413                                sufficientIntent.setComponent(verifierComponent);
16414                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16415                            }
16416                        }
16417                    }
16418
16419                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16420                            mRequiredVerifierPackage, receivers);
16421                    if (ret == PackageManager.INSTALL_SUCCEEDED
16422                            && mRequiredVerifierPackage != null) {
16423                        Trace.asyncTraceBegin(
16424                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16425                        /*
16426                         * Send the intent to the required verification agent,
16427                         * but only start the verification timeout after the
16428                         * target BroadcastReceivers have run.
16429                         */
16430                        verification.setComponent(requiredVerifierComponent);
16431                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16432                                mRequiredVerifierPackage, idleDuration,
16433                                verifierUser.getIdentifier(), false, "package verifier");
16434                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16435                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16436                                new BroadcastReceiver() {
16437                                    @Override
16438                                    public void onReceive(Context context, Intent intent) {
16439                                        final Message msg = mHandler
16440                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16441                                        msg.arg1 = verificationId;
16442                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16443                                    }
16444                                }, null, 0, null, null);
16445
16446                        /*
16447                         * We don't want the copy to proceed until verification
16448                         * succeeds, so null out this field.
16449                         */
16450                        mArgs = null;
16451                    }
16452                } else {
16453                    /*
16454                     * No package verification is enabled, so immediately start
16455                     * the remote call to initiate copy using temporary file.
16456                     */
16457                    ret = args.copyApk(mContainerService, true);
16458                }
16459            }
16460
16461            mRet = ret;
16462        }
16463
16464        @Override
16465        void handleReturnCode() {
16466            // If mArgs is null, then MCS couldn't be reached. When it
16467            // reconnects, it will try again to install. At that point, this
16468            // will succeed.
16469            if (mArgs != null) {
16470                processPendingInstall(mArgs, mRet);
16471            }
16472        }
16473
16474        @Override
16475        void handleServiceError() {
16476            mArgs = createInstallArgs(this);
16477            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16478        }
16479
16480        public boolean isForwardLocked() {
16481            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16482        }
16483    }
16484
16485    /**
16486     * Used during creation of InstallArgs
16487     *
16488     * @param installFlags package installation flags
16489     * @return true if should be installed on external storage
16490     */
16491    private static boolean installOnExternalAsec(int installFlags) {
16492        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16493            return false;
16494        }
16495        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16496            return true;
16497        }
16498        return false;
16499    }
16500
16501    /**
16502     * Used during creation of InstallArgs
16503     *
16504     * @param installFlags package installation flags
16505     * @return true if should be installed as forward locked
16506     */
16507    private static boolean installForwardLocked(int installFlags) {
16508        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16509    }
16510
16511    private InstallArgs createInstallArgs(InstallParams params) {
16512        if (params.move != null) {
16513            return new MoveInstallArgs(params);
16514        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16515            return new AsecInstallArgs(params);
16516        } else {
16517            return new FileInstallArgs(params);
16518        }
16519    }
16520
16521    /**
16522     * Create args that describe an existing installed package. Typically used
16523     * when cleaning up old installs, or used as a move source.
16524     */
16525    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16526            String resourcePath, String[] instructionSets) {
16527        final boolean isInAsec;
16528        if (installOnExternalAsec(installFlags)) {
16529            /* Apps on SD card are always in ASEC containers. */
16530            isInAsec = true;
16531        } else if (installForwardLocked(installFlags)
16532                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16533            /*
16534             * Forward-locked apps are only in ASEC containers if they're the
16535             * new style
16536             */
16537            isInAsec = true;
16538        } else {
16539            isInAsec = false;
16540        }
16541
16542        if (isInAsec) {
16543            return new AsecInstallArgs(codePath, instructionSets,
16544                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16545        } else {
16546            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16547        }
16548    }
16549
16550    static abstract class InstallArgs {
16551        /** @see InstallParams#origin */
16552        final OriginInfo origin;
16553        /** @see InstallParams#move */
16554        final MoveInfo move;
16555
16556        final IPackageInstallObserver2 observer;
16557        // Always refers to PackageManager flags only
16558        final int installFlags;
16559        final String installerPackageName;
16560        final String volumeUuid;
16561        final UserHandle user;
16562        final String abiOverride;
16563        final String[] installGrantPermissions;
16564        /** If non-null, drop an async trace when the install completes */
16565        final String traceMethod;
16566        final int traceCookie;
16567        final Certificate[][] certificates;
16568        final int installReason;
16569
16570        // The list of instruction sets supported by this app. This is currently
16571        // only used during the rmdex() phase to clean up resources. We can get rid of this
16572        // if we move dex files under the common app path.
16573        /* nullable */ String[] instructionSets;
16574
16575        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16576                int installFlags, String installerPackageName, String volumeUuid,
16577                UserHandle user, String[] instructionSets,
16578                String abiOverride, String[] installGrantPermissions,
16579                String traceMethod, int traceCookie, Certificate[][] certificates,
16580                int installReason) {
16581            this.origin = origin;
16582            this.move = move;
16583            this.installFlags = installFlags;
16584            this.observer = observer;
16585            this.installerPackageName = installerPackageName;
16586            this.volumeUuid = volumeUuid;
16587            this.user = user;
16588            this.instructionSets = instructionSets;
16589            this.abiOverride = abiOverride;
16590            this.installGrantPermissions = installGrantPermissions;
16591            this.traceMethod = traceMethod;
16592            this.traceCookie = traceCookie;
16593            this.certificates = certificates;
16594            this.installReason = installReason;
16595        }
16596
16597        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16598        abstract int doPreInstall(int status);
16599
16600        /**
16601         * Rename package into final resting place. All paths on the given
16602         * scanned package should be updated to reflect the rename.
16603         */
16604        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16605        abstract int doPostInstall(int status, int uid);
16606
16607        /** @see PackageSettingBase#codePathString */
16608        abstract String getCodePath();
16609        /** @see PackageSettingBase#resourcePathString */
16610        abstract String getResourcePath();
16611
16612        // Need installer lock especially for dex file removal.
16613        abstract void cleanUpResourcesLI();
16614        abstract boolean doPostDeleteLI(boolean delete);
16615
16616        /**
16617         * Called before the source arguments are copied. This is used mostly
16618         * for MoveParams when it needs to read the source file to put it in the
16619         * destination.
16620         */
16621        int doPreCopy() {
16622            return PackageManager.INSTALL_SUCCEEDED;
16623        }
16624
16625        /**
16626         * Called after the source arguments are copied. This is used mostly for
16627         * MoveParams when it needs to read the source file to put it in the
16628         * destination.
16629         */
16630        int doPostCopy(int uid) {
16631            return PackageManager.INSTALL_SUCCEEDED;
16632        }
16633
16634        protected boolean isFwdLocked() {
16635            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16636        }
16637
16638        protected boolean isExternalAsec() {
16639            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16640        }
16641
16642        protected boolean isEphemeral() {
16643            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16644        }
16645
16646        UserHandle getUser() {
16647            return user;
16648        }
16649    }
16650
16651    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16652        if (!allCodePaths.isEmpty()) {
16653            if (instructionSets == null) {
16654                throw new IllegalStateException("instructionSet == null");
16655            }
16656            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16657            for (String codePath : allCodePaths) {
16658                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16659                    try {
16660                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16661                    } catch (InstallerException ignored) {
16662                    }
16663                }
16664            }
16665        }
16666    }
16667
16668    /**
16669     * Logic to handle installation of non-ASEC applications, including copying
16670     * and renaming logic.
16671     */
16672    class FileInstallArgs extends InstallArgs {
16673        private File codeFile;
16674        private File resourceFile;
16675
16676        // Example topology:
16677        // /data/app/com.example/base.apk
16678        // /data/app/com.example/split_foo.apk
16679        // /data/app/com.example/lib/arm/libfoo.so
16680        // /data/app/com.example/lib/arm64/libfoo.so
16681        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16682
16683        /** New install */
16684        FileInstallArgs(InstallParams params) {
16685            super(params.origin, params.move, params.observer, params.installFlags,
16686                    params.installerPackageName, params.volumeUuid,
16687                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16688                    params.grantedRuntimePermissions,
16689                    params.traceMethod, params.traceCookie, params.certificates,
16690                    params.installReason);
16691            if (isFwdLocked()) {
16692                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16693            }
16694        }
16695
16696        /** Existing install */
16697        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16698            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16699                    null, null, null, 0, null /*certificates*/,
16700                    PackageManager.INSTALL_REASON_UNKNOWN);
16701            this.codeFile = (codePath != null) ? new File(codePath) : null;
16702            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16703        }
16704
16705        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16706            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16707            try {
16708                return doCopyApk(imcs, temp);
16709            } finally {
16710                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16711            }
16712        }
16713
16714        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16715            if (origin.staged) {
16716                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16717                codeFile = origin.file;
16718                resourceFile = origin.file;
16719                return PackageManager.INSTALL_SUCCEEDED;
16720            }
16721
16722            try {
16723                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16724                final File tempDir =
16725                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16726                codeFile = tempDir;
16727                resourceFile = tempDir;
16728            } catch (IOException e) {
16729                Slog.w(TAG, "Failed to create copy file: " + e);
16730                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16731            }
16732
16733            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16734                @Override
16735                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16736                    if (!FileUtils.isValidExtFilename(name)) {
16737                        throw new IllegalArgumentException("Invalid filename: " + name);
16738                    }
16739                    try {
16740                        final File file = new File(codeFile, name);
16741                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16742                                O_RDWR | O_CREAT, 0644);
16743                        Os.chmod(file.getAbsolutePath(), 0644);
16744                        return new ParcelFileDescriptor(fd);
16745                    } catch (ErrnoException e) {
16746                        throw new RemoteException("Failed to open: " + e.getMessage());
16747                    }
16748                }
16749            };
16750
16751            int ret = PackageManager.INSTALL_SUCCEEDED;
16752            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16753            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16754                Slog.e(TAG, "Failed to copy package");
16755                return ret;
16756            }
16757
16758            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16759            NativeLibraryHelper.Handle handle = null;
16760            try {
16761                handle = NativeLibraryHelper.Handle.create(codeFile);
16762                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16763                        abiOverride);
16764            } catch (IOException e) {
16765                Slog.e(TAG, "Copying native libraries failed", e);
16766                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16767            } finally {
16768                IoUtils.closeQuietly(handle);
16769            }
16770
16771            return ret;
16772        }
16773
16774        int doPreInstall(int status) {
16775            if (status != PackageManager.INSTALL_SUCCEEDED) {
16776                cleanUp();
16777            }
16778            return status;
16779        }
16780
16781        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16782            if (status != PackageManager.INSTALL_SUCCEEDED) {
16783                cleanUp();
16784                return false;
16785            }
16786
16787            final File targetDir = codeFile.getParentFile();
16788            final File beforeCodeFile = codeFile;
16789            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16790
16791            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16792            try {
16793                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16794            } catch (ErrnoException e) {
16795                Slog.w(TAG, "Failed to rename", e);
16796                return false;
16797            }
16798
16799            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16800                Slog.w(TAG, "Failed to restorecon");
16801                return false;
16802            }
16803
16804            // Reflect the rename internally
16805            codeFile = afterCodeFile;
16806            resourceFile = afterCodeFile;
16807
16808            // Reflect the rename in scanned details
16809            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16810            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16811                    afterCodeFile, pkg.baseCodePath));
16812            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16813                    afterCodeFile, pkg.splitCodePaths));
16814
16815            // Reflect the rename in app info
16816            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16817            pkg.setApplicationInfoCodePath(pkg.codePath);
16818            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16819            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16820            pkg.setApplicationInfoResourcePath(pkg.codePath);
16821            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16822            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16823
16824            return true;
16825        }
16826
16827        int doPostInstall(int status, int uid) {
16828            if (status != PackageManager.INSTALL_SUCCEEDED) {
16829                cleanUp();
16830            }
16831            return status;
16832        }
16833
16834        @Override
16835        String getCodePath() {
16836            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16837        }
16838
16839        @Override
16840        String getResourcePath() {
16841            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16842        }
16843
16844        private boolean cleanUp() {
16845            if (codeFile == null || !codeFile.exists()) {
16846                return false;
16847            }
16848
16849            removeCodePathLI(codeFile);
16850
16851            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16852                resourceFile.delete();
16853            }
16854
16855            return true;
16856        }
16857
16858        void cleanUpResourcesLI() {
16859            // Try enumerating all code paths before deleting
16860            List<String> allCodePaths = Collections.EMPTY_LIST;
16861            if (codeFile != null && codeFile.exists()) {
16862                try {
16863                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16864                    allCodePaths = pkg.getAllCodePaths();
16865                } catch (PackageParserException e) {
16866                    // Ignored; we tried our best
16867                }
16868            }
16869
16870            cleanUp();
16871            removeDexFiles(allCodePaths, instructionSets);
16872        }
16873
16874        boolean doPostDeleteLI(boolean delete) {
16875            // XXX err, shouldn't we respect the delete flag?
16876            cleanUpResourcesLI();
16877            return true;
16878        }
16879    }
16880
16881    private boolean isAsecExternal(String cid) {
16882        final String asecPath = PackageHelper.getSdFilesystem(cid);
16883        return !asecPath.startsWith(mAsecInternalPath);
16884    }
16885
16886    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16887            PackageManagerException {
16888        if (copyRet < 0) {
16889            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16890                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16891                throw new PackageManagerException(copyRet, message);
16892            }
16893        }
16894    }
16895
16896    /**
16897     * Extract the StorageManagerService "container ID" from the full code path of an
16898     * .apk.
16899     */
16900    static String cidFromCodePath(String fullCodePath) {
16901        int eidx = fullCodePath.lastIndexOf("/");
16902        String subStr1 = fullCodePath.substring(0, eidx);
16903        int sidx = subStr1.lastIndexOf("/");
16904        return subStr1.substring(sidx+1, eidx);
16905    }
16906
16907    /**
16908     * Logic to handle installation of ASEC applications, including copying and
16909     * renaming logic.
16910     */
16911    class AsecInstallArgs extends InstallArgs {
16912        static final String RES_FILE_NAME = "pkg.apk";
16913        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16914
16915        String cid;
16916        String packagePath;
16917        String resourcePath;
16918
16919        /** New install */
16920        AsecInstallArgs(InstallParams params) {
16921            super(params.origin, params.move, params.observer, params.installFlags,
16922                    params.installerPackageName, params.volumeUuid,
16923                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16924                    params.grantedRuntimePermissions,
16925                    params.traceMethod, params.traceCookie, params.certificates,
16926                    params.installReason);
16927        }
16928
16929        /** Existing install */
16930        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16931                        boolean isExternal, boolean isForwardLocked) {
16932            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16933                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16934                    instructionSets, null, null, null, 0, null /*certificates*/,
16935                    PackageManager.INSTALL_REASON_UNKNOWN);
16936            // Hackily pretend we're still looking at a full code path
16937            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16938                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16939            }
16940
16941            // Extract cid from fullCodePath
16942            int eidx = fullCodePath.lastIndexOf("/");
16943            String subStr1 = fullCodePath.substring(0, eidx);
16944            int sidx = subStr1.lastIndexOf("/");
16945            cid = subStr1.substring(sidx+1, eidx);
16946            setMountPath(subStr1);
16947        }
16948
16949        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16950            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16951                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16952                    instructionSets, null, null, null, 0, null /*certificates*/,
16953                    PackageManager.INSTALL_REASON_UNKNOWN);
16954            this.cid = cid;
16955            setMountPath(PackageHelper.getSdDir(cid));
16956        }
16957
16958        void createCopyFile() {
16959            cid = mInstallerService.allocateExternalStageCidLegacy();
16960        }
16961
16962        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16963            if (origin.staged && origin.cid != null) {
16964                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16965                cid = origin.cid;
16966                setMountPath(PackageHelper.getSdDir(cid));
16967                return PackageManager.INSTALL_SUCCEEDED;
16968            }
16969
16970            if (temp) {
16971                createCopyFile();
16972            } else {
16973                /*
16974                 * Pre-emptively destroy the container since it's destroyed if
16975                 * copying fails due to it existing anyway.
16976                 */
16977                PackageHelper.destroySdDir(cid);
16978            }
16979
16980            final String newMountPath = imcs.copyPackageToContainer(
16981                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16982                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16983
16984            if (newMountPath != null) {
16985                setMountPath(newMountPath);
16986                return PackageManager.INSTALL_SUCCEEDED;
16987            } else {
16988                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16989            }
16990        }
16991
16992        @Override
16993        String getCodePath() {
16994            return packagePath;
16995        }
16996
16997        @Override
16998        String getResourcePath() {
16999            return resourcePath;
17000        }
17001
17002        int doPreInstall(int status) {
17003            if (status != PackageManager.INSTALL_SUCCEEDED) {
17004                // Destroy container
17005                PackageHelper.destroySdDir(cid);
17006            } else {
17007                boolean mounted = PackageHelper.isContainerMounted(cid);
17008                if (!mounted) {
17009                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17010                            Process.SYSTEM_UID);
17011                    if (newMountPath != null) {
17012                        setMountPath(newMountPath);
17013                    } else {
17014                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17015                    }
17016                }
17017            }
17018            return status;
17019        }
17020
17021        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17022            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17023            String newMountPath = null;
17024            if (PackageHelper.isContainerMounted(cid)) {
17025                // Unmount the container
17026                if (!PackageHelper.unMountSdDir(cid)) {
17027                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17028                    return false;
17029                }
17030            }
17031            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17032                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17033                        " which might be stale. Will try to clean up.");
17034                // Clean up the stale container and proceed to recreate.
17035                if (!PackageHelper.destroySdDir(newCacheId)) {
17036                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17037                    return false;
17038                }
17039                // Successfully cleaned up stale container. Try to rename again.
17040                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17041                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17042                            + " inspite of cleaning it up.");
17043                    return false;
17044                }
17045            }
17046            if (!PackageHelper.isContainerMounted(newCacheId)) {
17047                Slog.w(TAG, "Mounting container " + newCacheId);
17048                newMountPath = PackageHelper.mountSdDir(newCacheId,
17049                        getEncryptKey(), Process.SYSTEM_UID);
17050            } else {
17051                newMountPath = PackageHelper.getSdDir(newCacheId);
17052            }
17053            if (newMountPath == null) {
17054                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17055                return false;
17056            }
17057            Log.i(TAG, "Succesfully renamed " + cid +
17058                    " to " + newCacheId +
17059                    " at new path: " + newMountPath);
17060            cid = newCacheId;
17061
17062            final File beforeCodeFile = new File(packagePath);
17063            setMountPath(newMountPath);
17064            final File afterCodeFile = new File(packagePath);
17065
17066            // Reflect the rename in scanned details
17067            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17068            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17069                    afterCodeFile, pkg.baseCodePath));
17070            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17071                    afterCodeFile, pkg.splitCodePaths));
17072
17073            // Reflect the rename in app info
17074            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17075            pkg.setApplicationInfoCodePath(pkg.codePath);
17076            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17077            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17078            pkg.setApplicationInfoResourcePath(pkg.codePath);
17079            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17080            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17081
17082            return true;
17083        }
17084
17085        private void setMountPath(String mountPath) {
17086            final File mountFile = new File(mountPath);
17087
17088            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17089            if (monolithicFile.exists()) {
17090                packagePath = monolithicFile.getAbsolutePath();
17091                if (isFwdLocked()) {
17092                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17093                } else {
17094                    resourcePath = packagePath;
17095                }
17096            } else {
17097                packagePath = mountFile.getAbsolutePath();
17098                resourcePath = packagePath;
17099            }
17100        }
17101
17102        int doPostInstall(int status, int uid) {
17103            if (status != PackageManager.INSTALL_SUCCEEDED) {
17104                cleanUp();
17105            } else {
17106                final int groupOwner;
17107                final String protectedFile;
17108                if (isFwdLocked()) {
17109                    groupOwner = UserHandle.getSharedAppGid(uid);
17110                    protectedFile = RES_FILE_NAME;
17111                } else {
17112                    groupOwner = -1;
17113                    protectedFile = null;
17114                }
17115
17116                if (uid < Process.FIRST_APPLICATION_UID
17117                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17118                    Slog.e(TAG, "Failed to finalize " + cid);
17119                    PackageHelper.destroySdDir(cid);
17120                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17121                }
17122
17123                boolean mounted = PackageHelper.isContainerMounted(cid);
17124                if (!mounted) {
17125                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17126                }
17127            }
17128            return status;
17129        }
17130
17131        private void cleanUp() {
17132            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17133
17134            // Destroy secure container
17135            PackageHelper.destroySdDir(cid);
17136        }
17137
17138        private List<String> getAllCodePaths() {
17139            final File codeFile = new File(getCodePath());
17140            if (codeFile != null && codeFile.exists()) {
17141                try {
17142                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17143                    return pkg.getAllCodePaths();
17144                } catch (PackageParserException e) {
17145                    // Ignored; we tried our best
17146                }
17147            }
17148            return Collections.EMPTY_LIST;
17149        }
17150
17151        void cleanUpResourcesLI() {
17152            // Enumerate all code paths before deleting
17153            cleanUpResourcesLI(getAllCodePaths());
17154        }
17155
17156        private void cleanUpResourcesLI(List<String> allCodePaths) {
17157            cleanUp();
17158            removeDexFiles(allCodePaths, instructionSets);
17159        }
17160
17161        String getPackageName() {
17162            return getAsecPackageName(cid);
17163        }
17164
17165        boolean doPostDeleteLI(boolean delete) {
17166            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17167            final List<String> allCodePaths = getAllCodePaths();
17168            boolean mounted = PackageHelper.isContainerMounted(cid);
17169            if (mounted) {
17170                // Unmount first
17171                if (PackageHelper.unMountSdDir(cid)) {
17172                    mounted = false;
17173                }
17174            }
17175            if (!mounted && delete) {
17176                cleanUpResourcesLI(allCodePaths);
17177            }
17178            return !mounted;
17179        }
17180
17181        @Override
17182        int doPreCopy() {
17183            if (isFwdLocked()) {
17184                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17185                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17186                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17187                }
17188            }
17189
17190            return PackageManager.INSTALL_SUCCEEDED;
17191        }
17192
17193        @Override
17194        int doPostCopy(int uid) {
17195            if (isFwdLocked()) {
17196                if (uid < Process.FIRST_APPLICATION_UID
17197                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17198                                RES_FILE_NAME)) {
17199                    Slog.e(TAG, "Failed to finalize " + cid);
17200                    PackageHelper.destroySdDir(cid);
17201                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17202                }
17203            }
17204
17205            return PackageManager.INSTALL_SUCCEEDED;
17206        }
17207    }
17208
17209    /**
17210     * Logic to handle movement of existing installed applications.
17211     */
17212    class MoveInstallArgs extends InstallArgs {
17213        private File codeFile;
17214        private File resourceFile;
17215
17216        /** New install */
17217        MoveInstallArgs(InstallParams params) {
17218            super(params.origin, params.move, params.observer, params.installFlags,
17219                    params.installerPackageName, params.volumeUuid,
17220                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17221                    params.grantedRuntimePermissions,
17222                    params.traceMethod, params.traceCookie, params.certificates,
17223                    params.installReason);
17224        }
17225
17226        int copyApk(IMediaContainerService imcs, boolean temp) {
17227            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17228                    + move.fromUuid + " to " + move.toUuid);
17229            synchronized (mInstaller) {
17230                try {
17231                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17232                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17233                } catch (InstallerException e) {
17234                    Slog.w(TAG, "Failed to move app", e);
17235                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17236                }
17237            }
17238
17239            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17240            resourceFile = codeFile;
17241            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17242
17243            return PackageManager.INSTALL_SUCCEEDED;
17244        }
17245
17246        int doPreInstall(int status) {
17247            if (status != PackageManager.INSTALL_SUCCEEDED) {
17248                cleanUp(move.toUuid);
17249            }
17250            return status;
17251        }
17252
17253        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17254            if (status != PackageManager.INSTALL_SUCCEEDED) {
17255                cleanUp(move.toUuid);
17256                return false;
17257            }
17258
17259            // Reflect the move in app info
17260            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17261            pkg.setApplicationInfoCodePath(pkg.codePath);
17262            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17263            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17264            pkg.setApplicationInfoResourcePath(pkg.codePath);
17265            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17266            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17267
17268            return true;
17269        }
17270
17271        int doPostInstall(int status, int uid) {
17272            if (status == PackageManager.INSTALL_SUCCEEDED) {
17273                cleanUp(move.fromUuid);
17274            } else {
17275                cleanUp(move.toUuid);
17276            }
17277            return status;
17278        }
17279
17280        @Override
17281        String getCodePath() {
17282            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17283        }
17284
17285        @Override
17286        String getResourcePath() {
17287            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17288        }
17289
17290        private boolean cleanUp(String volumeUuid) {
17291            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17292                    move.dataAppName);
17293            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17294            final int[] userIds = sUserManager.getUserIds();
17295            synchronized (mInstallLock) {
17296                // Clean up both app data and code
17297                // All package moves are frozen until finished
17298                for (int userId : userIds) {
17299                    try {
17300                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17301                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17302                    } catch (InstallerException e) {
17303                        Slog.w(TAG, String.valueOf(e));
17304                    }
17305                }
17306                removeCodePathLI(codeFile);
17307            }
17308            return true;
17309        }
17310
17311        void cleanUpResourcesLI() {
17312            throw new UnsupportedOperationException();
17313        }
17314
17315        boolean doPostDeleteLI(boolean delete) {
17316            throw new UnsupportedOperationException();
17317        }
17318    }
17319
17320    static String getAsecPackageName(String packageCid) {
17321        int idx = packageCid.lastIndexOf("-");
17322        if (idx == -1) {
17323            return packageCid;
17324        }
17325        return packageCid.substring(0, idx);
17326    }
17327
17328    // Utility method used to create code paths based on package name and available index.
17329    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17330        String idxStr = "";
17331        int idx = 1;
17332        // Fall back to default value of idx=1 if prefix is not
17333        // part of oldCodePath
17334        if (oldCodePath != null) {
17335            String subStr = oldCodePath;
17336            // Drop the suffix right away
17337            if (suffix != null && subStr.endsWith(suffix)) {
17338                subStr = subStr.substring(0, subStr.length() - suffix.length());
17339            }
17340            // If oldCodePath already contains prefix find out the
17341            // ending index to either increment or decrement.
17342            int sidx = subStr.lastIndexOf(prefix);
17343            if (sidx != -1) {
17344                subStr = subStr.substring(sidx + prefix.length());
17345                if (subStr != null) {
17346                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17347                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17348                    }
17349                    try {
17350                        idx = Integer.parseInt(subStr);
17351                        if (idx <= 1) {
17352                            idx++;
17353                        } else {
17354                            idx--;
17355                        }
17356                    } catch(NumberFormatException e) {
17357                    }
17358                }
17359            }
17360        }
17361        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17362        return prefix + idxStr;
17363    }
17364
17365    private File getNextCodePath(File targetDir, String packageName) {
17366        File result;
17367        SecureRandom random = new SecureRandom();
17368        byte[] bytes = new byte[16];
17369        do {
17370            random.nextBytes(bytes);
17371            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17372            result = new File(targetDir, packageName + "-" + suffix);
17373        } while (result.exists());
17374        return result;
17375    }
17376
17377    // Utility method that returns the relative package path with respect
17378    // to the installation directory. Like say for /data/data/com.test-1.apk
17379    // string com.test-1 is returned.
17380    static String deriveCodePathName(String codePath) {
17381        if (codePath == null) {
17382            return null;
17383        }
17384        final File codeFile = new File(codePath);
17385        final String name = codeFile.getName();
17386        if (codeFile.isDirectory()) {
17387            return name;
17388        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17389            final int lastDot = name.lastIndexOf('.');
17390            return name.substring(0, lastDot);
17391        } else {
17392            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17393            return null;
17394        }
17395    }
17396
17397    static class PackageInstalledInfo {
17398        String name;
17399        int uid;
17400        // The set of users that originally had this package installed.
17401        int[] origUsers;
17402        // The set of users that now have this package installed.
17403        int[] newUsers;
17404        PackageParser.Package pkg;
17405        int returnCode;
17406        String returnMsg;
17407        PackageRemovedInfo removedInfo;
17408        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17409
17410        public void setError(int code, String msg) {
17411            setReturnCode(code);
17412            setReturnMessage(msg);
17413            Slog.w(TAG, msg);
17414        }
17415
17416        public void setError(String msg, PackageParserException e) {
17417            setReturnCode(e.error);
17418            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17419            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17420            for (int i = 0; i < childCount; i++) {
17421                addedChildPackages.valueAt(i).setError(msg, e);
17422            }
17423            Slog.w(TAG, msg, e);
17424        }
17425
17426        public void setError(String msg, PackageManagerException e) {
17427            returnCode = e.error;
17428            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17429            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17430            for (int i = 0; i < childCount; i++) {
17431                addedChildPackages.valueAt(i).setError(msg, e);
17432            }
17433            Slog.w(TAG, msg, e);
17434        }
17435
17436        public void setReturnCode(int returnCode) {
17437            this.returnCode = returnCode;
17438            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17439            for (int i = 0; i < childCount; i++) {
17440                addedChildPackages.valueAt(i).returnCode = returnCode;
17441            }
17442        }
17443
17444        private void setReturnMessage(String returnMsg) {
17445            this.returnMsg = returnMsg;
17446            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17447            for (int i = 0; i < childCount; i++) {
17448                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17449            }
17450        }
17451
17452        // In some error cases we want to convey more info back to the observer
17453        String origPackage;
17454        String origPermission;
17455    }
17456
17457    /*
17458     * Install a non-existing package.
17459     */
17460    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17461            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17462            PackageInstalledInfo res, int installReason) {
17463        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17464
17465        // Remember this for later, in case we need to rollback this install
17466        String pkgName = pkg.packageName;
17467
17468        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17469
17470        synchronized(mPackages) {
17471            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17472            if (renamedPackage != null) {
17473                // A package with the same name is already installed, though
17474                // it has been renamed to an older name.  The package we
17475                // are trying to install should be installed as an update to
17476                // the existing one, but that has not been requested, so bail.
17477                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17478                        + " without first uninstalling package running as "
17479                        + renamedPackage);
17480                return;
17481            }
17482            if (mPackages.containsKey(pkgName)) {
17483                // Don't allow installation over an existing package with the same name.
17484                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17485                        + " without first uninstalling.");
17486                return;
17487            }
17488        }
17489
17490        try {
17491            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17492                    System.currentTimeMillis(), user);
17493
17494            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17495
17496            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17497                prepareAppDataAfterInstallLIF(newPackage);
17498
17499            } else {
17500                // Remove package from internal structures, but keep around any
17501                // data that might have already existed
17502                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17503                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17504            }
17505        } catch (PackageManagerException e) {
17506            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17507        }
17508
17509        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17510    }
17511
17512    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17513        // Can't rotate keys during boot or if sharedUser.
17514        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17515                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17516            return false;
17517        }
17518        // app is using upgradeKeySets; make sure all are valid
17519        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17520        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17521        for (int i = 0; i < upgradeKeySets.length; i++) {
17522            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17523                Slog.wtf(TAG, "Package "
17524                         + (oldPs.name != null ? oldPs.name : "<null>")
17525                         + " contains upgrade-key-set reference to unknown key-set: "
17526                         + upgradeKeySets[i]
17527                         + " reverting to signatures check.");
17528                return false;
17529            }
17530        }
17531        return true;
17532    }
17533
17534    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17535        // Upgrade keysets are being used.  Determine if new package has a superset of the
17536        // required keys.
17537        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17538        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17539        for (int i = 0; i < upgradeKeySets.length; i++) {
17540            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17541            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17542                return true;
17543            }
17544        }
17545        return false;
17546    }
17547
17548    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17549        try (DigestInputStream digestStream =
17550                new DigestInputStream(new FileInputStream(file), digest)) {
17551            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17552        }
17553    }
17554
17555    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17556            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17557            int installReason) {
17558        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17559
17560        final PackageParser.Package oldPackage;
17561        final PackageSetting ps;
17562        final String pkgName = pkg.packageName;
17563        final int[] allUsers;
17564        final int[] installedUsers;
17565
17566        synchronized(mPackages) {
17567            oldPackage = mPackages.get(pkgName);
17568            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17569
17570            // don't allow upgrade to target a release SDK from a pre-release SDK
17571            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17572                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17573            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17574                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17575            if (oldTargetsPreRelease
17576                    && !newTargetsPreRelease
17577                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17578                Slog.w(TAG, "Can't install package targeting released sdk");
17579                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17580                return;
17581            }
17582
17583            ps = mSettings.mPackages.get(pkgName);
17584
17585            // verify signatures are valid
17586            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17587                if (!checkUpgradeKeySetLP(ps, pkg)) {
17588                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17589                            "New package not signed by keys specified by upgrade-keysets: "
17590                                    + pkgName);
17591                    return;
17592                }
17593            } else {
17594                // default to original signature matching
17595                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17596                        != PackageManager.SIGNATURE_MATCH) {
17597                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17598                            "New package has a different signature: " + pkgName);
17599                    return;
17600                }
17601            }
17602
17603            // don't allow a system upgrade unless the upgrade hash matches
17604            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17605                byte[] digestBytes = null;
17606                try {
17607                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17608                    updateDigest(digest, new File(pkg.baseCodePath));
17609                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17610                        for (String path : pkg.splitCodePaths) {
17611                            updateDigest(digest, new File(path));
17612                        }
17613                    }
17614                    digestBytes = digest.digest();
17615                } catch (NoSuchAlgorithmException | IOException e) {
17616                    res.setError(INSTALL_FAILED_INVALID_APK,
17617                            "Could not compute hash: " + pkgName);
17618                    return;
17619                }
17620                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17621                    res.setError(INSTALL_FAILED_INVALID_APK,
17622                            "New package fails restrict-update check: " + pkgName);
17623                    return;
17624                }
17625                // retain upgrade restriction
17626                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17627            }
17628
17629            // Check for shared user id changes
17630            String invalidPackageName =
17631                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17632            if (invalidPackageName != null) {
17633                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17634                        "Package " + invalidPackageName + " tried to change user "
17635                                + oldPackage.mSharedUserId);
17636                return;
17637            }
17638
17639            // In case of rollback, remember per-user/profile install state
17640            allUsers = sUserManager.getUserIds();
17641            installedUsers = ps.queryInstalledUsers(allUsers, true);
17642
17643            // don't allow an upgrade from full to ephemeral
17644            if (isInstantApp) {
17645                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17646                    for (int currentUser : allUsers) {
17647                        if (!ps.getInstantApp(currentUser)) {
17648                            // can't downgrade from full to instant
17649                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17650                                    + " for user: " + currentUser);
17651                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17652                            return;
17653                        }
17654                    }
17655                } else if (!ps.getInstantApp(user.getIdentifier())) {
17656                    // can't downgrade from full to instant
17657                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17658                            + " for user: " + user.getIdentifier());
17659                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17660                    return;
17661                }
17662            }
17663        }
17664
17665        // Update what is removed
17666        res.removedInfo = new PackageRemovedInfo(this);
17667        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17668        res.removedInfo.removedPackage = oldPackage.packageName;
17669        res.removedInfo.installerPackageName = ps.installerPackageName;
17670        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17671        res.removedInfo.isUpdate = true;
17672        res.removedInfo.origUsers = installedUsers;
17673        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17674        for (int i = 0; i < installedUsers.length; i++) {
17675            final int userId = installedUsers[i];
17676            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17677        }
17678
17679        final int childCount = (oldPackage.childPackages != null)
17680                ? oldPackage.childPackages.size() : 0;
17681        for (int i = 0; i < childCount; i++) {
17682            boolean childPackageUpdated = false;
17683            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17684            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17685            if (res.addedChildPackages != null) {
17686                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17687                if (childRes != null) {
17688                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17689                    childRes.removedInfo.removedPackage = childPkg.packageName;
17690                    if (childPs != null) {
17691                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17692                    }
17693                    childRes.removedInfo.isUpdate = true;
17694                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17695                    childPackageUpdated = true;
17696                }
17697            }
17698            if (!childPackageUpdated) {
17699                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17700                childRemovedRes.removedPackage = childPkg.packageName;
17701                if (childPs != null) {
17702                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17703                }
17704                childRemovedRes.isUpdate = false;
17705                childRemovedRes.dataRemoved = true;
17706                synchronized (mPackages) {
17707                    if (childPs != null) {
17708                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17709                    }
17710                }
17711                if (res.removedInfo.removedChildPackages == null) {
17712                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17713                }
17714                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17715            }
17716        }
17717
17718        boolean sysPkg = (isSystemApp(oldPackage));
17719        if (sysPkg) {
17720            // Set the system/privileged flags as needed
17721            final boolean privileged =
17722                    (oldPackage.applicationInfo.privateFlags
17723                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17724            final int systemPolicyFlags = policyFlags
17725                    | PackageParser.PARSE_IS_SYSTEM
17726                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17727
17728            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17729                    user, allUsers, installerPackageName, res, installReason);
17730        } else {
17731            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17732                    user, allUsers, installerPackageName, res, installReason);
17733        }
17734    }
17735
17736    @Override
17737    public List<String> getPreviousCodePaths(String packageName) {
17738        final int callingUid = Binder.getCallingUid();
17739        final List<String> result = new ArrayList<>();
17740        if (getInstantAppPackageName(callingUid) != null) {
17741            return result;
17742        }
17743        final PackageSetting ps = mSettings.mPackages.get(packageName);
17744        if (ps != null
17745                && ps.oldCodePaths != null
17746                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17747            result.addAll(ps.oldCodePaths);
17748        }
17749        return result;
17750    }
17751
17752    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17753            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17754            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17755            int installReason) {
17756        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17757                + deletedPackage);
17758
17759        String pkgName = deletedPackage.packageName;
17760        boolean deletedPkg = true;
17761        boolean addedPkg = false;
17762        boolean updatedSettings = false;
17763        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17764        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17765                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17766
17767        final long origUpdateTime = (pkg.mExtras != null)
17768                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17769
17770        // First delete the existing package while retaining the data directory
17771        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17772                res.removedInfo, true, pkg)) {
17773            // If the existing package wasn't successfully deleted
17774            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17775            deletedPkg = false;
17776        } else {
17777            // Successfully deleted the old package; proceed with replace.
17778
17779            // If deleted package lived in a container, give users a chance to
17780            // relinquish resources before killing.
17781            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17782                if (DEBUG_INSTALL) {
17783                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17784                }
17785                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17786                final ArrayList<String> pkgList = new ArrayList<String>(1);
17787                pkgList.add(deletedPackage.applicationInfo.packageName);
17788                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17789            }
17790
17791            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17792                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17793            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17794
17795            try {
17796                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17797                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17798                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17799                        installReason);
17800
17801                // Update the in-memory copy of the previous code paths.
17802                PackageSetting ps = mSettings.mPackages.get(pkgName);
17803                if (!killApp) {
17804                    if (ps.oldCodePaths == null) {
17805                        ps.oldCodePaths = new ArraySet<>();
17806                    }
17807                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17808                    if (deletedPackage.splitCodePaths != null) {
17809                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17810                    }
17811                } else {
17812                    ps.oldCodePaths = null;
17813                }
17814                if (ps.childPackageNames != null) {
17815                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17816                        final String childPkgName = ps.childPackageNames.get(i);
17817                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17818                        childPs.oldCodePaths = ps.oldCodePaths;
17819                    }
17820                }
17821                // set instant app status, but, only if it's explicitly specified
17822                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17823                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17824                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17825                prepareAppDataAfterInstallLIF(newPackage);
17826                addedPkg = true;
17827                mDexManager.notifyPackageUpdated(newPackage.packageName,
17828                        newPackage.baseCodePath, newPackage.splitCodePaths);
17829            } catch (PackageManagerException e) {
17830                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17831            }
17832        }
17833
17834        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17835            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17836
17837            // Revert all internal state mutations and added folders for the failed install
17838            if (addedPkg) {
17839                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17840                        res.removedInfo, true, null);
17841            }
17842
17843            // Restore the old package
17844            if (deletedPkg) {
17845                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17846                File restoreFile = new File(deletedPackage.codePath);
17847                // Parse old package
17848                boolean oldExternal = isExternal(deletedPackage);
17849                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17850                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17851                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17852                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17853                try {
17854                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17855                            null);
17856                } catch (PackageManagerException e) {
17857                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17858                            + e.getMessage());
17859                    return;
17860                }
17861
17862                synchronized (mPackages) {
17863                    // Ensure the installer package name up to date
17864                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17865
17866                    // Update permissions for restored package
17867                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17868
17869                    mSettings.writeLPr();
17870                }
17871
17872                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17873            }
17874        } else {
17875            synchronized (mPackages) {
17876                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17877                if (ps != null) {
17878                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17879                    if (res.removedInfo.removedChildPackages != null) {
17880                        final int childCount = res.removedInfo.removedChildPackages.size();
17881                        // Iterate in reverse as we may modify the collection
17882                        for (int i = childCount - 1; i >= 0; i--) {
17883                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17884                            if (res.addedChildPackages.containsKey(childPackageName)) {
17885                                res.removedInfo.removedChildPackages.removeAt(i);
17886                            } else {
17887                                PackageRemovedInfo childInfo = res.removedInfo
17888                                        .removedChildPackages.valueAt(i);
17889                                childInfo.removedForAllUsers = mPackages.get(
17890                                        childInfo.removedPackage) == null;
17891                            }
17892                        }
17893                    }
17894                }
17895            }
17896        }
17897    }
17898
17899    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17900            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17901            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17902            int installReason) {
17903        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17904                + ", old=" + deletedPackage);
17905
17906        final boolean disabledSystem;
17907
17908        // Remove existing system package
17909        removePackageLI(deletedPackage, true);
17910
17911        synchronized (mPackages) {
17912            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17913        }
17914        if (!disabledSystem) {
17915            // We didn't need to disable the .apk as a current system package,
17916            // which means we are replacing another update that is already
17917            // installed.  We need to make sure to delete the older one's .apk.
17918            res.removedInfo.args = createInstallArgsForExisting(0,
17919                    deletedPackage.applicationInfo.getCodePath(),
17920                    deletedPackage.applicationInfo.getResourcePath(),
17921                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17922        } else {
17923            res.removedInfo.args = null;
17924        }
17925
17926        // Successfully disabled the old package. Now proceed with re-installation
17927        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17928                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17929        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17930
17931        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17932        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17933                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17934
17935        PackageParser.Package newPackage = null;
17936        try {
17937            // Add the package to the internal data structures
17938            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17939
17940            // Set the update and install times
17941            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17942            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17943                    System.currentTimeMillis());
17944
17945            // Update the package dynamic state if succeeded
17946            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17947                // Now that the install succeeded make sure we remove data
17948                // directories for any child package the update removed.
17949                final int deletedChildCount = (deletedPackage.childPackages != null)
17950                        ? deletedPackage.childPackages.size() : 0;
17951                final int newChildCount = (newPackage.childPackages != null)
17952                        ? newPackage.childPackages.size() : 0;
17953                for (int i = 0; i < deletedChildCount; i++) {
17954                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17955                    boolean childPackageDeleted = true;
17956                    for (int j = 0; j < newChildCount; j++) {
17957                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17958                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17959                            childPackageDeleted = false;
17960                            break;
17961                        }
17962                    }
17963                    if (childPackageDeleted) {
17964                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17965                                deletedChildPkg.packageName);
17966                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17967                            PackageRemovedInfo removedChildRes = res.removedInfo
17968                                    .removedChildPackages.get(deletedChildPkg.packageName);
17969                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17970                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17971                        }
17972                    }
17973                }
17974
17975                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17976                        installReason);
17977                prepareAppDataAfterInstallLIF(newPackage);
17978
17979                mDexManager.notifyPackageUpdated(newPackage.packageName,
17980                            newPackage.baseCodePath, newPackage.splitCodePaths);
17981            }
17982        } catch (PackageManagerException e) {
17983            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17984            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17985        }
17986
17987        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17988            // Re installation failed. Restore old information
17989            // Remove new pkg information
17990            if (newPackage != null) {
17991                removeInstalledPackageLI(newPackage, true);
17992            }
17993            // Add back the old system package
17994            try {
17995                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17996            } catch (PackageManagerException e) {
17997                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17998            }
17999
18000            synchronized (mPackages) {
18001                if (disabledSystem) {
18002                    enableSystemPackageLPw(deletedPackage);
18003                }
18004
18005                // Ensure the installer package name up to date
18006                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18007
18008                // Update permissions for restored package
18009                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18010
18011                mSettings.writeLPr();
18012            }
18013
18014            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18015                    + " after failed upgrade");
18016        }
18017    }
18018
18019    /**
18020     * Checks whether the parent or any of the child packages have a change shared
18021     * user. For a package to be a valid update the shred users of the parent and
18022     * the children should match. We may later support changing child shared users.
18023     * @param oldPkg The updated package.
18024     * @param newPkg The update package.
18025     * @return The shared user that change between the versions.
18026     */
18027    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18028            PackageParser.Package newPkg) {
18029        // Check parent shared user
18030        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18031            return newPkg.packageName;
18032        }
18033        // Check child shared users
18034        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18035        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18036        for (int i = 0; i < newChildCount; i++) {
18037            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18038            // If this child was present, did it have the same shared user?
18039            for (int j = 0; j < oldChildCount; j++) {
18040                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18041                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18042                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18043                    return newChildPkg.packageName;
18044                }
18045            }
18046        }
18047        return null;
18048    }
18049
18050    private void removeNativeBinariesLI(PackageSetting ps) {
18051        // Remove the lib path for the parent package
18052        if (ps != null) {
18053            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18054            // Remove the lib path for the child packages
18055            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18056            for (int i = 0; i < childCount; i++) {
18057                PackageSetting childPs = null;
18058                synchronized (mPackages) {
18059                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18060                }
18061                if (childPs != null) {
18062                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18063                            .legacyNativeLibraryPathString);
18064                }
18065            }
18066        }
18067    }
18068
18069    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18070        // Enable the parent package
18071        mSettings.enableSystemPackageLPw(pkg.packageName);
18072        // Enable the child packages
18073        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18074        for (int i = 0; i < childCount; i++) {
18075            PackageParser.Package childPkg = pkg.childPackages.get(i);
18076            mSettings.enableSystemPackageLPw(childPkg.packageName);
18077        }
18078    }
18079
18080    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18081            PackageParser.Package newPkg) {
18082        // Disable the parent package (parent always replaced)
18083        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18084        // Disable the child packages
18085        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18086        for (int i = 0; i < childCount; i++) {
18087            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18088            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18089            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18090        }
18091        return disabled;
18092    }
18093
18094    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18095            String installerPackageName) {
18096        // Enable the parent package
18097        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18098        // Enable the child packages
18099        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18100        for (int i = 0; i < childCount; i++) {
18101            PackageParser.Package childPkg = pkg.childPackages.get(i);
18102            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18103        }
18104    }
18105
18106    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18107        // Collect all used permissions in the UID
18108        ArraySet<String> usedPermissions = new ArraySet<>();
18109        final int packageCount = su.packages.size();
18110        for (int i = 0; i < packageCount; i++) {
18111            PackageSetting ps = su.packages.valueAt(i);
18112            if (ps.pkg == null) {
18113                continue;
18114            }
18115            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18116            for (int j = 0; j < requestedPermCount; j++) {
18117                String permission = ps.pkg.requestedPermissions.get(j);
18118                BasePermission bp = mSettings.mPermissions.get(permission);
18119                if (bp != null) {
18120                    usedPermissions.add(permission);
18121                }
18122            }
18123        }
18124
18125        PermissionsState permissionsState = su.getPermissionsState();
18126        // Prune install permissions
18127        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18128        final int installPermCount = installPermStates.size();
18129        for (int i = installPermCount - 1; i >= 0;  i--) {
18130            PermissionState permissionState = installPermStates.get(i);
18131            if (!usedPermissions.contains(permissionState.getName())) {
18132                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18133                if (bp != null) {
18134                    permissionsState.revokeInstallPermission(bp);
18135                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18136                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18137                }
18138            }
18139        }
18140
18141        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18142
18143        // Prune runtime permissions
18144        for (int userId : allUserIds) {
18145            List<PermissionState> runtimePermStates = permissionsState
18146                    .getRuntimePermissionStates(userId);
18147            final int runtimePermCount = runtimePermStates.size();
18148            for (int i = runtimePermCount - 1; i >= 0; i--) {
18149                PermissionState permissionState = runtimePermStates.get(i);
18150                if (!usedPermissions.contains(permissionState.getName())) {
18151                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18152                    if (bp != null) {
18153                        permissionsState.revokeRuntimePermission(bp, userId);
18154                        permissionsState.updatePermissionFlags(bp, userId,
18155                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18156                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18157                                runtimePermissionChangedUserIds, userId);
18158                    }
18159                }
18160            }
18161        }
18162
18163        return runtimePermissionChangedUserIds;
18164    }
18165
18166    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18167            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18168        // Update the parent package setting
18169        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18170                res, user, installReason);
18171        // Update the child packages setting
18172        final int childCount = (newPackage.childPackages != null)
18173                ? newPackage.childPackages.size() : 0;
18174        for (int i = 0; i < childCount; i++) {
18175            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18176            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18177            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18178                    childRes.origUsers, childRes, user, installReason);
18179        }
18180    }
18181
18182    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18183            String installerPackageName, int[] allUsers, int[] installedForUsers,
18184            PackageInstalledInfo res, UserHandle user, int installReason) {
18185        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18186
18187        String pkgName = newPackage.packageName;
18188        synchronized (mPackages) {
18189            //write settings. the installStatus will be incomplete at this stage.
18190            //note that the new package setting would have already been
18191            //added to mPackages. It hasn't been persisted yet.
18192            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18193            // TODO: Remove this write? It's also written at the end of this method
18194            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18195            mSettings.writeLPr();
18196            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18197        }
18198
18199        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18200        synchronized (mPackages) {
18201            updatePermissionsLPw(newPackage.packageName, newPackage,
18202                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18203                            ? UPDATE_PERMISSIONS_ALL : 0));
18204            // For system-bundled packages, we assume that installing an upgraded version
18205            // of the package implies that the user actually wants to run that new code,
18206            // so we enable the package.
18207            PackageSetting ps = mSettings.mPackages.get(pkgName);
18208            final int userId = user.getIdentifier();
18209            if (ps != null) {
18210                if (isSystemApp(newPackage)) {
18211                    if (DEBUG_INSTALL) {
18212                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18213                    }
18214                    // Enable system package for requested users
18215                    if (res.origUsers != null) {
18216                        for (int origUserId : res.origUsers) {
18217                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18218                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18219                                        origUserId, installerPackageName);
18220                            }
18221                        }
18222                    }
18223                    // Also convey the prior install/uninstall state
18224                    if (allUsers != null && installedForUsers != null) {
18225                        for (int currentUserId : allUsers) {
18226                            final boolean installed = ArrayUtils.contains(
18227                                    installedForUsers, currentUserId);
18228                            if (DEBUG_INSTALL) {
18229                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18230                            }
18231                            ps.setInstalled(installed, currentUserId);
18232                        }
18233                        // these install state changes will be persisted in the
18234                        // upcoming call to mSettings.writeLPr().
18235                    }
18236                }
18237                // It's implied that when a user requests installation, they want the app to be
18238                // installed and enabled.
18239                if (userId != UserHandle.USER_ALL) {
18240                    ps.setInstalled(true, userId);
18241                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18242                }
18243
18244                // When replacing an existing package, preserve the original install reason for all
18245                // users that had the package installed before.
18246                final Set<Integer> previousUserIds = new ArraySet<>();
18247                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18248                    final int installReasonCount = res.removedInfo.installReasons.size();
18249                    for (int i = 0; i < installReasonCount; i++) {
18250                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18251                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18252                        ps.setInstallReason(previousInstallReason, previousUserId);
18253                        previousUserIds.add(previousUserId);
18254                    }
18255                }
18256
18257                // Set install reason for users that are having the package newly installed.
18258                if (userId == UserHandle.USER_ALL) {
18259                    for (int currentUserId : sUserManager.getUserIds()) {
18260                        if (!previousUserIds.contains(currentUserId)) {
18261                            ps.setInstallReason(installReason, currentUserId);
18262                        }
18263                    }
18264                } else if (!previousUserIds.contains(userId)) {
18265                    ps.setInstallReason(installReason, userId);
18266                }
18267                mSettings.writeKernelMappingLPr(ps);
18268            }
18269            res.name = pkgName;
18270            res.uid = newPackage.applicationInfo.uid;
18271            res.pkg = newPackage;
18272            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18273            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18274            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18275            //to update install status
18276            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18277            mSettings.writeLPr();
18278            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18279        }
18280
18281        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18282    }
18283
18284    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18285        try {
18286            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18287            installPackageLI(args, res);
18288        } finally {
18289            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18290        }
18291    }
18292
18293    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18294        final int installFlags = args.installFlags;
18295        final String installerPackageName = args.installerPackageName;
18296        final String volumeUuid = args.volumeUuid;
18297        final File tmpPackageFile = new File(args.getCodePath());
18298        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18299        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18300                || (args.volumeUuid != null));
18301        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18302        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18303        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18304        final boolean virtualPreload =
18305                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18306        boolean replace = false;
18307        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18308        if (args.move != null) {
18309            // moving a complete application; perform an initial scan on the new install location
18310            scanFlags |= SCAN_INITIAL;
18311        }
18312        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18313            scanFlags |= SCAN_DONT_KILL_APP;
18314        }
18315        if (instantApp) {
18316            scanFlags |= SCAN_AS_INSTANT_APP;
18317        }
18318        if (fullApp) {
18319            scanFlags |= SCAN_AS_FULL_APP;
18320        }
18321        if (virtualPreload) {
18322            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18323        }
18324
18325        // Result object to be returned
18326        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18327
18328        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18329
18330        // Sanity check
18331        if (instantApp && (forwardLocked || onExternal)) {
18332            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18333                    + " external=" + onExternal);
18334            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18335            return;
18336        }
18337
18338        // Retrieve PackageSettings and parse package
18339        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18340                | PackageParser.PARSE_ENFORCE_CODE
18341                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18342                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18343                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18344                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18345        PackageParser pp = new PackageParser();
18346        pp.setSeparateProcesses(mSeparateProcesses);
18347        pp.setDisplayMetrics(mMetrics);
18348        pp.setCallback(mPackageParserCallback);
18349
18350        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18351        final PackageParser.Package pkg;
18352        try {
18353            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18354        } catch (PackageParserException e) {
18355            res.setError("Failed parse during installPackageLI", e);
18356            return;
18357        } finally {
18358            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18359        }
18360
18361        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18362        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18363            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18364            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18365                    "Instant app package must target O");
18366            return;
18367        }
18368        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18369            Slog.w(TAG, "Instant app package " + pkg.packageName
18370                    + " does not target targetSandboxVersion 2");
18371            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18372                    "Instant app package must use targetSanboxVersion 2");
18373            return;
18374        }
18375
18376        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18377            // Static shared libraries have synthetic package names
18378            renameStaticSharedLibraryPackage(pkg);
18379
18380            // No static shared libs on external storage
18381            if (onExternal) {
18382                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18383                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18384                        "Packages declaring static-shared libs cannot be updated");
18385                return;
18386            }
18387        }
18388
18389        // If we are installing a clustered package add results for the children
18390        if (pkg.childPackages != null) {
18391            synchronized (mPackages) {
18392                final int childCount = pkg.childPackages.size();
18393                for (int i = 0; i < childCount; i++) {
18394                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18395                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18396                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18397                    childRes.pkg = childPkg;
18398                    childRes.name = childPkg.packageName;
18399                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18400                    if (childPs != null) {
18401                        childRes.origUsers = childPs.queryInstalledUsers(
18402                                sUserManager.getUserIds(), true);
18403                    }
18404                    if ((mPackages.containsKey(childPkg.packageName))) {
18405                        childRes.removedInfo = new PackageRemovedInfo(this);
18406                        childRes.removedInfo.removedPackage = childPkg.packageName;
18407                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18408                    }
18409                    if (res.addedChildPackages == null) {
18410                        res.addedChildPackages = new ArrayMap<>();
18411                    }
18412                    res.addedChildPackages.put(childPkg.packageName, childRes);
18413                }
18414            }
18415        }
18416
18417        // If package doesn't declare API override, mark that we have an install
18418        // time CPU ABI override.
18419        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18420            pkg.cpuAbiOverride = args.abiOverride;
18421        }
18422
18423        String pkgName = res.name = pkg.packageName;
18424        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18425            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18426                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18427                return;
18428            }
18429        }
18430
18431        try {
18432            // either use what we've been given or parse directly from the APK
18433            if (args.certificates != null) {
18434                try {
18435                    PackageParser.populateCertificates(pkg, args.certificates);
18436                } catch (PackageParserException e) {
18437                    // there was something wrong with the certificates we were given;
18438                    // try to pull them from the APK
18439                    PackageParser.collectCertificates(pkg, parseFlags);
18440                }
18441            } else {
18442                PackageParser.collectCertificates(pkg, parseFlags);
18443            }
18444        } catch (PackageParserException e) {
18445            res.setError("Failed collect during installPackageLI", e);
18446            return;
18447        }
18448
18449        // Get rid of all references to package scan path via parser.
18450        pp = null;
18451        String oldCodePath = null;
18452        boolean systemApp = false;
18453        synchronized (mPackages) {
18454            // Check if installing already existing package
18455            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18456                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18457                if (pkg.mOriginalPackages != null
18458                        && pkg.mOriginalPackages.contains(oldName)
18459                        && mPackages.containsKey(oldName)) {
18460                    // This package is derived from an original package,
18461                    // and this device has been updating from that original
18462                    // name.  We must continue using the original name, so
18463                    // rename the new package here.
18464                    pkg.setPackageName(oldName);
18465                    pkgName = pkg.packageName;
18466                    replace = true;
18467                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18468                            + oldName + " pkgName=" + pkgName);
18469                } else if (mPackages.containsKey(pkgName)) {
18470                    // This package, under its official name, already exists
18471                    // on the device; we should replace it.
18472                    replace = true;
18473                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18474                }
18475
18476                // Child packages are installed through the parent package
18477                if (pkg.parentPackage != null) {
18478                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18479                            "Package " + pkg.packageName + " is child of package "
18480                                    + pkg.parentPackage.parentPackage + ". Child packages "
18481                                    + "can be updated only through the parent package.");
18482                    return;
18483                }
18484
18485                if (replace) {
18486                    // Prevent apps opting out from runtime permissions
18487                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18488                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18489                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18490                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18491                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18492                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18493                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18494                                        + " doesn't support runtime permissions but the old"
18495                                        + " target SDK " + oldTargetSdk + " does.");
18496                        return;
18497                    }
18498                    // Prevent apps from downgrading their targetSandbox.
18499                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18500                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18501                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18502                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18503                                "Package " + pkg.packageName + " new target sandbox "
18504                                + newTargetSandbox + " is incompatible with the previous value of"
18505                                + oldTargetSandbox + ".");
18506                        return;
18507                    }
18508
18509                    // Prevent installing of child packages
18510                    if (oldPackage.parentPackage != null) {
18511                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18512                                "Package " + pkg.packageName + " is child of package "
18513                                        + oldPackage.parentPackage + ". Child packages "
18514                                        + "can be updated only through the parent package.");
18515                        return;
18516                    }
18517                }
18518            }
18519
18520            PackageSetting ps = mSettings.mPackages.get(pkgName);
18521            if (ps != null) {
18522                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18523
18524                // Static shared libs have same package with different versions where
18525                // we internally use a synthetic package name to allow multiple versions
18526                // of the same package, therefore we need to compare signatures against
18527                // the package setting for the latest library version.
18528                PackageSetting signatureCheckPs = ps;
18529                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18530                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18531                    if (libraryEntry != null) {
18532                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18533                    }
18534                }
18535
18536                // Quick sanity check that we're signed correctly if updating;
18537                // we'll check this again later when scanning, but we want to
18538                // bail early here before tripping over redefined permissions.
18539                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18540                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18541                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18542                                + pkg.packageName + " upgrade keys do not match the "
18543                                + "previously installed version");
18544                        return;
18545                    }
18546                } else {
18547                    try {
18548                        verifySignaturesLP(signatureCheckPs, pkg);
18549                    } catch (PackageManagerException e) {
18550                        res.setError(e.error, e.getMessage());
18551                        return;
18552                    }
18553                }
18554
18555                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18556                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18557                    systemApp = (ps.pkg.applicationInfo.flags &
18558                            ApplicationInfo.FLAG_SYSTEM) != 0;
18559                }
18560                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18561            }
18562
18563            int N = pkg.permissions.size();
18564            for (int i = N-1; i >= 0; i--) {
18565                PackageParser.Permission perm = pkg.permissions.get(i);
18566                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18567
18568                // Don't allow anyone but the system to define ephemeral permissions.
18569                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18570                        && !systemApp) {
18571                    Slog.w(TAG, "Non-System package " + pkg.packageName
18572                            + " attempting to delcare ephemeral permission "
18573                            + perm.info.name + "; Removing ephemeral.");
18574                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18575                }
18576                // Check whether the newly-scanned package wants to define an already-defined perm
18577                if (bp != null) {
18578                    // If the defining package is signed with our cert, it's okay.  This
18579                    // also includes the "updating the same package" case, of course.
18580                    // "updating same package" could also involve key-rotation.
18581                    final boolean sigsOk;
18582                    if (bp.sourcePackage.equals(pkg.packageName)
18583                            && (bp.packageSetting instanceof PackageSetting)
18584                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18585                                    scanFlags))) {
18586                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18587                    } else {
18588                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18589                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18590                    }
18591                    if (!sigsOk) {
18592                        // If the owning package is the system itself, we log but allow
18593                        // install to proceed; we fail the install on all other permission
18594                        // redefinitions.
18595                        if (!bp.sourcePackage.equals("android")) {
18596                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18597                                    + pkg.packageName + " attempting to redeclare permission "
18598                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18599                            res.origPermission = perm.info.name;
18600                            res.origPackage = bp.sourcePackage;
18601                            return;
18602                        } else {
18603                            Slog.w(TAG, "Package " + pkg.packageName
18604                                    + " attempting to redeclare system permission "
18605                                    + perm.info.name + "; ignoring new declaration");
18606                            pkg.permissions.remove(i);
18607                        }
18608                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18609                        // Prevent apps to change protection level to dangerous from any other
18610                        // type as this would allow a privilege escalation where an app adds a
18611                        // normal/signature permission in other app's group and later redefines
18612                        // it as dangerous leading to the group auto-grant.
18613                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18614                                == PermissionInfo.PROTECTION_DANGEROUS) {
18615                            if (bp != null && !bp.isRuntime()) {
18616                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18617                                        + "non-runtime permission " + perm.info.name
18618                                        + " to runtime; keeping old protection level");
18619                                perm.info.protectionLevel = bp.protectionLevel;
18620                            }
18621                        }
18622                    }
18623                }
18624            }
18625        }
18626
18627        if (systemApp) {
18628            if (onExternal) {
18629                // Abort update; system app can't be replaced with app on sdcard
18630                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18631                        "Cannot install updates to system apps on sdcard");
18632                return;
18633            } else if (instantApp) {
18634                // Abort update; system app can't be replaced with an instant app
18635                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18636                        "Cannot update a system app with an instant app");
18637                return;
18638            }
18639        }
18640
18641        if (args.move != null) {
18642            // We did an in-place move, so dex is ready to roll
18643            scanFlags |= SCAN_NO_DEX;
18644            scanFlags |= SCAN_MOVE;
18645
18646            synchronized (mPackages) {
18647                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18648                if (ps == null) {
18649                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18650                            "Missing settings for moved package " + pkgName);
18651                }
18652
18653                // We moved the entire application as-is, so bring over the
18654                // previously derived ABI information.
18655                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18656                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18657            }
18658
18659        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18660            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18661            scanFlags |= SCAN_NO_DEX;
18662
18663            try {
18664                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18665                    args.abiOverride : pkg.cpuAbiOverride);
18666                final boolean extractNativeLibs = !pkg.isLibrary();
18667                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18668                        extractNativeLibs, mAppLib32InstallDir);
18669            } catch (PackageManagerException pme) {
18670                Slog.e(TAG, "Error deriving application ABI", pme);
18671                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18672                return;
18673            }
18674
18675            // Shared libraries for the package need to be updated.
18676            synchronized (mPackages) {
18677                try {
18678                    updateSharedLibrariesLPr(pkg, null);
18679                } catch (PackageManagerException e) {
18680                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18681                }
18682            }
18683        }
18684
18685        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18686            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18687            return;
18688        }
18689
18690        // Verify if we need to dexopt the app.
18691        //
18692        // NOTE: it is *important* to call dexopt after doRename which will sync the
18693        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18694        //
18695        // We only need to dexopt if the package meets ALL of the following conditions:
18696        //   1) it is not forward locked.
18697        //   2) it is not on on an external ASEC container.
18698        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18699        //
18700        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18701        // complete, so we skip this step during installation. Instead, we'll take extra time
18702        // the first time the instant app starts. It's preferred to do it this way to provide
18703        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18704        // middle of running an instant app. The default behaviour can be overridden
18705        // via gservices.
18706        final boolean performDexopt = !forwardLocked
18707            && !pkg.applicationInfo.isExternalAsec()
18708            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18709                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18710
18711        if (performDexopt) {
18712            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18713            // Do not run PackageDexOptimizer through the local performDexOpt
18714            // method because `pkg` may not be in `mPackages` yet.
18715            //
18716            // Also, don't fail application installs if the dexopt step fails.
18717            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18718                REASON_INSTALL,
18719                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18720            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18721                null /* instructionSets */,
18722                getOrCreateCompilerPackageStats(pkg),
18723                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18724                dexoptOptions);
18725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18726        }
18727
18728        // Notify BackgroundDexOptService that the package has been changed.
18729        // If this is an update of a package which used to fail to compile,
18730        // BackgroundDexOptService will remove it from its blacklist.
18731        // TODO: Layering violation
18732        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18733
18734        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18735
18736        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18737                "installPackageLI")) {
18738            if (replace) {
18739                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18740                    // Static libs have a synthetic package name containing the version
18741                    // and cannot be updated as an update would get a new package name,
18742                    // unless this is the exact same version code which is useful for
18743                    // development.
18744                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18745                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18746                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18747                                + "static-shared libs cannot be updated");
18748                        return;
18749                    }
18750                }
18751                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18752                        installerPackageName, res, args.installReason);
18753            } else {
18754                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18755                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18756            }
18757        }
18758
18759        synchronized (mPackages) {
18760            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18761            if (ps != null) {
18762                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18763                ps.setUpdateAvailable(false /*updateAvailable*/);
18764            }
18765
18766            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18767            for (int i = 0; i < childCount; i++) {
18768                PackageParser.Package childPkg = pkg.childPackages.get(i);
18769                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18770                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18771                if (childPs != null) {
18772                    childRes.newUsers = childPs.queryInstalledUsers(
18773                            sUserManager.getUserIds(), true);
18774                }
18775            }
18776
18777            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18778                updateSequenceNumberLP(ps, res.newUsers);
18779                updateInstantAppInstallerLocked(pkgName);
18780            }
18781        }
18782    }
18783
18784    private void startIntentFilterVerifications(int userId, boolean replacing,
18785            PackageParser.Package pkg) {
18786        if (mIntentFilterVerifierComponent == null) {
18787            Slog.w(TAG, "No IntentFilter verification will not be done as "
18788                    + "there is no IntentFilterVerifier available!");
18789            return;
18790        }
18791
18792        final int verifierUid = getPackageUid(
18793                mIntentFilterVerifierComponent.getPackageName(),
18794                MATCH_DEBUG_TRIAGED_MISSING,
18795                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18796
18797        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18798        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18799        mHandler.sendMessage(msg);
18800
18801        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18802        for (int i = 0; i < childCount; i++) {
18803            PackageParser.Package childPkg = pkg.childPackages.get(i);
18804            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18805            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18806            mHandler.sendMessage(msg);
18807        }
18808    }
18809
18810    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18811            PackageParser.Package pkg) {
18812        int size = pkg.activities.size();
18813        if (size == 0) {
18814            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18815                    "No activity, so no need to verify any IntentFilter!");
18816            return;
18817        }
18818
18819        final boolean hasDomainURLs = hasDomainURLs(pkg);
18820        if (!hasDomainURLs) {
18821            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18822                    "No domain URLs, so no need to verify any IntentFilter!");
18823            return;
18824        }
18825
18826        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18827                + " if any IntentFilter from the " + size
18828                + " Activities needs verification ...");
18829
18830        int count = 0;
18831        final String packageName = pkg.packageName;
18832
18833        synchronized (mPackages) {
18834            // If this is a new install and we see that we've already run verification for this
18835            // package, we have nothing to do: it means the state was restored from backup.
18836            if (!replacing) {
18837                IntentFilterVerificationInfo ivi =
18838                        mSettings.getIntentFilterVerificationLPr(packageName);
18839                if (ivi != null) {
18840                    if (DEBUG_DOMAIN_VERIFICATION) {
18841                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18842                                + ivi.getStatusString());
18843                    }
18844                    return;
18845                }
18846            }
18847
18848            // If any filters need to be verified, then all need to be.
18849            boolean needToVerify = false;
18850            for (PackageParser.Activity a : pkg.activities) {
18851                for (ActivityIntentInfo filter : a.intents) {
18852                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18853                        if (DEBUG_DOMAIN_VERIFICATION) {
18854                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18855                        }
18856                        needToVerify = true;
18857                        break;
18858                    }
18859                }
18860            }
18861
18862            if (needToVerify) {
18863                final int verificationId = mIntentFilterVerificationToken++;
18864                for (PackageParser.Activity a : pkg.activities) {
18865                    for (ActivityIntentInfo filter : a.intents) {
18866                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18867                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18868                                    "Verification needed for IntentFilter:" + filter.toString());
18869                            mIntentFilterVerifier.addOneIntentFilterVerification(
18870                                    verifierUid, userId, verificationId, filter, packageName);
18871                            count++;
18872                        }
18873                    }
18874                }
18875            }
18876        }
18877
18878        if (count > 0) {
18879            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18880                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18881                    +  " for userId:" + userId);
18882            mIntentFilterVerifier.startVerifications(userId);
18883        } else {
18884            if (DEBUG_DOMAIN_VERIFICATION) {
18885                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18886            }
18887        }
18888    }
18889
18890    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18891        final ComponentName cn  = filter.activity.getComponentName();
18892        final String packageName = cn.getPackageName();
18893
18894        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18895                packageName);
18896        if (ivi == null) {
18897            return true;
18898        }
18899        int status = ivi.getStatus();
18900        switch (status) {
18901            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18902            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18903                return true;
18904
18905            default:
18906                // Nothing to do
18907                return false;
18908        }
18909    }
18910
18911    private static boolean isMultiArch(ApplicationInfo info) {
18912        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18913    }
18914
18915    private static boolean isExternal(PackageParser.Package pkg) {
18916        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18917    }
18918
18919    private static boolean isExternal(PackageSetting ps) {
18920        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18921    }
18922
18923    private static boolean isSystemApp(PackageParser.Package pkg) {
18924        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18925    }
18926
18927    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18928        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18929    }
18930
18931    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18932        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18933    }
18934
18935    private static boolean isSystemApp(PackageSetting ps) {
18936        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18937    }
18938
18939    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18940        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18941    }
18942
18943    private int packageFlagsToInstallFlags(PackageSetting ps) {
18944        int installFlags = 0;
18945        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18946            // This existing package was an external ASEC install when we have
18947            // the external flag without a UUID
18948            installFlags |= PackageManager.INSTALL_EXTERNAL;
18949        }
18950        if (ps.isForwardLocked()) {
18951            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18952        }
18953        return installFlags;
18954    }
18955
18956    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18957        if (isExternal(pkg)) {
18958            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18959                return StorageManager.UUID_PRIMARY_PHYSICAL;
18960            } else {
18961                return pkg.volumeUuid;
18962            }
18963        } else {
18964            return StorageManager.UUID_PRIVATE_INTERNAL;
18965        }
18966    }
18967
18968    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18969        if (isExternal(pkg)) {
18970            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18971                return mSettings.getExternalVersion();
18972            } else {
18973                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18974            }
18975        } else {
18976            return mSettings.getInternalVersion();
18977        }
18978    }
18979
18980    private void deleteTempPackageFiles() {
18981        final FilenameFilter filter = new FilenameFilter() {
18982            public boolean accept(File dir, String name) {
18983                return name.startsWith("vmdl") && name.endsWith(".tmp");
18984            }
18985        };
18986        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18987            file.delete();
18988        }
18989    }
18990
18991    @Override
18992    public void deletePackageAsUser(String packageName, int versionCode,
18993            IPackageDeleteObserver observer, int userId, int flags) {
18994        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18995                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18996    }
18997
18998    @Override
18999    public void deletePackageVersioned(VersionedPackage versionedPackage,
19000            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19001        final int callingUid = Binder.getCallingUid();
19002        mContext.enforceCallingOrSelfPermission(
19003                android.Manifest.permission.DELETE_PACKAGES, null);
19004        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19005        Preconditions.checkNotNull(versionedPackage);
19006        Preconditions.checkNotNull(observer);
19007        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19008                PackageManager.VERSION_CODE_HIGHEST,
19009                Integer.MAX_VALUE, "versionCode must be >= -1");
19010
19011        final String packageName = versionedPackage.getPackageName();
19012        final int versionCode = versionedPackage.getVersionCode();
19013        final String internalPackageName;
19014        synchronized (mPackages) {
19015            // Normalize package name to handle renamed packages and static libs
19016            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19017                    versionedPackage.getVersionCode());
19018        }
19019
19020        final int uid = Binder.getCallingUid();
19021        if (!isOrphaned(internalPackageName)
19022                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19023            try {
19024                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19025                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19026                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19027                observer.onUserActionRequired(intent);
19028            } catch (RemoteException re) {
19029            }
19030            return;
19031        }
19032        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19033        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19034        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19035            mContext.enforceCallingOrSelfPermission(
19036                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19037                    "deletePackage for user " + userId);
19038        }
19039
19040        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19041            try {
19042                observer.onPackageDeleted(packageName,
19043                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19044            } catch (RemoteException re) {
19045            }
19046            return;
19047        }
19048
19049        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19050            try {
19051                observer.onPackageDeleted(packageName,
19052                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19053            } catch (RemoteException re) {
19054            }
19055            return;
19056        }
19057
19058        if (DEBUG_REMOVE) {
19059            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19060                    + " deleteAllUsers: " + deleteAllUsers + " version="
19061                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19062                    ? "VERSION_CODE_HIGHEST" : versionCode));
19063        }
19064        // Queue up an async operation since the package deletion may take a little while.
19065        mHandler.post(new Runnable() {
19066            public void run() {
19067                mHandler.removeCallbacks(this);
19068                int returnCode;
19069                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19070                boolean doDeletePackage = true;
19071                if (ps != null) {
19072                    final boolean targetIsInstantApp =
19073                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19074                    doDeletePackage = !targetIsInstantApp
19075                            || canViewInstantApps;
19076                }
19077                if (doDeletePackage) {
19078                    if (!deleteAllUsers) {
19079                        returnCode = deletePackageX(internalPackageName, versionCode,
19080                                userId, deleteFlags);
19081                    } else {
19082                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19083                                internalPackageName, users);
19084                        // If nobody is blocking uninstall, proceed with delete for all users
19085                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19086                            returnCode = deletePackageX(internalPackageName, versionCode,
19087                                    userId, deleteFlags);
19088                        } else {
19089                            // Otherwise uninstall individually for users with blockUninstalls=false
19090                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19091                            for (int userId : users) {
19092                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19093                                    returnCode = deletePackageX(internalPackageName, versionCode,
19094                                            userId, userFlags);
19095                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19096                                        Slog.w(TAG, "Package delete failed for user " + userId
19097                                                + ", returnCode " + returnCode);
19098                                    }
19099                                }
19100                            }
19101                            // The app has only been marked uninstalled for certain users.
19102                            // We still need to report that delete was blocked
19103                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19104                        }
19105                    }
19106                } else {
19107                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19108                }
19109                try {
19110                    observer.onPackageDeleted(packageName, returnCode, null);
19111                } catch (RemoteException e) {
19112                    Log.i(TAG, "Observer no longer exists.");
19113                } //end catch
19114            } //end run
19115        });
19116    }
19117
19118    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19119        if (pkg.staticSharedLibName != null) {
19120            return pkg.manifestPackageName;
19121        }
19122        return pkg.packageName;
19123    }
19124
19125    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19126        // Handle renamed packages
19127        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19128        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19129
19130        // Is this a static library?
19131        SparseArray<SharedLibraryEntry> versionedLib =
19132                mStaticLibsByDeclaringPackage.get(packageName);
19133        if (versionedLib == null || versionedLib.size() <= 0) {
19134            return packageName;
19135        }
19136
19137        // Figure out which lib versions the caller can see
19138        SparseIntArray versionsCallerCanSee = null;
19139        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19140        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19141                && callingAppId != Process.ROOT_UID) {
19142            versionsCallerCanSee = new SparseIntArray();
19143            String libName = versionedLib.valueAt(0).info.getName();
19144            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19145            if (uidPackages != null) {
19146                for (String uidPackage : uidPackages) {
19147                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19148                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19149                    if (libIdx >= 0) {
19150                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19151                        versionsCallerCanSee.append(libVersion, libVersion);
19152                    }
19153                }
19154            }
19155        }
19156
19157        // Caller can see nothing - done
19158        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19159            return packageName;
19160        }
19161
19162        // Find the version the caller can see and the app version code
19163        SharedLibraryEntry highestVersion = null;
19164        final int versionCount = versionedLib.size();
19165        for (int i = 0; i < versionCount; i++) {
19166            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19167            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19168                    libEntry.info.getVersion()) < 0) {
19169                continue;
19170            }
19171            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19172            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19173                if (libVersionCode == versionCode) {
19174                    return libEntry.apk;
19175                }
19176            } else if (highestVersion == null) {
19177                highestVersion = libEntry;
19178            } else if (libVersionCode  > highestVersion.info
19179                    .getDeclaringPackage().getVersionCode()) {
19180                highestVersion = libEntry;
19181            }
19182        }
19183
19184        if (highestVersion != null) {
19185            return highestVersion.apk;
19186        }
19187
19188        return packageName;
19189    }
19190
19191    boolean isCallerVerifier(int callingUid) {
19192        final int callingUserId = UserHandle.getUserId(callingUid);
19193        return mRequiredVerifierPackage != null &&
19194                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19195    }
19196
19197    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19198        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19199              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19200            return true;
19201        }
19202        final int callingUserId = UserHandle.getUserId(callingUid);
19203        // If the caller installed the pkgName, then allow it to silently uninstall.
19204        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19205            return true;
19206        }
19207
19208        // Allow package verifier to silently uninstall.
19209        if (mRequiredVerifierPackage != null &&
19210                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19211            return true;
19212        }
19213
19214        // Allow package uninstaller to silently uninstall.
19215        if (mRequiredUninstallerPackage != null &&
19216                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19217            return true;
19218        }
19219
19220        // Allow storage manager to silently uninstall.
19221        if (mStorageManagerPackage != null &&
19222                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19223            return true;
19224        }
19225
19226        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19227        // uninstall for device owner provisioning.
19228        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19229                == PERMISSION_GRANTED) {
19230            return true;
19231        }
19232
19233        return false;
19234    }
19235
19236    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19237        int[] result = EMPTY_INT_ARRAY;
19238        for (int userId : userIds) {
19239            if (getBlockUninstallForUser(packageName, userId)) {
19240                result = ArrayUtils.appendInt(result, userId);
19241            }
19242        }
19243        return result;
19244    }
19245
19246    @Override
19247    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19248        final int callingUid = Binder.getCallingUid();
19249        if (getInstantAppPackageName(callingUid) != null
19250                && !isCallerSameApp(packageName, callingUid)) {
19251            return false;
19252        }
19253        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19254    }
19255
19256    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19257        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19258                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19259        try {
19260            if (dpm != null) {
19261                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19262                        /* callingUserOnly =*/ false);
19263                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19264                        : deviceOwnerComponentName.getPackageName();
19265                // Does the package contains the device owner?
19266                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19267                // this check is probably not needed, since DO should be registered as a device
19268                // admin on some user too. (Original bug for this: b/17657954)
19269                if (packageName.equals(deviceOwnerPackageName)) {
19270                    return true;
19271                }
19272                // Does it contain a device admin for any user?
19273                int[] users;
19274                if (userId == UserHandle.USER_ALL) {
19275                    users = sUserManager.getUserIds();
19276                } else {
19277                    users = new int[]{userId};
19278                }
19279                for (int i = 0; i < users.length; ++i) {
19280                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19281                        return true;
19282                    }
19283                }
19284            }
19285        } catch (RemoteException e) {
19286        }
19287        return false;
19288    }
19289
19290    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19291        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19292    }
19293
19294    /**
19295     *  This method is an internal method that could be get invoked either
19296     *  to delete an installed package or to clean up a failed installation.
19297     *  After deleting an installed package, a broadcast is sent to notify any
19298     *  listeners that the package has been removed. For cleaning up a failed
19299     *  installation, the broadcast is not necessary since the package's
19300     *  installation wouldn't have sent the initial broadcast either
19301     *  The key steps in deleting a package are
19302     *  deleting the package information in internal structures like mPackages,
19303     *  deleting the packages base directories through installd
19304     *  updating mSettings to reflect current status
19305     *  persisting settings for later use
19306     *  sending a broadcast if necessary
19307     */
19308    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19309        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19310        final boolean res;
19311
19312        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19313                ? UserHandle.USER_ALL : userId;
19314
19315        if (isPackageDeviceAdmin(packageName, removeUser)) {
19316            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19317            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19318        }
19319
19320        PackageSetting uninstalledPs = null;
19321        PackageParser.Package pkg = null;
19322
19323        // for the uninstall-updates case and restricted profiles, remember the per-
19324        // user handle installed state
19325        int[] allUsers;
19326        synchronized (mPackages) {
19327            uninstalledPs = mSettings.mPackages.get(packageName);
19328            if (uninstalledPs == null) {
19329                Slog.w(TAG, "Not removing non-existent package " + packageName);
19330                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19331            }
19332
19333            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19334                    && uninstalledPs.versionCode != versionCode) {
19335                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19336                        + uninstalledPs.versionCode + " != " + versionCode);
19337                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19338            }
19339
19340            // Static shared libs can be declared by any package, so let us not
19341            // allow removing a package if it provides a lib others depend on.
19342            pkg = mPackages.get(packageName);
19343
19344            allUsers = sUserManager.getUserIds();
19345
19346            if (pkg != null && pkg.staticSharedLibName != null) {
19347                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19348                        pkg.staticSharedLibVersion);
19349                if (libEntry != null) {
19350                    for (int currUserId : allUsers) {
19351                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19352                            continue;
19353                        }
19354                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19355                                libEntry.info, 0, currUserId);
19356                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19357                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19358                                    + " hosting lib " + libEntry.info.getName() + " version "
19359                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19360                                    + " for user " + currUserId);
19361                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19362                        }
19363                    }
19364                }
19365            }
19366
19367            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19368        }
19369
19370        final int freezeUser;
19371        if (isUpdatedSystemApp(uninstalledPs)
19372                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19373            // We're downgrading a system app, which will apply to all users, so
19374            // freeze them all during the downgrade
19375            freezeUser = UserHandle.USER_ALL;
19376        } else {
19377            freezeUser = removeUser;
19378        }
19379
19380        synchronized (mInstallLock) {
19381            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19382            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19383                    deleteFlags, "deletePackageX")) {
19384                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19385                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19386            }
19387            synchronized (mPackages) {
19388                if (res) {
19389                    if (pkg != null) {
19390                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19391                    }
19392                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19393                    updateInstantAppInstallerLocked(packageName);
19394                }
19395            }
19396        }
19397
19398        if (res) {
19399            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19400            info.sendPackageRemovedBroadcasts(killApp);
19401            info.sendSystemPackageUpdatedBroadcasts();
19402            info.sendSystemPackageAppearedBroadcasts();
19403        }
19404        // Force a gc here.
19405        Runtime.getRuntime().gc();
19406        // Delete the resources here after sending the broadcast to let
19407        // other processes clean up before deleting resources.
19408        if (info.args != null) {
19409            synchronized (mInstallLock) {
19410                info.args.doPostDeleteLI(true);
19411            }
19412        }
19413
19414        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19415    }
19416
19417    static class PackageRemovedInfo {
19418        final PackageSender packageSender;
19419        String removedPackage;
19420        String installerPackageName;
19421        int uid = -1;
19422        int removedAppId = -1;
19423        int[] origUsers;
19424        int[] removedUsers = null;
19425        int[] broadcastUsers = null;
19426        SparseArray<Integer> installReasons;
19427        boolean isRemovedPackageSystemUpdate = false;
19428        boolean isUpdate;
19429        boolean dataRemoved;
19430        boolean removedForAllUsers;
19431        boolean isStaticSharedLib;
19432        // Clean up resources deleted packages.
19433        InstallArgs args = null;
19434        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19435        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19436
19437        PackageRemovedInfo(PackageSender packageSender) {
19438            this.packageSender = packageSender;
19439        }
19440
19441        void sendPackageRemovedBroadcasts(boolean killApp) {
19442            sendPackageRemovedBroadcastInternal(killApp);
19443            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19444            for (int i = 0; i < childCount; i++) {
19445                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19446                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19447            }
19448        }
19449
19450        void sendSystemPackageUpdatedBroadcasts() {
19451            if (isRemovedPackageSystemUpdate) {
19452                sendSystemPackageUpdatedBroadcastsInternal();
19453                final int childCount = (removedChildPackages != null)
19454                        ? removedChildPackages.size() : 0;
19455                for (int i = 0; i < childCount; i++) {
19456                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19457                    if (childInfo.isRemovedPackageSystemUpdate) {
19458                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19459                    }
19460                }
19461            }
19462        }
19463
19464        void sendSystemPackageAppearedBroadcasts() {
19465            final int packageCount = (appearedChildPackages != null)
19466                    ? appearedChildPackages.size() : 0;
19467            for (int i = 0; i < packageCount; i++) {
19468                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19469                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19470                    true /*sendBootCompleted*/, false /*startReceiver*/,
19471                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19472            }
19473        }
19474
19475        private void sendSystemPackageUpdatedBroadcastsInternal() {
19476            Bundle extras = new Bundle(2);
19477            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19478            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19479            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19480                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19481            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19482                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19483            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19484                null, null, 0, removedPackage, null, null);
19485            if (installerPackageName != null) {
19486                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19487                        removedPackage, extras, 0 /*flags*/,
19488                        installerPackageName, null, null);
19489                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19490                        removedPackage, extras, 0 /*flags*/,
19491                        installerPackageName, null, null);
19492            }
19493        }
19494
19495        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19496            // Don't send static shared library removal broadcasts as these
19497            // libs are visible only the the apps that depend on them an one
19498            // cannot remove the library if it has a dependency.
19499            if (isStaticSharedLib) {
19500                return;
19501            }
19502            Bundle extras = new Bundle(2);
19503            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19504            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19505            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19506            if (isUpdate || isRemovedPackageSystemUpdate) {
19507                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19508            }
19509            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19510            if (removedPackage != null) {
19511                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19512                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19513                if (installerPackageName != null) {
19514                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19515                            removedPackage, extras, 0 /*flags*/,
19516                            installerPackageName, null, broadcastUsers);
19517                }
19518                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19519                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19520                        removedPackage, extras,
19521                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19522                        null, null, broadcastUsers);
19523                }
19524            }
19525            if (removedAppId >= 0) {
19526                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19527                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19528                    null, null, broadcastUsers);
19529            }
19530        }
19531
19532        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19533            removedUsers = userIds;
19534            if (removedUsers == null) {
19535                broadcastUsers = null;
19536                return;
19537            }
19538
19539            broadcastUsers = EMPTY_INT_ARRAY;
19540            for (int i = userIds.length - 1; i >= 0; --i) {
19541                final int userId = userIds[i];
19542                if (deletedPackageSetting.getInstantApp(userId)) {
19543                    continue;
19544                }
19545                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19546            }
19547        }
19548    }
19549
19550    /*
19551     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19552     * flag is not set, the data directory is removed as well.
19553     * make sure this flag is set for partially installed apps. If not its meaningless to
19554     * delete a partially installed application.
19555     */
19556    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19557            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19558        String packageName = ps.name;
19559        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19560        // Retrieve object to delete permissions for shared user later on
19561        final PackageParser.Package deletedPkg;
19562        final PackageSetting deletedPs;
19563        // reader
19564        synchronized (mPackages) {
19565            deletedPkg = mPackages.get(packageName);
19566            deletedPs = mSettings.mPackages.get(packageName);
19567            if (outInfo != null) {
19568                outInfo.removedPackage = packageName;
19569                outInfo.installerPackageName = ps.installerPackageName;
19570                outInfo.isStaticSharedLib = deletedPkg != null
19571                        && deletedPkg.staticSharedLibName != null;
19572                outInfo.populateUsers(deletedPs == null ? null
19573                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19574            }
19575        }
19576
19577        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19578
19579        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19580            final PackageParser.Package resolvedPkg;
19581            if (deletedPkg != null) {
19582                resolvedPkg = deletedPkg;
19583            } else {
19584                // We don't have a parsed package when it lives on an ejected
19585                // adopted storage device, so fake something together
19586                resolvedPkg = new PackageParser.Package(ps.name);
19587                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19588            }
19589            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19590                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19591            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19592            if (outInfo != null) {
19593                outInfo.dataRemoved = true;
19594            }
19595            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19596        }
19597
19598        int removedAppId = -1;
19599
19600        // writer
19601        synchronized (mPackages) {
19602            boolean installedStateChanged = false;
19603            if (deletedPs != null) {
19604                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19605                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19606                    clearDefaultBrowserIfNeeded(packageName);
19607                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19608                    removedAppId = mSettings.removePackageLPw(packageName);
19609                    if (outInfo != null) {
19610                        outInfo.removedAppId = removedAppId;
19611                    }
19612                    updatePermissionsLPw(deletedPs.name, null, 0);
19613                    if (deletedPs.sharedUser != null) {
19614                        // Remove permissions associated with package. Since runtime
19615                        // permissions are per user we have to kill the removed package
19616                        // or packages running under the shared user of the removed
19617                        // package if revoking the permissions requested only by the removed
19618                        // package is successful and this causes a change in gids.
19619                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19620                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19621                                    userId);
19622                            if (userIdToKill == UserHandle.USER_ALL
19623                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19624                                // If gids changed for this user, kill all affected packages.
19625                                mHandler.post(new Runnable() {
19626                                    @Override
19627                                    public void run() {
19628                                        // This has to happen with no lock held.
19629                                        killApplication(deletedPs.name, deletedPs.appId,
19630                                                KILL_APP_REASON_GIDS_CHANGED);
19631                                    }
19632                                });
19633                                break;
19634                            }
19635                        }
19636                    }
19637                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19638                }
19639                // make sure to preserve per-user disabled state if this removal was just
19640                // a downgrade of a system app to the factory package
19641                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19642                    if (DEBUG_REMOVE) {
19643                        Slog.d(TAG, "Propagating install state across downgrade");
19644                    }
19645                    for (int userId : allUserHandles) {
19646                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19647                        if (DEBUG_REMOVE) {
19648                            Slog.d(TAG, "    user " + userId + " => " + installed);
19649                        }
19650                        if (installed != ps.getInstalled(userId)) {
19651                            installedStateChanged = true;
19652                        }
19653                        ps.setInstalled(installed, userId);
19654                    }
19655                }
19656            }
19657            // can downgrade to reader
19658            if (writeSettings) {
19659                // Save settings now
19660                mSettings.writeLPr();
19661            }
19662            if (installedStateChanged) {
19663                mSettings.writeKernelMappingLPr(ps);
19664            }
19665        }
19666        if (removedAppId != -1) {
19667            // A user ID was deleted here. Go through all users and remove it
19668            // from KeyStore.
19669            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19670        }
19671    }
19672
19673    static boolean locationIsPrivileged(File path) {
19674        try {
19675            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19676                    .getCanonicalPath();
19677            return path.getCanonicalPath().startsWith(privilegedAppDir);
19678        } catch (IOException e) {
19679            Slog.e(TAG, "Unable to access code path " + path);
19680        }
19681        return false;
19682    }
19683
19684    /*
19685     * Tries to delete system package.
19686     */
19687    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19688            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19689            boolean writeSettings) {
19690        if (deletedPs.parentPackageName != null) {
19691            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19692            return false;
19693        }
19694
19695        final boolean applyUserRestrictions
19696                = (allUserHandles != null) && (outInfo.origUsers != null);
19697        final PackageSetting disabledPs;
19698        // Confirm if the system package has been updated
19699        // An updated system app can be deleted. This will also have to restore
19700        // the system pkg from system partition
19701        // reader
19702        synchronized (mPackages) {
19703            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19704        }
19705
19706        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19707                + " disabledPs=" + disabledPs);
19708
19709        if (disabledPs == null) {
19710            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19711            return false;
19712        } else if (DEBUG_REMOVE) {
19713            Slog.d(TAG, "Deleting system pkg from data partition");
19714        }
19715
19716        if (DEBUG_REMOVE) {
19717            if (applyUserRestrictions) {
19718                Slog.d(TAG, "Remembering install states:");
19719                for (int userId : allUserHandles) {
19720                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19721                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19722                }
19723            }
19724        }
19725
19726        // Delete the updated package
19727        outInfo.isRemovedPackageSystemUpdate = true;
19728        if (outInfo.removedChildPackages != null) {
19729            final int childCount = (deletedPs.childPackageNames != null)
19730                    ? deletedPs.childPackageNames.size() : 0;
19731            for (int i = 0; i < childCount; i++) {
19732                String childPackageName = deletedPs.childPackageNames.get(i);
19733                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19734                        .contains(childPackageName)) {
19735                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19736                            childPackageName);
19737                    if (childInfo != null) {
19738                        childInfo.isRemovedPackageSystemUpdate = true;
19739                    }
19740                }
19741            }
19742        }
19743
19744        if (disabledPs.versionCode < deletedPs.versionCode) {
19745            // Delete data for downgrades
19746            flags &= ~PackageManager.DELETE_KEEP_DATA;
19747        } else {
19748            // Preserve data by setting flag
19749            flags |= PackageManager.DELETE_KEEP_DATA;
19750        }
19751
19752        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19753                outInfo, writeSettings, disabledPs.pkg);
19754        if (!ret) {
19755            return false;
19756        }
19757
19758        // writer
19759        synchronized (mPackages) {
19760            // Reinstate the old system package
19761            enableSystemPackageLPw(disabledPs.pkg);
19762            // Remove any native libraries from the upgraded package.
19763            removeNativeBinariesLI(deletedPs);
19764        }
19765
19766        // Install the system package
19767        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19768        int parseFlags = mDefParseFlags
19769                | PackageParser.PARSE_MUST_BE_APK
19770                | PackageParser.PARSE_IS_SYSTEM
19771                | PackageParser.PARSE_IS_SYSTEM_DIR;
19772        if (locationIsPrivileged(disabledPs.codePath)) {
19773            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19774        }
19775
19776        final PackageParser.Package newPkg;
19777        try {
19778            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19779                0 /* currentTime */, null);
19780        } catch (PackageManagerException e) {
19781            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19782                    + e.getMessage());
19783            return false;
19784        }
19785
19786        try {
19787            // update shared libraries for the newly re-installed system package
19788            updateSharedLibrariesLPr(newPkg, null);
19789        } catch (PackageManagerException e) {
19790            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19791        }
19792
19793        prepareAppDataAfterInstallLIF(newPkg);
19794
19795        // writer
19796        synchronized (mPackages) {
19797            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19798
19799            // Propagate the permissions state as we do not want to drop on the floor
19800            // runtime permissions. The update permissions method below will take
19801            // care of removing obsolete permissions and grant install permissions.
19802            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19803            updatePermissionsLPw(newPkg.packageName, newPkg,
19804                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19805
19806            if (applyUserRestrictions) {
19807                boolean installedStateChanged = false;
19808                if (DEBUG_REMOVE) {
19809                    Slog.d(TAG, "Propagating install state across reinstall");
19810                }
19811                for (int userId : allUserHandles) {
19812                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19813                    if (DEBUG_REMOVE) {
19814                        Slog.d(TAG, "    user " + userId + " => " + installed);
19815                    }
19816                    if (installed != ps.getInstalled(userId)) {
19817                        installedStateChanged = true;
19818                    }
19819                    ps.setInstalled(installed, userId);
19820
19821                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19822                }
19823                // Regardless of writeSettings we need to ensure that this restriction
19824                // state propagation is persisted
19825                mSettings.writeAllUsersPackageRestrictionsLPr();
19826                if (installedStateChanged) {
19827                    mSettings.writeKernelMappingLPr(ps);
19828                }
19829            }
19830            // can downgrade to reader here
19831            if (writeSettings) {
19832                mSettings.writeLPr();
19833            }
19834        }
19835        return true;
19836    }
19837
19838    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19839            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19840            PackageRemovedInfo outInfo, boolean writeSettings,
19841            PackageParser.Package replacingPackage) {
19842        synchronized (mPackages) {
19843            if (outInfo != null) {
19844                outInfo.uid = ps.appId;
19845            }
19846
19847            if (outInfo != null && outInfo.removedChildPackages != null) {
19848                final int childCount = (ps.childPackageNames != null)
19849                        ? ps.childPackageNames.size() : 0;
19850                for (int i = 0; i < childCount; i++) {
19851                    String childPackageName = ps.childPackageNames.get(i);
19852                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19853                    if (childPs == null) {
19854                        return false;
19855                    }
19856                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19857                            childPackageName);
19858                    if (childInfo != null) {
19859                        childInfo.uid = childPs.appId;
19860                    }
19861                }
19862            }
19863        }
19864
19865        // Delete package data from internal structures and also remove data if flag is set
19866        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19867
19868        // Delete the child packages data
19869        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19870        for (int i = 0; i < childCount; i++) {
19871            PackageSetting childPs;
19872            synchronized (mPackages) {
19873                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19874            }
19875            if (childPs != null) {
19876                PackageRemovedInfo childOutInfo = (outInfo != null
19877                        && outInfo.removedChildPackages != null)
19878                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19879                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19880                        && (replacingPackage != null
19881                        && !replacingPackage.hasChildPackage(childPs.name))
19882                        ? flags & ~DELETE_KEEP_DATA : flags;
19883                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19884                        deleteFlags, writeSettings);
19885            }
19886        }
19887
19888        // Delete application code and resources only for parent packages
19889        if (ps.parentPackageName == null) {
19890            if (deleteCodeAndResources && (outInfo != null)) {
19891                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19892                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19893                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19894            }
19895        }
19896
19897        return true;
19898    }
19899
19900    @Override
19901    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19902            int userId) {
19903        mContext.enforceCallingOrSelfPermission(
19904                android.Manifest.permission.DELETE_PACKAGES, null);
19905        synchronized (mPackages) {
19906            // Cannot block uninstall of static shared libs as they are
19907            // considered a part of the using app (emulating static linking).
19908            // Also static libs are installed always on internal storage.
19909            PackageParser.Package pkg = mPackages.get(packageName);
19910            if (pkg != null && pkg.staticSharedLibName != null) {
19911                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19912                        + " providing static shared library: " + pkg.staticSharedLibName);
19913                return false;
19914            }
19915            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19916            mSettings.writePackageRestrictionsLPr(userId);
19917        }
19918        return true;
19919    }
19920
19921    @Override
19922    public boolean getBlockUninstallForUser(String packageName, int userId) {
19923        synchronized (mPackages) {
19924            final PackageSetting ps = mSettings.mPackages.get(packageName);
19925            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19926                return false;
19927            }
19928            return mSettings.getBlockUninstallLPr(userId, packageName);
19929        }
19930    }
19931
19932    @Override
19933    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19934        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19935        synchronized (mPackages) {
19936            PackageSetting ps = mSettings.mPackages.get(packageName);
19937            if (ps == null) {
19938                Log.w(TAG, "Package doesn't exist: " + packageName);
19939                return false;
19940            }
19941            if (systemUserApp) {
19942                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19943            } else {
19944                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19945            }
19946            mSettings.writeLPr();
19947        }
19948        return true;
19949    }
19950
19951    /*
19952     * This method handles package deletion in general
19953     */
19954    private boolean deletePackageLIF(String packageName, UserHandle user,
19955            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19956            PackageRemovedInfo outInfo, boolean writeSettings,
19957            PackageParser.Package replacingPackage) {
19958        if (packageName == null) {
19959            Slog.w(TAG, "Attempt to delete null packageName.");
19960            return false;
19961        }
19962
19963        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19964
19965        PackageSetting ps;
19966        synchronized (mPackages) {
19967            ps = mSettings.mPackages.get(packageName);
19968            if (ps == null) {
19969                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19970                return false;
19971            }
19972
19973            if (ps.parentPackageName != null && (!isSystemApp(ps)
19974                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19975                if (DEBUG_REMOVE) {
19976                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19977                            + ((user == null) ? UserHandle.USER_ALL : user));
19978                }
19979                final int removedUserId = (user != null) ? user.getIdentifier()
19980                        : UserHandle.USER_ALL;
19981                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19982                    return false;
19983                }
19984                markPackageUninstalledForUserLPw(ps, user);
19985                scheduleWritePackageRestrictionsLocked(user);
19986                return true;
19987            }
19988        }
19989
19990        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19991                && user.getIdentifier() != UserHandle.USER_ALL)) {
19992            // The caller is asking that the package only be deleted for a single
19993            // user.  To do this, we just mark its uninstalled state and delete
19994            // its data. If this is a system app, we only allow this to happen if
19995            // they have set the special DELETE_SYSTEM_APP which requests different
19996            // semantics than normal for uninstalling system apps.
19997            markPackageUninstalledForUserLPw(ps, user);
19998
19999            if (!isSystemApp(ps)) {
20000                // Do not uninstall the APK if an app should be cached
20001                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20002                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20003                    // Other user still have this package installed, so all
20004                    // we need to do is clear this user's data and save that
20005                    // it is uninstalled.
20006                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20007                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20008                        return false;
20009                    }
20010                    scheduleWritePackageRestrictionsLocked(user);
20011                    return true;
20012                } else {
20013                    // We need to set it back to 'installed' so the uninstall
20014                    // broadcasts will be sent correctly.
20015                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20016                    ps.setInstalled(true, user.getIdentifier());
20017                    mSettings.writeKernelMappingLPr(ps);
20018                }
20019            } else {
20020                // This is a system app, so we assume that the
20021                // other users still have this package installed, so all
20022                // we need to do is clear this user's data and save that
20023                // it is uninstalled.
20024                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20025                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20026                    return false;
20027                }
20028                scheduleWritePackageRestrictionsLocked(user);
20029                return true;
20030            }
20031        }
20032
20033        // If we are deleting a composite package for all users, keep track
20034        // of result for each child.
20035        if (ps.childPackageNames != null && outInfo != null) {
20036            synchronized (mPackages) {
20037                final int childCount = ps.childPackageNames.size();
20038                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20039                for (int i = 0; i < childCount; i++) {
20040                    String childPackageName = ps.childPackageNames.get(i);
20041                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20042                    childInfo.removedPackage = childPackageName;
20043                    childInfo.installerPackageName = ps.installerPackageName;
20044                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20045                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20046                    if (childPs != null) {
20047                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20048                    }
20049                }
20050            }
20051        }
20052
20053        boolean ret = false;
20054        if (isSystemApp(ps)) {
20055            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20056            // When an updated system application is deleted we delete the existing resources
20057            // as well and fall back to existing code in system partition
20058            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20059        } else {
20060            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20061            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20062                    outInfo, writeSettings, replacingPackage);
20063        }
20064
20065        // Take a note whether we deleted the package for all users
20066        if (outInfo != null) {
20067            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20068            if (outInfo.removedChildPackages != null) {
20069                synchronized (mPackages) {
20070                    final int childCount = outInfo.removedChildPackages.size();
20071                    for (int i = 0; i < childCount; i++) {
20072                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20073                        if (childInfo != null) {
20074                            childInfo.removedForAllUsers = mPackages.get(
20075                                    childInfo.removedPackage) == null;
20076                        }
20077                    }
20078                }
20079            }
20080            // If we uninstalled an update to a system app there may be some
20081            // child packages that appeared as they are declared in the system
20082            // app but were not declared in the update.
20083            if (isSystemApp(ps)) {
20084                synchronized (mPackages) {
20085                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20086                    final int childCount = (updatedPs.childPackageNames != null)
20087                            ? updatedPs.childPackageNames.size() : 0;
20088                    for (int i = 0; i < childCount; i++) {
20089                        String childPackageName = updatedPs.childPackageNames.get(i);
20090                        if (outInfo.removedChildPackages == null
20091                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20092                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20093                            if (childPs == null) {
20094                                continue;
20095                            }
20096                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20097                            installRes.name = childPackageName;
20098                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20099                            installRes.pkg = mPackages.get(childPackageName);
20100                            installRes.uid = childPs.pkg.applicationInfo.uid;
20101                            if (outInfo.appearedChildPackages == null) {
20102                                outInfo.appearedChildPackages = new ArrayMap<>();
20103                            }
20104                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20105                        }
20106                    }
20107                }
20108            }
20109        }
20110
20111        return ret;
20112    }
20113
20114    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20115        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20116                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20117        for (int nextUserId : userIds) {
20118            if (DEBUG_REMOVE) {
20119                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20120            }
20121            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20122                    false /*installed*/,
20123                    true /*stopped*/,
20124                    true /*notLaunched*/,
20125                    false /*hidden*/,
20126                    false /*suspended*/,
20127                    false /*instantApp*/,
20128                    false /*virtualPreload*/,
20129                    null /*lastDisableAppCaller*/,
20130                    null /*enabledComponents*/,
20131                    null /*disabledComponents*/,
20132                    ps.readUserState(nextUserId).domainVerificationStatus,
20133                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20134        }
20135        mSettings.writeKernelMappingLPr(ps);
20136    }
20137
20138    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20139            PackageRemovedInfo outInfo) {
20140        final PackageParser.Package pkg;
20141        synchronized (mPackages) {
20142            pkg = mPackages.get(ps.name);
20143        }
20144
20145        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20146                : new int[] {userId};
20147        for (int nextUserId : userIds) {
20148            if (DEBUG_REMOVE) {
20149                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20150                        + nextUserId);
20151            }
20152
20153            destroyAppDataLIF(pkg, userId,
20154                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20155            destroyAppProfilesLIF(pkg, userId);
20156            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20157            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20158            schedulePackageCleaning(ps.name, nextUserId, false);
20159            synchronized (mPackages) {
20160                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20161                    scheduleWritePackageRestrictionsLocked(nextUserId);
20162                }
20163                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20164            }
20165        }
20166
20167        if (outInfo != null) {
20168            outInfo.removedPackage = ps.name;
20169            outInfo.installerPackageName = ps.installerPackageName;
20170            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20171            outInfo.removedAppId = ps.appId;
20172            outInfo.removedUsers = userIds;
20173            outInfo.broadcastUsers = userIds;
20174        }
20175
20176        return true;
20177    }
20178
20179    private final class ClearStorageConnection implements ServiceConnection {
20180        IMediaContainerService mContainerService;
20181
20182        @Override
20183        public void onServiceConnected(ComponentName name, IBinder service) {
20184            synchronized (this) {
20185                mContainerService = IMediaContainerService.Stub
20186                        .asInterface(Binder.allowBlocking(service));
20187                notifyAll();
20188            }
20189        }
20190
20191        @Override
20192        public void onServiceDisconnected(ComponentName name) {
20193        }
20194    }
20195
20196    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20197        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20198
20199        final boolean mounted;
20200        if (Environment.isExternalStorageEmulated()) {
20201            mounted = true;
20202        } else {
20203            final String status = Environment.getExternalStorageState();
20204
20205            mounted = status.equals(Environment.MEDIA_MOUNTED)
20206                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20207        }
20208
20209        if (!mounted) {
20210            return;
20211        }
20212
20213        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20214        int[] users;
20215        if (userId == UserHandle.USER_ALL) {
20216            users = sUserManager.getUserIds();
20217        } else {
20218            users = new int[] { userId };
20219        }
20220        final ClearStorageConnection conn = new ClearStorageConnection();
20221        if (mContext.bindServiceAsUser(
20222                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20223            try {
20224                for (int curUser : users) {
20225                    long timeout = SystemClock.uptimeMillis() + 5000;
20226                    synchronized (conn) {
20227                        long now;
20228                        while (conn.mContainerService == null &&
20229                                (now = SystemClock.uptimeMillis()) < timeout) {
20230                            try {
20231                                conn.wait(timeout - now);
20232                            } catch (InterruptedException e) {
20233                            }
20234                        }
20235                    }
20236                    if (conn.mContainerService == null) {
20237                        return;
20238                    }
20239
20240                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20241                    clearDirectory(conn.mContainerService,
20242                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20243                    if (allData) {
20244                        clearDirectory(conn.mContainerService,
20245                                userEnv.buildExternalStorageAppDataDirs(packageName));
20246                        clearDirectory(conn.mContainerService,
20247                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20248                    }
20249                }
20250            } finally {
20251                mContext.unbindService(conn);
20252            }
20253        }
20254    }
20255
20256    @Override
20257    public void clearApplicationProfileData(String packageName) {
20258        enforceSystemOrRoot("Only the system can clear all profile data");
20259
20260        final PackageParser.Package pkg;
20261        synchronized (mPackages) {
20262            pkg = mPackages.get(packageName);
20263        }
20264
20265        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20266            synchronized (mInstallLock) {
20267                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20268            }
20269        }
20270    }
20271
20272    @Override
20273    public void clearApplicationUserData(final String packageName,
20274            final IPackageDataObserver observer, final int userId) {
20275        mContext.enforceCallingOrSelfPermission(
20276                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20277
20278        final int callingUid = Binder.getCallingUid();
20279        enforceCrossUserPermission(callingUid, userId,
20280                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20281
20282        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20283        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20284        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20285            throw new SecurityException("Cannot clear data for a protected package: "
20286                    + packageName);
20287        }
20288        // Queue up an async operation since the package deletion may take a little while.
20289        mHandler.post(new Runnable() {
20290            public void run() {
20291                mHandler.removeCallbacks(this);
20292                final boolean succeeded;
20293                if (!filterApp) {
20294                    try (PackageFreezer freezer = freezePackage(packageName,
20295                            "clearApplicationUserData")) {
20296                        synchronized (mInstallLock) {
20297                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20298                        }
20299                        clearExternalStorageDataSync(packageName, userId, true);
20300                        synchronized (mPackages) {
20301                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20302                                    packageName, userId);
20303                        }
20304                    }
20305                    if (succeeded) {
20306                        // invoke DeviceStorageMonitor's update method to clear any notifications
20307                        DeviceStorageMonitorInternal dsm = LocalServices
20308                                .getService(DeviceStorageMonitorInternal.class);
20309                        if (dsm != null) {
20310                            dsm.checkMemory();
20311                        }
20312                    }
20313                } else {
20314                    succeeded = false;
20315                }
20316                if (observer != null) {
20317                    try {
20318                        observer.onRemoveCompleted(packageName, succeeded);
20319                    } catch (RemoteException e) {
20320                        Log.i(TAG, "Observer no longer exists.");
20321                    }
20322                } //end if observer
20323            } //end run
20324        });
20325    }
20326
20327    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20328        if (packageName == null) {
20329            Slog.w(TAG, "Attempt to delete null packageName.");
20330            return false;
20331        }
20332
20333        // Try finding details about the requested package
20334        PackageParser.Package pkg;
20335        synchronized (mPackages) {
20336            pkg = mPackages.get(packageName);
20337            if (pkg == null) {
20338                final PackageSetting ps = mSettings.mPackages.get(packageName);
20339                if (ps != null) {
20340                    pkg = ps.pkg;
20341                }
20342            }
20343
20344            if (pkg == null) {
20345                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20346                return false;
20347            }
20348
20349            PackageSetting ps = (PackageSetting) pkg.mExtras;
20350            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20351        }
20352
20353        clearAppDataLIF(pkg, userId,
20354                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20355
20356        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20357        removeKeystoreDataIfNeeded(userId, appId);
20358
20359        UserManagerInternal umInternal = getUserManagerInternal();
20360        final int flags;
20361        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20362            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20363        } else if (umInternal.isUserRunning(userId)) {
20364            flags = StorageManager.FLAG_STORAGE_DE;
20365        } else {
20366            flags = 0;
20367        }
20368        prepareAppDataContentsLIF(pkg, userId, flags);
20369
20370        return true;
20371    }
20372
20373    /**
20374     * Reverts user permission state changes (permissions and flags) in
20375     * all packages for a given user.
20376     *
20377     * @param userId The device user for which to do a reset.
20378     */
20379    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20380        final int packageCount = mPackages.size();
20381        for (int i = 0; i < packageCount; i++) {
20382            PackageParser.Package pkg = mPackages.valueAt(i);
20383            PackageSetting ps = (PackageSetting) pkg.mExtras;
20384            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20385        }
20386    }
20387
20388    private void resetNetworkPolicies(int userId) {
20389        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20390    }
20391
20392    /**
20393     * Reverts user permission state changes (permissions and flags).
20394     *
20395     * @param ps The package for which to reset.
20396     * @param userId The device user for which to do a reset.
20397     */
20398    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20399            final PackageSetting ps, final int userId) {
20400        if (ps.pkg == null) {
20401            return;
20402        }
20403
20404        // These are flags that can change base on user actions.
20405        final int userSettableMask = FLAG_PERMISSION_USER_SET
20406                | FLAG_PERMISSION_USER_FIXED
20407                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20408                | FLAG_PERMISSION_REVIEW_REQUIRED;
20409
20410        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20411                | FLAG_PERMISSION_POLICY_FIXED;
20412
20413        boolean writeInstallPermissions = false;
20414        boolean writeRuntimePermissions = false;
20415
20416        final int permissionCount = ps.pkg.requestedPermissions.size();
20417        for (int i = 0; i < permissionCount; i++) {
20418            String permission = ps.pkg.requestedPermissions.get(i);
20419
20420            BasePermission bp = mSettings.mPermissions.get(permission);
20421            if (bp == null) {
20422                continue;
20423            }
20424
20425            // If shared user we just reset the state to which only this app contributed.
20426            if (ps.sharedUser != null) {
20427                boolean used = false;
20428                final int packageCount = ps.sharedUser.packages.size();
20429                for (int j = 0; j < packageCount; j++) {
20430                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20431                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20432                            && pkg.pkg.requestedPermissions.contains(permission)) {
20433                        used = true;
20434                        break;
20435                    }
20436                }
20437                if (used) {
20438                    continue;
20439                }
20440            }
20441
20442            PermissionsState permissionsState = ps.getPermissionsState();
20443
20444            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20445
20446            // Always clear the user settable flags.
20447            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20448                    bp.name) != null;
20449            // If permission review is enabled and this is a legacy app, mark the
20450            // permission as requiring a review as this is the initial state.
20451            int flags = 0;
20452            if (mPermissionReviewRequired
20453                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20454                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20455            }
20456            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20457                if (hasInstallState) {
20458                    writeInstallPermissions = true;
20459                } else {
20460                    writeRuntimePermissions = true;
20461                }
20462            }
20463
20464            // Below is only runtime permission handling.
20465            if (!bp.isRuntime()) {
20466                continue;
20467            }
20468
20469            // Never clobber system or policy.
20470            if ((oldFlags & policyOrSystemFlags) != 0) {
20471                continue;
20472            }
20473
20474            // If this permission was granted by default, make sure it is.
20475            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20476                if (permissionsState.grantRuntimePermission(bp, userId)
20477                        != PERMISSION_OPERATION_FAILURE) {
20478                    writeRuntimePermissions = true;
20479                }
20480            // If permission review is enabled the permissions for a legacy apps
20481            // are represented as constantly granted runtime ones, so don't revoke.
20482            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20483                // Otherwise, reset the permission.
20484                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20485                switch (revokeResult) {
20486                    case PERMISSION_OPERATION_SUCCESS:
20487                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20488                        writeRuntimePermissions = true;
20489                        final int appId = ps.appId;
20490                        mHandler.post(new Runnable() {
20491                            @Override
20492                            public void run() {
20493                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20494                            }
20495                        });
20496                    } break;
20497                }
20498            }
20499        }
20500
20501        // Synchronously write as we are taking permissions away.
20502        if (writeRuntimePermissions) {
20503            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20504        }
20505
20506        // Synchronously write as we are taking permissions away.
20507        if (writeInstallPermissions) {
20508            mSettings.writeLPr();
20509        }
20510    }
20511
20512    /**
20513     * Remove entries from the keystore daemon. Will only remove it if the
20514     * {@code appId} is valid.
20515     */
20516    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20517        if (appId < 0) {
20518            return;
20519        }
20520
20521        final KeyStore keyStore = KeyStore.getInstance();
20522        if (keyStore != null) {
20523            if (userId == UserHandle.USER_ALL) {
20524                for (final int individual : sUserManager.getUserIds()) {
20525                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20526                }
20527            } else {
20528                keyStore.clearUid(UserHandle.getUid(userId, appId));
20529            }
20530        } else {
20531            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20532        }
20533    }
20534
20535    @Override
20536    public void deleteApplicationCacheFiles(final String packageName,
20537            final IPackageDataObserver observer) {
20538        final int userId = UserHandle.getCallingUserId();
20539        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20540    }
20541
20542    @Override
20543    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20544            final IPackageDataObserver observer) {
20545        final int callingUid = Binder.getCallingUid();
20546        mContext.enforceCallingOrSelfPermission(
20547                android.Manifest.permission.DELETE_CACHE_FILES, null);
20548        enforceCrossUserPermission(callingUid, userId,
20549                /* requireFullPermission= */ true, /* checkShell= */ false,
20550                "delete application cache files");
20551        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20552                android.Manifest.permission.ACCESS_INSTANT_APPS);
20553
20554        final PackageParser.Package pkg;
20555        synchronized (mPackages) {
20556            pkg = mPackages.get(packageName);
20557        }
20558
20559        // Queue up an async operation since the package deletion may take a little while.
20560        mHandler.post(new Runnable() {
20561            public void run() {
20562                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20563                boolean doClearData = true;
20564                if (ps != null) {
20565                    final boolean targetIsInstantApp =
20566                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20567                    doClearData = !targetIsInstantApp
20568                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20569                }
20570                if (doClearData) {
20571                    synchronized (mInstallLock) {
20572                        final int flags = StorageManager.FLAG_STORAGE_DE
20573                                | StorageManager.FLAG_STORAGE_CE;
20574                        // We're only clearing cache files, so we don't care if the
20575                        // app is unfrozen and still able to run
20576                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20577                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20578                    }
20579                    clearExternalStorageDataSync(packageName, userId, false);
20580                }
20581                if (observer != null) {
20582                    try {
20583                        observer.onRemoveCompleted(packageName, true);
20584                    } catch (RemoteException e) {
20585                        Log.i(TAG, "Observer no longer exists.");
20586                    }
20587                }
20588            }
20589        });
20590    }
20591
20592    @Override
20593    public void getPackageSizeInfo(final String packageName, int userHandle,
20594            final IPackageStatsObserver observer) {
20595        throw new UnsupportedOperationException(
20596                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20597    }
20598
20599    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20600        final PackageSetting ps;
20601        synchronized (mPackages) {
20602            ps = mSettings.mPackages.get(packageName);
20603            if (ps == null) {
20604                Slog.w(TAG, "Failed to find settings for " + packageName);
20605                return false;
20606            }
20607        }
20608
20609        final String[] packageNames = { packageName };
20610        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20611        final String[] codePaths = { ps.codePathString };
20612
20613        try {
20614            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20615                    ps.appId, ceDataInodes, codePaths, stats);
20616
20617            // For now, ignore code size of packages on system partition
20618            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20619                stats.codeSize = 0;
20620            }
20621
20622            // External clients expect these to be tracked separately
20623            stats.dataSize -= stats.cacheSize;
20624
20625        } catch (InstallerException e) {
20626            Slog.w(TAG, String.valueOf(e));
20627            return false;
20628        }
20629
20630        return true;
20631    }
20632
20633    private int getUidTargetSdkVersionLockedLPr(int uid) {
20634        Object obj = mSettings.getUserIdLPr(uid);
20635        if (obj instanceof SharedUserSetting) {
20636            final SharedUserSetting sus = (SharedUserSetting) obj;
20637            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20638            final Iterator<PackageSetting> it = sus.packages.iterator();
20639            while (it.hasNext()) {
20640                final PackageSetting ps = it.next();
20641                if (ps.pkg != null) {
20642                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20643                    if (v < vers) vers = v;
20644                }
20645            }
20646            return vers;
20647        } else if (obj instanceof PackageSetting) {
20648            final PackageSetting ps = (PackageSetting) obj;
20649            if (ps.pkg != null) {
20650                return ps.pkg.applicationInfo.targetSdkVersion;
20651            }
20652        }
20653        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20654    }
20655
20656    @Override
20657    public void addPreferredActivity(IntentFilter filter, int match,
20658            ComponentName[] set, ComponentName activity, int userId) {
20659        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20660                "Adding preferred");
20661    }
20662
20663    private void addPreferredActivityInternal(IntentFilter filter, int match,
20664            ComponentName[] set, ComponentName activity, boolean always, int userId,
20665            String opname) {
20666        // writer
20667        int callingUid = Binder.getCallingUid();
20668        enforceCrossUserPermission(callingUid, userId,
20669                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20670        if (filter.countActions() == 0) {
20671            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20672            return;
20673        }
20674        synchronized (mPackages) {
20675            if (mContext.checkCallingOrSelfPermission(
20676                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20677                    != PackageManager.PERMISSION_GRANTED) {
20678                if (getUidTargetSdkVersionLockedLPr(callingUid)
20679                        < Build.VERSION_CODES.FROYO) {
20680                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20681                            + callingUid);
20682                    return;
20683                }
20684                mContext.enforceCallingOrSelfPermission(
20685                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20686            }
20687
20688            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20689            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20690                    + userId + ":");
20691            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20692            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20693            scheduleWritePackageRestrictionsLocked(userId);
20694            postPreferredActivityChangedBroadcast(userId);
20695        }
20696    }
20697
20698    private void postPreferredActivityChangedBroadcast(int userId) {
20699        mHandler.post(() -> {
20700            final IActivityManager am = ActivityManager.getService();
20701            if (am == null) {
20702                return;
20703            }
20704
20705            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20706            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20707            try {
20708                am.broadcastIntent(null, intent, null, null,
20709                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20710                        null, false, false, userId);
20711            } catch (RemoteException e) {
20712            }
20713        });
20714    }
20715
20716    @Override
20717    public void replacePreferredActivity(IntentFilter filter, int match,
20718            ComponentName[] set, ComponentName activity, int userId) {
20719        if (filter.countActions() != 1) {
20720            throw new IllegalArgumentException(
20721                    "replacePreferredActivity expects filter to have only 1 action.");
20722        }
20723        if (filter.countDataAuthorities() != 0
20724                || filter.countDataPaths() != 0
20725                || filter.countDataSchemes() > 1
20726                || filter.countDataTypes() != 0) {
20727            throw new IllegalArgumentException(
20728                    "replacePreferredActivity expects filter to have no data authorities, " +
20729                    "paths, or types; and at most one scheme.");
20730        }
20731
20732        final int callingUid = Binder.getCallingUid();
20733        enforceCrossUserPermission(callingUid, userId,
20734                true /* requireFullPermission */, false /* checkShell */,
20735                "replace preferred activity");
20736        synchronized (mPackages) {
20737            if (mContext.checkCallingOrSelfPermission(
20738                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20739                    != PackageManager.PERMISSION_GRANTED) {
20740                if (getUidTargetSdkVersionLockedLPr(callingUid)
20741                        < Build.VERSION_CODES.FROYO) {
20742                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20743                            + Binder.getCallingUid());
20744                    return;
20745                }
20746                mContext.enforceCallingOrSelfPermission(
20747                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20748            }
20749
20750            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20751            if (pir != null) {
20752                // Get all of the existing entries that exactly match this filter.
20753                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20754                if (existing != null && existing.size() == 1) {
20755                    PreferredActivity cur = existing.get(0);
20756                    if (DEBUG_PREFERRED) {
20757                        Slog.i(TAG, "Checking replace of preferred:");
20758                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20759                        if (!cur.mPref.mAlways) {
20760                            Slog.i(TAG, "  -- CUR; not mAlways!");
20761                        } else {
20762                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20763                            Slog.i(TAG, "  -- CUR: mSet="
20764                                    + Arrays.toString(cur.mPref.mSetComponents));
20765                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20766                            Slog.i(TAG, "  -- NEW: mMatch="
20767                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20768                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20769                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20770                        }
20771                    }
20772                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20773                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20774                            && cur.mPref.sameSet(set)) {
20775                        // Setting the preferred activity to what it happens to be already
20776                        if (DEBUG_PREFERRED) {
20777                            Slog.i(TAG, "Replacing with same preferred activity "
20778                                    + cur.mPref.mShortComponent + " for user "
20779                                    + userId + ":");
20780                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20781                        }
20782                        return;
20783                    }
20784                }
20785
20786                if (existing != null) {
20787                    if (DEBUG_PREFERRED) {
20788                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20789                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20790                    }
20791                    for (int i = 0; i < existing.size(); i++) {
20792                        PreferredActivity pa = existing.get(i);
20793                        if (DEBUG_PREFERRED) {
20794                            Slog.i(TAG, "Removing existing preferred activity "
20795                                    + pa.mPref.mComponent + ":");
20796                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20797                        }
20798                        pir.removeFilter(pa);
20799                    }
20800                }
20801            }
20802            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20803                    "Replacing preferred");
20804        }
20805    }
20806
20807    @Override
20808    public void clearPackagePreferredActivities(String packageName) {
20809        final int callingUid = Binder.getCallingUid();
20810        if (getInstantAppPackageName(callingUid) != null) {
20811            return;
20812        }
20813        // writer
20814        synchronized (mPackages) {
20815            PackageParser.Package pkg = mPackages.get(packageName);
20816            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20817                if (mContext.checkCallingOrSelfPermission(
20818                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20819                        != PackageManager.PERMISSION_GRANTED) {
20820                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20821                            < Build.VERSION_CODES.FROYO) {
20822                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20823                                + callingUid);
20824                        return;
20825                    }
20826                    mContext.enforceCallingOrSelfPermission(
20827                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20828                }
20829            }
20830            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20831            if (ps != null
20832                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20833                return;
20834            }
20835            int user = UserHandle.getCallingUserId();
20836            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20837                scheduleWritePackageRestrictionsLocked(user);
20838            }
20839        }
20840    }
20841
20842    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20843    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20844        ArrayList<PreferredActivity> removed = null;
20845        boolean changed = false;
20846        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20847            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20848            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20849            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20850                continue;
20851            }
20852            Iterator<PreferredActivity> it = pir.filterIterator();
20853            while (it.hasNext()) {
20854                PreferredActivity pa = it.next();
20855                // Mark entry for removal only if it matches the package name
20856                // and the entry is of type "always".
20857                if (packageName == null ||
20858                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20859                                && pa.mPref.mAlways)) {
20860                    if (removed == null) {
20861                        removed = new ArrayList<PreferredActivity>();
20862                    }
20863                    removed.add(pa);
20864                }
20865            }
20866            if (removed != null) {
20867                for (int j=0; j<removed.size(); j++) {
20868                    PreferredActivity pa = removed.get(j);
20869                    pir.removeFilter(pa);
20870                }
20871                changed = true;
20872            }
20873        }
20874        if (changed) {
20875            postPreferredActivityChangedBroadcast(userId);
20876        }
20877        return changed;
20878    }
20879
20880    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20881    private void clearIntentFilterVerificationsLPw(int userId) {
20882        final int packageCount = mPackages.size();
20883        for (int i = 0; i < packageCount; i++) {
20884            PackageParser.Package pkg = mPackages.valueAt(i);
20885            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20886        }
20887    }
20888
20889    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20890    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20891        if (userId == UserHandle.USER_ALL) {
20892            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20893                    sUserManager.getUserIds())) {
20894                for (int oneUserId : sUserManager.getUserIds()) {
20895                    scheduleWritePackageRestrictionsLocked(oneUserId);
20896                }
20897            }
20898        } else {
20899            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20900                scheduleWritePackageRestrictionsLocked(userId);
20901            }
20902        }
20903    }
20904
20905    /** Clears state for all users, and touches intent filter verification policy */
20906    void clearDefaultBrowserIfNeeded(String packageName) {
20907        for (int oneUserId : sUserManager.getUserIds()) {
20908            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20909        }
20910    }
20911
20912    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20913        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20914        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20915            if (packageName.equals(defaultBrowserPackageName)) {
20916                setDefaultBrowserPackageName(null, userId);
20917            }
20918        }
20919    }
20920
20921    @Override
20922    public void resetApplicationPreferences(int userId) {
20923        mContext.enforceCallingOrSelfPermission(
20924                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20925        final long identity = Binder.clearCallingIdentity();
20926        // writer
20927        try {
20928            synchronized (mPackages) {
20929                clearPackagePreferredActivitiesLPw(null, userId);
20930                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20931                // TODO: We have to reset the default SMS and Phone. This requires
20932                // significant refactoring to keep all default apps in the package
20933                // manager (cleaner but more work) or have the services provide
20934                // callbacks to the package manager to request a default app reset.
20935                applyFactoryDefaultBrowserLPw(userId);
20936                clearIntentFilterVerificationsLPw(userId);
20937                primeDomainVerificationsLPw(userId);
20938                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20939                scheduleWritePackageRestrictionsLocked(userId);
20940            }
20941            resetNetworkPolicies(userId);
20942        } finally {
20943            Binder.restoreCallingIdentity(identity);
20944        }
20945    }
20946
20947    @Override
20948    public int getPreferredActivities(List<IntentFilter> outFilters,
20949            List<ComponentName> outActivities, String packageName) {
20950        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20951            return 0;
20952        }
20953        int num = 0;
20954        final int userId = UserHandle.getCallingUserId();
20955        // reader
20956        synchronized (mPackages) {
20957            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20958            if (pir != null) {
20959                final Iterator<PreferredActivity> it = pir.filterIterator();
20960                while (it.hasNext()) {
20961                    final PreferredActivity pa = it.next();
20962                    if (packageName == null
20963                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20964                                    && pa.mPref.mAlways)) {
20965                        if (outFilters != null) {
20966                            outFilters.add(new IntentFilter(pa));
20967                        }
20968                        if (outActivities != null) {
20969                            outActivities.add(pa.mPref.mComponent);
20970                        }
20971                    }
20972                }
20973            }
20974        }
20975
20976        return num;
20977    }
20978
20979    @Override
20980    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20981            int userId) {
20982        int callingUid = Binder.getCallingUid();
20983        if (callingUid != Process.SYSTEM_UID) {
20984            throw new SecurityException(
20985                    "addPersistentPreferredActivity can only be run by the system");
20986        }
20987        if (filter.countActions() == 0) {
20988            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20989            return;
20990        }
20991        synchronized (mPackages) {
20992            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20993                    ":");
20994            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20995            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20996                    new PersistentPreferredActivity(filter, activity));
20997            scheduleWritePackageRestrictionsLocked(userId);
20998            postPreferredActivityChangedBroadcast(userId);
20999        }
21000    }
21001
21002    @Override
21003    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21004        int callingUid = Binder.getCallingUid();
21005        if (callingUid != Process.SYSTEM_UID) {
21006            throw new SecurityException(
21007                    "clearPackagePersistentPreferredActivities can only be run by the system");
21008        }
21009        ArrayList<PersistentPreferredActivity> removed = null;
21010        boolean changed = false;
21011        synchronized (mPackages) {
21012            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21013                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21014                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21015                        .valueAt(i);
21016                if (userId != thisUserId) {
21017                    continue;
21018                }
21019                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21020                while (it.hasNext()) {
21021                    PersistentPreferredActivity ppa = it.next();
21022                    // Mark entry for removal only if it matches the package name.
21023                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21024                        if (removed == null) {
21025                            removed = new ArrayList<PersistentPreferredActivity>();
21026                        }
21027                        removed.add(ppa);
21028                    }
21029                }
21030                if (removed != null) {
21031                    for (int j=0; j<removed.size(); j++) {
21032                        PersistentPreferredActivity ppa = removed.get(j);
21033                        ppir.removeFilter(ppa);
21034                    }
21035                    changed = true;
21036                }
21037            }
21038
21039            if (changed) {
21040                scheduleWritePackageRestrictionsLocked(userId);
21041                postPreferredActivityChangedBroadcast(userId);
21042            }
21043        }
21044    }
21045
21046    /**
21047     * Common machinery for picking apart a restored XML blob and passing
21048     * it to a caller-supplied functor to be applied to the running system.
21049     */
21050    private void restoreFromXml(XmlPullParser parser, int userId,
21051            String expectedStartTag, BlobXmlRestorer functor)
21052            throws IOException, XmlPullParserException {
21053        int type;
21054        while ((type = parser.next()) != XmlPullParser.START_TAG
21055                && type != XmlPullParser.END_DOCUMENT) {
21056        }
21057        if (type != XmlPullParser.START_TAG) {
21058            // oops didn't find a start tag?!
21059            if (DEBUG_BACKUP) {
21060                Slog.e(TAG, "Didn't find start tag during restore");
21061            }
21062            return;
21063        }
21064Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21065        // this is supposed to be TAG_PREFERRED_BACKUP
21066        if (!expectedStartTag.equals(parser.getName())) {
21067            if (DEBUG_BACKUP) {
21068                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21069            }
21070            return;
21071        }
21072
21073        // skip interfering stuff, then we're aligned with the backing implementation
21074        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21075Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21076        functor.apply(parser, userId);
21077    }
21078
21079    private interface BlobXmlRestorer {
21080        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21081    }
21082
21083    /**
21084     * Non-Binder method, support for the backup/restore mechanism: write the
21085     * full set of preferred activities in its canonical XML format.  Returns the
21086     * XML output as a byte array, or null if there is none.
21087     */
21088    @Override
21089    public byte[] getPreferredActivityBackup(int userId) {
21090        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21091            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21092        }
21093
21094        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21095        try {
21096            final XmlSerializer serializer = new FastXmlSerializer();
21097            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21098            serializer.startDocument(null, true);
21099            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21100
21101            synchronized (mPackages) {
21102                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21103            }
21104
21105            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21106            serializer.endDocument();
21107            serializer.flush();
21108        } catch (Exception e) {
21109            if (DEBUG_BACKUP) {
21110                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21111            }
21112            return null;
21113        }
21114
21115        return dataStream.toByteArray();
21116    }
21117
21118    @Override
21119    public void restorePreferredActivities(byte[] backup, int userId) {
21120        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21121            throw new SecurityException("Only the system may call restorePreferredActivities()");
21122        }
21123
21124        try {
21125            final XmlPullParser parser = Xml.newPullParser();
21126            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21127            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21128                    new BlobXmlRestorer() {
21129                        @Override
21130                        public void apply(XmlPullParser parser, int userId)
21131                                throws XmlPullParserException, IOException {
21132                            synchronized (mPackages) {
21133                                mSettings.readPreferredActivitiesLPw(parser, userId);
21134                            }
21135                        }
21136                    } );
21137        } catch (Exception e) {
21138            if (DEBUG_BACKUP) {
21139                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21140            }
21141        }
21142    }
21143
21144    /**
21145     * Non-Binder method, support for the backup/restore mechanism: write the
21146     * default browser (etc) settings in its canonical XML format.  Returns the default
21147     * browser XML representation as a byte array, or null if there is none.
21148     */
21149    @Override
21150    public byte[] getDefaultAppsBackup(int userId) {
21151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21152            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21153        }
21154
21155        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21156        try {
21157            final XmlSerializer serializer = new FastXmlSerializer();
21158            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21159            serializer.startDocument(null, true);
21160            serializer.startTag(null, TAG_DEFAULT_APPS);
21161
21162            synchronized (mPackages) {
21163                mSettings.writeDefaultAppsLPr(serializer, userId);
21164            }
21165
21166            serializer.endTag(null, TAG_DEFAULT_APPS);
21167            serializer.endDocument();
21168            serializer.flush();
21169        } catch (Exception e) {
21170            if (DEBUG_BACKUP) {
21171                Slog.e(TAG, "Unable to write default apps for backup", e);
21172            }
21173            return null;
21174        }
21175
21176        return dataStream.toByteArray();
21177    }
21178
21179    @Override
21180    public void restoreDefaultApps(byte[] backup, int userId) {
21181        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21182            throw new SecurityException("Only the system may call restoreDefaultApps()");
21183        }
21184
21185        try {
21186            final XmlPullParser parser = Xml.newPullParser();
21187            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21188            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21189                    new BlobXmlRestorer() {
21190                        @Override
21191                        public void apply(XmlPullParser parser, int userId)
21192                                throws XmlPullParserException, IOException {
21193                            synchronized (mPackages) {
21194                                mSettings.readDefaultAppsLPw(parser, userId);
21195                            }
21196                        }
21197                    } );
21198        } catch (Exception e) {
21199            if (DEBUG_BACKUP) {
21200                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21201            }
21202        }
21203    }
21204
21205    @Override
21206    public byte[] getIntentFilterVerificationBackup(int userId) {
21207        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21208            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21209        }
21210
21211        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21212        try {
21213            final XmlSerializer serializer = new FastXmlSerializer();
21214            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21215            serializer.startDocument(null, true);
21216            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21217
21218            synchronized (mPackages) {
21219                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21220            }
21221
21222            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21223            serializer.endDocument();
21224            serializer.flush();
21225        } catch (Exception e) {
21226            if (DEBUG_BACKUP) {
21227                Slog.e(TAG, "Unable to write default apps for backup", e);
21228            }
21229            return null;
21230        }
21231
21232        return dataStream.toByteArray();
21233    }
21234
21235    @Override
21236    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21237        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21238            throw new SecurityException("Only the system may call restorePreferredActivities()");
21239        }
21240
21241        try {
21242            final XmlPullParser parser = Xml.newPullParser();
21243            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21244            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21245                    new BlobXmlRestorer() {
21246                        @Override
21247                        public void apply(XmlPullParser parser, int userId)
21248                                throws XmlPullParserException, IOException {
21249                            synchronized (mPackages) {
21250                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21251                                mSettings.writeLPr();
21252                            }
21253                        }
21254                    } );
21255        } catch (Exception e) {
21256            if (DEBUG_BACKUP) {
21257                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21258            }
21259        }
21260    }
21261
21262    @Override
21263    public byte[] getPermissionGrantBackup(int userId) {
21264        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21265            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21266        }
21267
21268        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21269        try {
21270            final XmlSerializer serializer = new FastXmlSerializer();
21271            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21272            serializer.startDocument(null, true);
21273            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21274
21275            synchronized (mPackages) {
21276                serializeRuntimePermissionGrantsLPr(serializer, userId);
21277            }
21278
21279            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21280            serializer.endDocument();
21281            serializer.flush();
21282        } catch (Exception e) {
21283            if (DEBUG_BACKUP) {
21284                Slog.e(TAG, "Unable to write default apps for backup", e);
21285            }
21286            return null;
21287        }
21288
21289        return dataStream.toByteArray();
21290    }
21291
21292    @Override
21293    public void restorePermissionGrants(byte[] backup, int userId) {
21294        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21295            throw new SecurityException("Only the system may call restorePermissionGrants()");
21296        }
21297
21298        try {
21299            final XmlPullParser parser = Xml.newPullParser();
21300            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21301            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21302                    new BlobXmlRestorer() {
21303                        @Override
21304                        public void apply(XmlPullParser parser, int userId)
21305                                throws XmlPullParserException, IOException {
21306                            synchronized (mPackages) {
21307                                processRestoredPermissionGrantsLPr(parser, userId);
21308                            }
21309                        }
21310                    } );
21311        } catch (Exception e) {
21312            if (DEBUG_BACKUP) {
21313                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21314            }
21315        }
21316    }
21317
21318    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21319            throws IOException {
21320        serializer.startTag(null, TAG_ALL_GRANTS);
21321
21322        final int N = mSettings.mPackages.size();
21323        for (int i = 0; i < N; i++) {
21324            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21325            boolean pkgGrantsKnown = false;
21326
21327            PermissionsState packagePerms = ps.getPermissionsState();
21328
21329            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21330                final int grantFlags = state.getFlags();
21331                // only look at grants that are not system/policy fixed
21332                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21333                    final boolean isGranted = state.isGranted();
21334                    // And only back up the user-twiddled state bits
21335                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21336                        final String packageName = mSettings.mPackages.keyAt(i);
21337                        if (!pkgGrantsKnown) {
21338                            serializer.startTag(null, TAG_GRANT);
21339                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21340                            pkgGrantsKnown = true;
21341                        }
21342
21343                        final boolean userSet =
21344                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21345                        final boolean userFixed =
21346                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21347                        final boolean revoke =
21348                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21349
21350                        serializer.startTag(null, TAG_PERMISSION);
21351                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21352                        if (isGranted) {
21353                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21354                        }
21355                        if (userSet) {
21356                            serializer.attribute(null, ATTR_USER_SET, "true");
21357                        }
21358                        if (userFixed) {
21359                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21360                        }
21361                        if (revoke) {
21362                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21363                        }
21364                        serializer.endTag(null, TAG_PERMISSION);
21365                    }
21366                }
21367            }
21368
21369            if (pkgGrantsKnown) {
21370                serializer.endTag(null, TAG_GRANT);
21371            }
21372        }
21373
21374        serializer.endTag(null, TAG_ALL_GRANTS);
21375    }
21376
21377    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21378            throws XmlPullParserException, IOException {
21379        String pkgName = null;
21380        int outerDepth = parser.getDepth();
21381        int type;
21382        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21383                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21384            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21385                continue;
21386            }
21387
21388            final String tagName = parser.getName();
21389            if (tagName.equals(TAG_GRANT)) {
21390                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21391                if (DEBUG_BACKUP) {
21392                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21393                }
21394            } else if (tagName.equals(TAG_PERMISSION)) {
21395
21396                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21397                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21398
21399                int newFlagSet = 0;
21400                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21401                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21402                }
21403                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21404                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21405                }
21406                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21407                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21408                }
21409                if (DEBUG_BACKUP) {
21410                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21411                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21412                }
21413                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21414                if (ps != null) {
21415                    // Already installed so we apply the grant immediately
21416                    if (DEBUG_BACKUP) {
21417                        Slog.v(TAG, "        + already installed; applying");
21418                    }
21419                    PermissionsState perms = ps.getPermissionsState();
21420                    BasePermission bp = mSettings.mPermissions.get(permName);
21421                    if (bp != null) {
21422                        if (isGranted) {
21423                            perms.grantRuntimePermission(bp, userId);
21424                        }
21425                        if (newFlagSet != 0) {
21426                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21427                        }
21428                    }
21429                } else {
21430                    // Need to wait for post-restore install to apply the grant
21431                    if (DEBUG_BACKUP) {
21432                        Slog.v(TAG, "        - not yet installed; saving for later");
21433                    }
21434                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21435                            isGranted, newFlagSet, userId);
21436                }
21437            } else {
21438                PackageManagerService.reportSettingsProblem(Log.WARN,
21439                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21440                XmlUtils.skipCurrentTag(parser);
21441            }
21442        }
21443
21444        scheduleWriteSettingsLocked();
21445        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21446    }
21447
21448    @Override
21449    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21450            int sourceUserId, int targetUserId, int flags) {
21451        mContext.enforceCallingOrSelfPermission(
21452                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21453        int callingUid = Binder.getCallingUid();
21454        enforceOwnerRights(ownerPackage, callingUid);
21455        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21456        if (intentFilter.countActions() == 0) {
21457            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21458            return;
21459        }
21460        synchronized (mPackages) {
21461            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21462                    ownerPackage, targetUserId, flags);
21463            CrossProfileIntentResolver resolver =
21464                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21465            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21466            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21467            if (existing != null) {
21468                int size = existing.size();
21469                for (int i = 0; i < size; i++) {
21470                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21471                        return;
21472                    }
21473                }
21474            }
21475            resolver.addFilter(newFilter);
21476            scheduleWritePackageRestrictionsLocked(sourceUserId);
21477        }
21478    }
21479
21480    @Override
21481    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21482        mContext.enforceCallingOrSelfPermission(
21483                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21484        final int callingUid = Binder.getCallingUid();
21485        enforceOwnerRights(ownerPackage, callingUid);
21486        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21487        synchronized (mPackages) {
21488            CrossProfileIntentResolver resolver =
21489                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21490            ArraySet<CrossProfileIntentFilter> set =
21491                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21492            for (CrossProfileIntentFilter filter : set) {
21493                if (filter.getOwnerPackage().equals(ownerPackage)) {
21494                    resolver.removeFilter(filter);
21495                }
21496            }
21497            scheduleWritePackageRestrictionsLocked(sourceUserId);
21498        }
21499    }
21500
21501    // Enforcing that callingUid is owning pkg on userId
21502    private void enforceOwnerRights(String pkg, int callingUid) {
21503        // The system owns everything.
21504        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21505            return;
21506        }
21507        final int callingUserId = UserHandle.getUserId(callingUid);
21508        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21509        if (pi == null) {
21510            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21511                    + callingUserId);
21512        }
21513        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21514            throw new SecurityException("Calling uid " + callingUid
21515                    + " does not own package " + pkg);
21516        }
21517    }
21518
21519    @Override
21520    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21521        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21522            return null;
21523        }
21524        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21525    }
21526
21527    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21528        UserManagerService ums = UserManagerService.getInstance();
21529        if (ums != null) {
21530            final UserInfo parent = ums.getProfileParent(userId);
21531            final int launcherUid = (parent != null) ? parent.id : userId;
21532            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21533            if (launcherComponent != null) {
21534                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21535                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21536                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21537                        .setPackage(launcherComponent.getPackageName());
21538                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21539            }
21540        }
21541    }
21542
21543    /**
21544     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21545     * then reports the most likely home activity or null if there are more than one.
21546     */
21547    private ComponentName getDefaultHomeActivity(int userId) {
21548        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21549        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21550        if (cn != null) {
21551            return cn;
21552        }
21553
21554        // Find the launcher with the highest priority and return that component if there are no
21555        // other home activity with the same priority.
21556        int lastPriority = Integer.MIN_VALUE;
21557        ComponentName lastComponent = null;
21558        final int size = allHomeCandidates.size();
21559        for (int i = 0; i < size; i++) {
21560            final ResolveInfo ri = allHomeCandidates.get(i);
21561            if (ri.priority > lastPriority) {
21562                lastComponent = ri.activityInfo.getComponentName();
21563                lastPriority = ri.priority;
21564            } else if (ri.priority == lastPriority) {
21565                // Two components found with same priority.
21566                lastComponent = null;
21567            }
21568        }
21569        return lastComponent;
21570    }
21571
21572    private Intent getHomeIntent() {
21573        Intent intent = new Intent(Intent.ACTION_MAIN);
21574        intent.addCategory(Intent.CATEGORY_HOME);
21575        intent.addCategory(Intent.CATEGORY_DEFAULT);
21576        return intent;
21577    }
21578
21579    private IntentFilter getHomeFilter() {
21580        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21581        filter.addCategory(Intent.CATEGORY_HOME);
21582        filter.addCategory(Intent.CATEGORY_DEFAULT);
21583        return filter;
21584    }
21585
21586    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21587            int userId) {
21588        Intent intent  = getHomeIntent();
21589        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21590                PackageManager.GET_META_DATA, userId);
21591        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21592                true, false, false, userId);
21593
21594        allHomeCandidates.clear();
21595        if (list != null) {
21596            for (ResolveInfo ri : list) {
21597                allHomeCandidates.add(ri);
21598            }
21599        }
21600        return (preferred == null || preferred.activityInfo == null)
21601                ? null
21602                : new ComponentName(preferred.activityInfo.packageName,
21603                        preferred.activityInfo.name);
21604    }
21605
21606    @Override
21607    public void setHomeActivity(ComponentName comp, int userId) {
21608        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21609            return;
21610        }
21611        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21612        getHomeActivitiesAsUser(homeActivities, userId);
21613
21614        boolean found = false;
21615
21616        final int size = homeActivities.size();
21617        final ComponentName[] set = new ComponentName[size];
21618        for (int i = 0; i < size; i++) {
21619            final ResolveInfo candidate = homeActivities.get(i);
21620            final ActivityInfo info = candidate.activityInfo;
21621            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21622            set[i] = activityName;
21623            if (!found && activityName.equals(comp)) {
21624                found = true;
21625            }
21626        }
21627        if (!found) {
21628            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21629                    + userId);
21630        }
21631        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21632                set, comp, userId);
21633    }
21634
21635    private @Nullable String getSetupWizardPackageName() {
21636        final Intent intent = new Intent(Intent.ACTION_MAIN);
21637        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21638
21639        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21640                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21641                        | MATCH_DISABLED_COMPONENTS,
21642                UserHandle.myUserId());
21643        if (matches.size() == 1) {
21644            return matches.get(0).getComponentInfo().packageName;
21645        } else {
21646            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21647                    + ": matches=" + matches);
21648            return null;
21649        }
21650    }
21651
21652    private @Nullable String getStorageManagerPackageName() {
21653        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21654
21655        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21656                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21657                        | MATCH_DISABLED_COMPONENTS,
21658                UserHandle.myUserId());
21659        if (matches.size() == 1) {
21660            return matches.get(0).getComponentInfo().packageName;
21661        } else {
21662            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21663                    + matches.size() + ": matches=" + matches);
21664            return null;
21665        }
21666    }
21667
21668    @Override
21669    public void setApplicationEnabledSetting(String appPackageName,
21670            int newState, int flags, int userId, String callingPackage) {
21671        if (!sUserManager.exists(userId)) return;
21672        if (callingPackage == null) {
21673            callingPackage = Integer.toString(Binder.getCallingUid());
21674        }
21675        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21676    }
21677
21678    @Override
21679    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21680        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21681        synchronized (mPackages) {
21682            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21683            if (pkgSetting != null) {
21684                pkgSetting.setUpdateAvailable(updateAvailable);
21685            }
21686        }
21687    }
21688
21689    @Override
21690    public void setComponentEnabledSetting(ComponentName componentName,
21691            int newState, int flags, int userId) {
21692        if (!sUserManager.exists(userId)) return;
21693        setEnabledSetting(componentName.getPackageName(),
21694                componentName.getClassName(), newState, flags, userId, null);
21695    }
21696
21697    private void setEnabledSetting(final String packageName, String className, int newState,
21698            final int flags, int userId, String callingPackage) {
21699        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21700              || newState == COMPONENT_ENABLED_STATE_ENABLED
21701              || newState == COMPONENT_ENABLED_STATE_DISABLED
21702              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21703              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21704            throw new IllegalArgumentException("Invalid new component state: "
21705                    + newState);
21706        }
21707        PackageSetting pkgSetting;
21708        final int callingUid = Binder.getCallingUid();
21709        final int permission;
21710        if (callingUid == Process.SYSTEM_UID) {
21711            permission = PackageManager.PERMISSION_GRANTED;
21712        } else {
21713            permission = mContext.checkCallingOrSelfPermission(
21714                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21715        }
21716        enforceCrossUserPermission(callingUid, userId,
21717                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21718        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21719        boolean sendNow = false;
21720        boolean isApp = (className == null);
21721        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21722        String componentName = isApp ? packageName : className;
21723        int packageUid = -1;
21724        ArrayList<String> components;
21725
21726        // reader
21727        synchronized (mPackages) {
21728            pkgSetting = mSettings.mPackages.get(packageName);
21729            if (pkgSetting == null) {
21730                if (!isCallerInstantApp) {
21731                    if (className == null) {
21732                        throw new IllegalArgumentException("Unknown package: " + packageName);
21733                    }
21734                    throw new IllegalArgumentException(
21735                            "Unknown component: " + packageName + "/" + className);
21736                } else {
21737                    // throw SecurityException to prevent leaking package information
21738                    throw new SecurityException(
21739                            "Attempt to change component state; "
21740                            + "pid=" + Binder.getCallingPid()
21741                            + ", uid=" + callingUid
21742                            + (className == null
21743                                    ? ", package=" + packageName
21744                                    : ", component=" + packageName + "/" + className));
21745                }
21746            }
21747        }
21748
21749        // Limit who can change which apps
21750        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21751            // Don't allow apps that don't have permission to modify other apps
21752            if (!allowedByPermission
21753                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21754                throw new SecurityException(
21755                        "Attempt to change component state; "
21756                        + "pid=" + Binder.getCallingPid()
21757                        + ", uid=" + callingUid
21758                        + (className == null
21759                                ? ", package=" + packageName
21760                                : ", component=" + packageName + "/" + className));
21761            }
21762            // Don't allow changing protected packages.
21763            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21764                throw new SecurityException("Cannot disable a protected package: " + packageName);
21765            }
21766        }
21767
21768        synchronized (mPackages) {
21769            if (callingUid == Process.SHELL_UID
21770                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21771                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21772                // unless it is a test package.
21773                int oldState = pkgSetting.getEnabled(userId);
21774                if (className == null
21775                    &&
21776                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21777                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21778                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21779                    &&
21780                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21781                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21782                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21783                    // ok
21784                } else {
21785                    throw new SecurityException(
21786                            "Shell cannot change component state for " + packageName + "/"
21787                            + className + " to " + newState);
21788                }
21789            }
21790            if (className == null) {
21791                // We're dealing with an application/package level state change
21792                if (pkgSetting.getEnabled(userId) == newState) {
21793                    // Nothing to do
21794                    return;
21795                }
21796                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21797                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21798                    // Don't care about who enables an app.
21799                    callingPackage = null;
21800                }
21801                pkgSetting.setEnabled(newState, userId, callingPackage);
21802                // pkgSetting.pkg.mSetEnabled = newState;
21803            } else {
21804                // We're dealing with a component level state change
21805                // First, verify that this is a valid class name.
21806                PackageParser.Package pkg = pkgSetting.pkg;
21807                if (pkg == null || !pkg.hasComponentClassName(className)) {
21808                    if (pkg != null &&
21809                            pkg.applicationInfo.targetSdkVersion >=
21810                                    Build.VERSION_CODES.JELLY_BEAN) {
21811                        throw new IllegalArgumentException("Component class " + className
21812                                + " does not exist in " + packageName);
21813                    } else {
21814                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21815                                + className + " does not exist in " + packageName);
21816                    }
21817                }
21818                switch (newState) {
21819                case COMPONENT_ENABLED_STATE_ENABLED:
21820                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21821                        return;
21822                    }
21823                    break;
21824                case COMPONENT_ENABLED_STATE_DISABLED:
21825                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21826                        return;
21827                    }
21828                    break;
21829                case COMPONENT_ENABLED_STATE_DEFAULT:
21830                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21831                        return;
21832                    }
21833                    break;
21834                default:
21835                    Slog.e(TAG, "Invalid new component state: " + newState);
21836                    return;
21837                }
21838            }
21839            scheduleWritePackageRestrictionsLocked(userId);
21840            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21841            final long callingId = Binder.clearCallingIdentity();
21842            try {
21843                updateInstantAppInstallerLocked(packageName);
21844            } finally {
21845                Binder.restoreCallingIdentity(callingId);
21846            }
21847            components = mPendingBroadcasts.get(userId, packageName);
21848            final boolean newPackage = components == null;
21849            if (newPackage) {
21850                components = new ArrayList<String>();
21851            }
21852            if (!components.contains(componentName)) {
21853                components.add(componentName);
21854            }
21855            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21856                sendNow = true;
21857                // Purge entry from pending broadcast list if another one exists already
21858                // since we are sending one right away.
21859                mPendingBroadcasts.remove(userId, packageName);
21860            } else {
21861                if (newPackage) {
21862                    mPendingBroadcasts.put(userId, packageName, components);
21863                }
21864                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21865                    // Schedule a message
21866                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21867                }
21868            }
21869        }
21870
21871        long callingId = Binder.clearCallingIdentity();
21872        try {
21873            if (sendNow) {
21874                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21875                sendPackageChangedBroadcast(packageName,
21876                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21877            }
21878        } finally {
21879            Binder.restoreCallingIdentity(callingId);
21880        }
21881    }
21882
21883    @Override
21884    public void flushPackageRestrictionsAsUser(int userId) {
21885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21886            return;
21887        }
21888        if (!sUserManager.exists(userId)) {
21889            return;
21890        }
21891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21892                false /* checkShell */, "flushPackageRestrictions");
21893        synchronized (mPackages) {
21894            mSettings.writePackageRestrictionsLPr(userId);
21895            mDirtyUsers.remove(userId);
21896            if (mDirtyUsers.isEmpty()) {
21897                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21898            }
21899        }
21900    }
21901
21902    private void sendPackageChangedBroadcast(String packageName,
21903            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21904        if (DEBUG_INSTALL)
21905            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21906                    + componentNames);
21907        Bundle extras = new Bundle(4);
21908        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21909        String nameList[] = new String[componentNames.size()];
21910        componentNames.toArray(nameList);
21911        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21912        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21913        extras.putInt(Intent.EXTRA_UID, packageUid);
21914        // If this is not reporting a change of the overall package, then only send it
21915        // to registered receivers.  We don't want to launch a swath of apps for every
21916        // little component state change.
21917        final int flags = !componentNames.contains(packageName)
21918                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21919        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21920                new int[] {UserHandle.getUserId(packageUid)});
21921    }
21922
21923    @Override
21924    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21925        if (!sUserManager.exists(userId)) return;
21926        final int callingUid = Binder.getCallingUid();
21927        if (getInstantAppPackageName(callingUid) != null) {
21928            return;
21929        }
21930        final int permission = mContext.checkCallingOrSelfPermission(
21931                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21932        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21933        enforceCrossUserPermission(callingUid, userId,
21934                true /* requireFullPermission */, true /* checkShell */, "stop package");
21935        // writer
21936        synchronized (mPackages) {
21937            final PackageSetting ps = mSettings.mPackages.get(packageName);
21938            if (!filterAppAccessLPr(ps, callingUid, userId)
21939                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21940                            allowedByPermission, callingUid, userId)) {
21941                scheduleWritePackageRestrictionsLocked(userId);
21942            }
21943        }
21944    }
21945
21946    @Override
21947    public String getInstallerPackageName(String packageName) {
21948        final int callingUid = Binder.getCallingUid();
21949        if (getInstantAppPackageName(callingUid) != null) {
21950            return null;
21951        }
21952        // reader
21953        synchronized (mPackages) {
21954            final PackageSetting ps = mSettings.mPackages.get(packageName);
21955            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21956                return null;
21957            }
21958            return mSettings.getInstallerPackageNameLPr(packageName);
21959        }
21960    }
21961
21962    public boolean isOrphaned(String packageName) {
21963        // reader
21964        synchronized (mPackages) {
21965            return mSettings.isOrphaned(packageName);
21966        }
21967    }
21968
21969    @Override
21970    public int getApplicationEnabledSetting(String packageName, int userId) {
21971        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21972        int callingUid = Binder.getCallingUid();
21973        enforceCrossUserPermission(callingUid, userId,
21974                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21975        // reader
21976        synchronized (mPackages) {
21977            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21978                return COMPONENT_ENABLED_STATE_DISABLED;
21979            }
21980            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21981        }
21982    }
21983
21984    @Override
21985    public int getComponentEnabledSetting(ComponentName component, int userId) {
21986        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21987        int callingUid = Binder.getCallingUid();
21988        enforceCrossUserPermission(callingUid, userId,
21989                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21990        synchronized (mPackages) {
21991            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21992                    component, TYPE_UNKNOWN, userId)) {
21993                return COMPONENT_ENABLED_STATE_DISABLED;
21994            }
21995            return mSettings.getComponentEnabledSettingLPr(component, userId);
21996        }
21997    }
21998
21999    @Override
22000    public void enterSafeMode() {
22001        enforceSystemOrRoot("Only the system can request entering safe mode");
22002
22003        if (!mSystemReady) {
22004            mSafeMode = true;
22005        }
22006    }
22007
22008    @Override
22009    public void systemReady() {
22010        enforceSystemOrRoot("Only the system can claim the system is ready");
22011
22012        mSystemReady = true;
22013        final ContentResolver resolver = mContext.getContentResolver();
22014        ContentObserver co = new ContentObserver(mHandler) {
22015            @Override
22016            public void onChange(boolean selfChange) {
22017                mEphemeralAppsDisabled =
22018                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22019                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22020            }
22021        };
22022        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22023                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22024                false, co, UserHandle.USER_SYSTEM);
22025        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22026                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22027        co.onChange(true);
22028
22029        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22030        // disabled after already being started.
22031        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22032                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22033
22034        // Read the compatibilty setting when the system is ready.
22035        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22036                mContext.getContentResolver(),
22037                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22038        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22039        if (DEBUG_SETTINGS) {
22040            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22041        }
22042
22043        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22044
22045        synchronized (mPackages) {
22046            // Verify that all of the preferred activity components actually
22047            // exist.  It is possible for applications to be updated and at
22048            // that point remove a previously declared activity component that
22049            // had been set as a preferred activity.  We try to clean this up
22050            // the next time we encounter that preferred activity, but it is
22051            // possible for the user flow to never be able to return to that
22052            // situation so here we do a sanity check to make sure we haven't
22053            // left any junk around.
22054            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22055            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22056                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22057                removed.clear();
22058                for (PreferredActivity pa : pir.filterSet()) {
22059                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22060                        removed.add(pa);
22061                    }
22062                }
22063                if (removed.size() > 0) {
22064                    for (int r=0; r<removed.size(); r++) {
22065                        PreferredActivity pa = removed.get(r);
22066                        Slog.w(TAG, "Removing dangling preferred activity: "
22067                                + pa.mPref.mComponent);
22068                        pir.removeFilter(pa);
22069                    }
22070                    mSettings.writePackageRestrictionsLPr(
22071                            mSettings.mPreferredActivities.keyAt(i));
22072                }
22073            }
22074
22075            for (int userId : UserManagerService.getInstance().getUserIds()) {
22076                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22077                    grantPermissionsUserIds = ArrayUtils.appendInt(
22078                            grantPermissionsUserIds, userId);
22079                }
22080            }
22081        }
22082        sUserManager.systemReady();
22083
22084        // If we upgraded grant all default permissions before kicking off.
22085        for (int userId : grantPermissionsUserIds) {
22086            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22087        }
22088
22089        // If we did not grant default permissions, we preload from this the
22090        // default permission exceptions lazily to ensure we don't hit the
22091        // disk on a new user creation.
22092        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22093            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22094        }
22095
22096        // Kick off any messages waiting for system ready
22097        if (mPostSystemReadyMessages != null) {
22098            for (Message msg : mPostSystemReadyMessages) {
22099                msg.sendToTarget();
22100            }
22101            mPostSystemReadyMessages = null;
22102        }
22103
22104        // Watch for external volumes that come and go over time
22105        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22106        storage.registerListener(mStorageListener);
22107
22108        mInstallerService.systemReady();
22109        mPackageDexOptimizer.systemReady();
22110
22111        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22112                StorageManagerInternal.class);
22113        StorageManagerInternal.addExternalStoragePolicy(
22114                new StorageManagerInternal.ExternalStorageMountPolicy() {
22115            @Override
22116            public int getMountMode(int uid, String packageName) {
22117                if (Process.isIsolated(uid)) {
22118                    return Zygote.MOUNT_EXTERNAL_NONE;
22119                }
22120                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22121                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22122                }
22123                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22124                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22125                }
22126                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22127                    return Zygote.MOUNT_EXTERNAL_READ;
22128                }
22129                return Zygote.MOUNT_EXTERNAL_WRITE;
22130            }
22131
22132            @Override
22133            public boolean hasExternalStorage(int uid, String packageName) {
22134                return true;
22135            }
22136        });
22137
22138        // Now that we're mostly running, clean up stale users and apps
22139        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22140        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22141
22142        if (mPrivappPermissionsViolations != null) {
22143            Slog.wtf(TAG,"Signature|privileged permissions not in "
22144                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22145            mPrivappPermissionsViolations = null;
22146        }
22147    }
22148
22149    public void waitForAppDataPrepared() {
22150        if (mPrepareAppDataFuture == null) {
22151            return;
22152        }
22153        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22154        mPrepareAppDataFuture = null;
22155    }
22156
22157    @Override
22158    public boolean isSafeMode() {
22159        // allow instant applications
22160        return mSafeMode;
22161    }
22162
22163    @Override
22164    public boolean hasSystemUidErrors() {
22165        // allow instant applications
22166        return mHasSystemUidErrors;
22167    }
22168
22169    static String arrayToString(int[] array) {
22170        StringBuffer buf = new StringBuffer(128);
22171        buf.append('[');
22172        if (array != null) {
22173            for (int i=0; i<array.length; i++) {
22174                if (i > 0) buf.append(", ");
22175                buf.append(array[i]);
22176            }
22177        }
22178        buf.append(']');
22179        return buf.toString();
22180    }
22181
22182    static class DumpState {
22183        public static final int DUMP_LIBS = 1 << 0;
22184        public static final int DUMP_FEATURES = 1 << 1;
22185        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22186        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22187        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22188        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22189        public static final int DUMP_PERMISSIONS = 1 << 6;
22190        public static final int DUMP_PACKAGES = 1 << 7;
22191        public static final int DUMP_SHARED_USERS = 1 << 8;
22192        public static final int DUMP_MESSAGES = 1 << 9;
22193        public static final int DUMP_PROVIDERS = 1 << 10;
22194        public static final int DUMP_VERIFIERS = 1 << 11;
22195        public static final int DUMP_PREFERRED = 1 << 12;
22196        public static final int DUMP_PREFERRED_XML = 1 << 13;
22197        public static final int DUMP_KEYSETS = 1 << 14;
22198        public static final int DUMP_VERSION = 1 << 15;
22199        public static final int DUMP_INSTALLS = 1 << 16;
22200        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22201        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22202        public static final int DUMP_FROZEN = 1 << 19;
22203        public static final int DUMP_DEXOPT = 1 << 20;
22204        public static final int DUMP_COMPILER_STATS = 1 << 21;
22205        public static final int DUMP_CHANGES = 1 << 22;
22206        public static final int DUMP_VOLUMES = 1 << 23;
22207
22208        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22209
22210        private int mTypes;
22211
22212        private int mOptions;
22213
22214        private boolean mTitlePrinted;
22215
22216        private SharedUserSetting mSharedUser;
22217
22218        public boolean isDumping(int type) {
22219            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22220                return true;
22221            }
22222
22223            return (mTypes & type) != 0;
22224        }
22225
22226        public void setDump(int type) {
22227            mTypes |= type;
22228        }
22229
22230        public boolean isOptionEnabled(int option) {
22231            return (mOptions & option) != 0;
22232        }
22233
22234        public void setOptionEnabled(int option) {
22235            mOptions |= option;
22236        }
22237
22238        public boolean onTitlePrinted() {
22239            final boolean printed = mTitlePrinted;
22240            mTitlePrinted = true;
22241            return printed;
22242        }
22243
22244        public boolean getTitlePrinted() {
22245            return mTitlePrinted;
22246        }
22247
22248        public void setTitlePrinted(boolean enabled) {
22249            mTitlePrinted = enabled;
22250        }
22251
22252        public SharedUserSetting getSharedUser() {
22253            return mSharedUser;
22254        }
22255
22256        public void setSharedUser(SharedUserSetting user) {
22257            mSharedUser = user;
22258        }
22259    }
22260
22261    @Override
22262    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22263            FileDescriptor err, String[] args, ShellCallback callback,
22264            ResultReceiver resultReceiver) {
22265        (new PackageManagerShellCommand(this)).exec(
22266                this, in, out, err, args, callback, resultReceiver);
22267    }
22268
22269    @Override
22270    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22271        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22272
22273        DumpState dumpState = new DumpState();
22274        boolean fullPreferred = false;
22275        boolean checkin = false;
22276
22277        String packageName = null;
22278        ArraySet<String> permissionNames = null;
22279
22280        int opti = 0;
22281        while (opti < args.length) {
22282            String opt = args[opti];
22283            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22284                break;
22285            }
22286            opti++;
22287
22288            if ("-a".equals(opt)) {
22289                // Right now we only know how to print all.
22290            } else if ("-h".equals(opt)) {
22291                pw.println("Package manager dump options:");
22292                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22293                pw.println("    --checkin: dump for a checkin");
22294                pw.println("    -f: print details of intent filters");
22295                pw.println("    -h: print this help");
22296                pw.println("  cmd may be one of:");
22297                pw.println("    l[ibraries]: list known shared libraries");
22298                pw.println("    f[eatures]: list device features");
22299                pw.println("    k[eysets]: print known keysets");
22300                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22301                pw.println("    perm[issions]: dump permissions");
22302                pw.println("    permission [name ...]: dump declaration and use of given permission");
22303                pw.println("    pref[erred]: print preferred package settings");
22304                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22305                pw.println("    prov[iders]: dump content providers");
22306                pw.println("    p[ackages]: dump installed packages");
22307                pw.println("    s[hared-users]: dump shared user IDs");
22308                pw.println("    m[essages]: print collected runtime messages");
22309                pw.println("    v[erifiers]: print package verifier info");
22310                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22311                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22312                pw.println("    version: print database version info");
22313                pw.println("    write: write current settings now");
22314                pw.println("    installs: details about install sessions");
22315                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22316                pw.println("    dexopt: dump dexopt state");
22317                pw.println("    compiler-stats: dump compiler statistics");
22318                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22319                pw.println("    <package.name>: info about given package");
22320                return;
22321            } else if ("--checkin".equals(opt)) {
22322                checkin = true;
22323            } else if ("-f".equals(opt)) {
22324                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22325            } else if ("--proto".equals(opt)) {
22326                dumpProto(fd);
22327                return;
22328            } else {
22329                pw.println("Unknown argument: " + opt + "; use -h for help");
22330            }
22331        }
22332
22333        // Is the caller requesting to dump a particular piece of data?
22334        if (opti < args.length) {
22335            String cmd = args[opti];
22336            opti++;
22337            // Is this a package name?
22338            if ("android".equals(cmd) || cmd.contains(".")) {
22339                packageName = cmd;
22340                // When dumping a single package, we always dump all of its
22341                // filter information since the amount of data will be reasonable.
22342                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22343            } else if ("check-permission".equals(cmd)) {
22344                if (opti >= args.length) {
22345                    pw.println("Error: check-permission missing permission argument");
22346                    return;
22347                }
22348                String perm = args[opti];
22349                opti++;
22350                if (opti >= args.length) {
22351                    pw.println("Error: check-permission missing package argument");
22352                    return;
22353                }
22354
22355                String pkg = args[opti];
22356                opti++;
22357                int user = UserHandle.getUserId(Binder.getCallingUid());
22358                if (opti < args.length) {
22359                    try {
22360                        user = Integer.parseInt(args[opti]);
22361                    } catch (NumberFormatException e) {
22362                        pw.println("Error: check-permission user argument is not a number: "
22363                                + args[opti]);
22364                        return;
22365                    }
22366                }
22367
22368                // Normalize package name to handle renamed packages and static libs
22369                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22370
22371                pw.println(checkPermission(perm, pkg, user));
22372                return;
22373            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22374                dumpState.setDump(DumpState.DUMP_LIBS);
22375            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22376                dumpState.setDump(DumpState.DUMP_FEATURES);
22377            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22378                if (opti >= args.length) {
22379                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22380                            | DumpState.DUMP_SERVICE_RESOLVERS
22381                            | DumpState.DUMP_RECEIVER_RESOLVERS
22382                            | DumpState.DUMP_CONTENT_RESOLVERS);
22383                } else {
22384                    while (opti < args.length) {
22385                        String name = args[opti];
22386                        if ("a".equals(name) || "activity".equals(name)) {
22387                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22388                        } else if ("s".equals(name) || "service".equals(name)) {
22389                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22390                        } else if ("r".equals(name) || "receiver".equals(name)) {
22391                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22392                        } else if ("c".equals(name) || "content".equals(name)) {
22393                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22394                        } else {
22395                            pw.println("Error: unknown resolver table type: " + name);
22396                            return;
22397                        }
22398                        opti++;
22399                    }
22400                }
22401            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22402                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22403            } else if ("permission".equals(cmd)) {
22404                if (opti >= args.length) {
22405                    pw.println("Error: permission requires permission name");
22406                    return;
22407                }
22408                permissionNames = new ArraySet<>();
22409                while (opti < args.length) {
22410                    permissionNames.add(args[opti]);
22411                    opti++;
22412                }
22413                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22414                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22415            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22416                dumpState.setDump(DumpState.DUMP_PREFERRED);
22417            } else if ("preferred-xml".equals(cmd)) {
22418                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22419                if (opti < args.length && "--full".equals(args[opti])) {
22420                    fullPreferred = true;
22421                    opti++;
22422                }
22423            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22424                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22425            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22426                dumpState.setDump(DumpState.DUMP_PACKAGES);
22427            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22428                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22429            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22430                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22431            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22432                dumpState.setDump(DumpState.DUMP_MESSAGES);
22433            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22434                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22435            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22436                    || "intent-filter-verifiers".equals(cmd)) {
22437                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22438            } else if ("version".equals(cmd)) {
22439                dumpState.setDump(DumpState.DUMP_VERSION);
22440            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22441                dumpState.setDump(DumpState.DUMP_KEYSETS);
22442            } else if ("installs".equals(cmd)) {
22443                dumpState.setDump(DumpState.DUMP_INSTALLS);
22444            } else if ("frozen".equals(cmd)) {
22445                dumpState.setDump(DumpState.DUMP_FROZEN);
22446            } else if ("volumes".equals(cmd)) {
22447                dumpState.setDump(DumpState.DUMP_VOLUMES);
22448            } else if ("dexopt".equals(cmd)) {
22449                dumpState.setDump(DumpState.DUMP_DEXOPT);
22450            } else if ("compiler-stats".equals(cmd)) {
22451                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22452            } else if ("changes".equals(cmd)) {
22453                dumpState.setDump(DumpState.DUMP_CHANGES);
22454            } else if ("write".equals(cmd)) {
22455                synchronized (mPackages) {
22456                    mSettings.writeLPr();
22457                    pw.println("Settings written.");
22458                    return;
22459                }
22460            }
22461        }
22462
22463        if (checkin) {
22464            pw.println("vers,1");
22465        }
22466
22467        // reader
22468        synchronized (mPackages) {
22469            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22470                if (!checkin) {
22471                    if (dumpState.onTitlePrinted())
22472                        pw.println();
22473                    pw.println("Database versions:");
22474                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22475                }
22476            }
22477
22478            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22479                if (!checkin) {
22480                    if (dumpState.onTitlePrinted())
22481                        pw.println();
22482                    pw.println("Verifiers:");
22483                    pw.print("  Required: ");
22484                    pw.print(mRequiredVerifierPackage);
22485                    pw.print(" (uid=");
22486                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22487                            UserHandle.USER_SYSTEM));
22488                    pw.println(")");
22489                } else if (mRequiredVerifierPackage != null) {
22490                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22491                    pw.print(",");
22492                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22493                            UserHandle.USER_SYSTEM));
22494                }
22495            }
22496
22497            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22498                    packageName == null) {
22499                if (mIntentFilterVerifierComponent != null) {
22500                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22501                    if (!checkin) {
22502                        if (dumpState.onTitlePrinted())
22503                            pw.println();
22504                        pw.println("Intent Filter Verifier:");
22505                        pw.print("  Using: ");
22506                        pw.print(verifierPackageName);
22507                        pw.print(" (uid=");
22508                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22509                                UserHandle.USER_SYSTEM));
22510                        pw.println(")");
22511                    } else if (verifierPackageName != null) {
22512                        pw.print("ifv,"); pw.print(verifierPackageName);
22513                        pw.print(",");
22514                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22515                                UserHandle.USER_SYSTEM));
22516                    }
22517                } else {
22518                    pw.println();
22519                    pw.println("No Intent Filter Verifier available!");
22520                }
22521            }
22522
22523            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22524                boolean printedHeader = false;
22525                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22526                while (it.hasNext()) {
22527                    String libName = it.next();
22528                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22529                    if (versionedLib == null) {
22530                        continue;
22531                    }
22532                    final int versionCount = versionedLib.size();
22533                    for (int i = 0; i < versionCount; i++) {
22534                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22535                        if (!checkin) {
22536                            if (!printedHeader) {
22537                                if (dumpState.onTitlePrinted())
22538                                    pw.println();
22539                                pw.println("Libraries:");
22540                                printedHeader = true;
22541                            }
22542                            pw.print("  ");
22543                        } else {
22544                            pw.print("lib,");
22545                        }
22546                        pw.print(libEntry.info.getName());
22547                        if (libEntry.info.isStatic()) {
22548                            pw.print(" version=" + libEntry.info.getVersion());
22549                        }
22550                        if (!checkin) {
22551                            pw.print(" -> ");
22552                        }
22553                        if (libEntry.path != null) {
22554                            pw.print(" (jar) ");
22555                            pw.print(libEntry.path);
22556                        } else {
22557                            pw.print(" (apk) ");
22558                            pw.print(libEntry.apk);
22559                        }
22560                        pw.println();
22561                    }
22562                }
22563            }
22564
22565            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22566                if (dumpState.onTitlePrinted())
22567                    pw.println();
22568                if (!checkin) {
22569                    pw.println("Features:");
22570                }
22571
22572                synchronized (mAvailableFeatures) {
22573                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22574                        if (checkin) {
22575                            pw.print("feat,");
22576                            pw.print(feat.name);
22577                            pw.print(",");
22578                            pw.println(feat.version);
22579                        } else {
22580                            pw.print("  ");
22581                            pw.print(feat.name);
22582                            if (feat.version > 0) {
22583                                pw.print(" version=");
22584                                pw.print(feat.version);
22585                            }
22586                            pw.println();
22587                        }
22588                    }
22589                }
22590            }
22591
22592            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22593                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22594                        : "Activity Resolver Table:", "  ", packageName,
22595                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22596                    dumpState.setTitlePrinted(true);
22597                }
22598            }
22599            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22600                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22601                        : "Receiver Resolver Table:", "  ", packageName,
22602                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22603                    dumpState.setTitlePrinted(true);
22604                }
22605            }
22606            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22607                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22608                        : "Service Resolver Table:", "  ", packageName,
22609                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22610                    dumpState.setTitlePrinted(true);
22611                }
22612            }
22613            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22614                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22615                        : "Provider Resolver Table:", "  ", packageName,
22616                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22617                    dumpState.setTitlePrinted(true);
22618                }
22619            }
22620
22621            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22622                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22623                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22624                    int user = mSettings.mPreferredActivities.keyAt(i);
22625                    if (pir.dump(pw,
22626                            dumpState.getTitlePrinted()
22627                                ? "\nPreferred Activities User " + user + ":"
22628                                : "Preferred Activities User " + user + ":", "  ",
22629                            packageName, true, false)) {
22630                        dumpState.setTitlePrinted(true);
22631                    }
22632                }
22633            }
22634
22635            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22636                pw.flush();
22637                FileOutputStream fout = new FileOutputStream(fd);
22638                BufferedOutputStream str = new BufferedOutputStream(fout);
22639                XmlSerializer serializer = new FastXmlSerializer();
22640                try {
22641                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22642                    serializer.startDocument(null, true);
22643                    serializer.setFeature(
22644                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22645                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22646                    serializer.endDocument();
22647                    serializer.flush();
22648                } catch (IllegalArgumentException e) {
22649                    pw.println("Failed writing: " + e);
22650                } catch (IllegalStateException e) {
22651                    pw.println("Failed writing: " + e);
22652                } catch (IOException e) {
22653                    pw.println("Failed writing: " + e);
22654                }
22655            }
22656
22657            if (!checkin
22658                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22659                    && packageName == null) {
22660                pw.println();
22661                int count = mSettings.mPackages.size();
22662                if (count == 0) {
22663                    pw.println("No applications!");
22664                    pw.println();
22665                } else {
22666                    final String prefix = "  ";
22667                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22668                    if (allPackageSettings.size() == 0) {
22669                        pw.println("No domain preferred apps!");
22670                        pw.println();
22671                    } else {
22672                        pw.println("App verification status:");
22673                        pw.println();
22674                        count = 0;
22675                        for (PackageSetting ps : allPackageSettings) {
22676                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22677                            if (ivi == null || ivi.getPackageName() == null) continue;
22678                            pw.println(prefix + "Package: " + ivi.getPackageName());
22679                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22680                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22681                            pw.println();
22682                            count++;
22683                        }
22684                        if (count == 0) {
22685                            pw.println(prefix + "No app verification established.");
22686                            pw.println();
22687                        }
22688                        for (int userId : sUserManager.getUserIds()) {
22689                            pw.println("App linkages for user " + userId + ":");
22690                            pw.println();
22691                            count = 0;
22692                            for (PackageSetting ps : allPackageSettings) {
22693                                final long status = ps.getDomainVerificationStatusForUser(userId);
22694                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22695                                        && !DEBUG_DOMAIN_VERIFICATION) {
22696                                    continue;
22697                                }
22698                                pw.println(prefix + "Package: " + ps.name);
22699                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22700                                String statusStr = IntentFilterVerificationInfo.
22701                                        getStatusStringFromValue(status);
22702                                pw.println(prefix + "Status:  " + statusStr);
22703                                pw.println();
22704                                count++;
22705                            }
22706                            if (count == 0) {
22707                                pw.println(prefix + "No configured app linkages.");
22708                                pw.println();
22709                            }
22710                        }
22711                    }
22712                }
22713            }
22714
22715            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22716                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22717                if (packageName == null && permissionNames == null) {
22718                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22719                        if (iperm == 0) {
22720                            if (dumpState.onTitlePrinted())
22721                                pw.println();
22722                            pw.println("AppOp Permissions:");
22723                        }
22724                        pw.print("  AppOp Permission ");
22725                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22726                        pw.println(":");
22727                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22728                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22729                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22730                        }
22731                    }
22732                }
22733            }
22734
22735            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22736                boolean printedSomething = false;
22737                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22738                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22739                        continue;
22740                    }
22741                    if (!printedSomething) {
22742                        if (dumpState.onTitlePrinted())
22743                            pw.println();
22744                        pw.println("Registered ContentProviders:");
22745                        printedSomething = true;
22746                    }
22747                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22748                    pw.print("    "); pw.println(p.toString());
22749                }
22750                printedSomething = false;
22751                for (Map.Entry<String, PackageParser.Provider> entry :
22752                        mProvidersByAuthority.entrySet()) {
22753                    PackageParser.Provider p = entry.getValue();
22754                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22755                        continue;
22756                    }
22757                    if (!printedSomething) {
22758                        if (dumpState.onTitlePrinted())
22759                            pw.println();
22760                        pw.println("ContentProvider Authorities:");
22761                        printedSomething = true;
22762                    }
22763                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22764                    pw.print("    "); pw.println(p.toString());
22765                    if (p.info != null && p.info.applicationInfo != null) {
22766                        final String appInfo = p.info.applicationInfo.toString();
22767                        pw.print("      applicationInfo="); pw.println(appInfo);
22768                    }
22769                }
22770            }
22771
22772            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22773                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22774            }
22775
22776            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22777                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22778            }
22779
22780            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22781                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22782            }
22783
22784            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22785                if (dumpState.onTitlePrinted()) pw.println();
22786                pw.println("Package Changes:");
22787                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22788                final int K = mChangedPackages.size();
22789                for (int i = 0; i < K; i++) {
22790                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22791                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22792                    final int N = changes.size();
22793                    if (N == 0) {
22794                        pw.print("    "); pw.println("No packages changed");
22795                    } else {
22796                        for (int j = 0; j < N; j++) {
22797                            final String pkgName = changes.valueAt(j);
22798                            final int sequenceNumber = changes.keyAt(j);
22799                            pw.print("    ");
22800                            pw.print("seq=");
22801                            pw.print(sequenceNumber);
22802                            pw.print(", package=");
22803                            pw.println(pkgName);
22804                        }
22805                    }
22806                }
22807            }
22808
22809            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22810                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22811            }
22812
22813            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22814                // XXX should handle packageName != null by dumping only install data that
22815                // the given package is involved with.
22816                if (dumpState.onTitlePrinted()) pw.println();
22817
22818                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22819                ipw.println();
22820                ipw.println("Frozen packages:");
22821                ipw.increaseIndent();
22822                if (mFrozenPackages.size() == 0) {
22823                    ipw.println("(none)");
22824                } else {
22825                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22826                        ipw.println(mFrozenPackages.valueAt(i));
22827                    }
22828                }
22829                ipw.decreaseIndent();
22830            }
22831
22832            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22833                if (dumpState.onTitlePrinted()) pw.println();
22834
22835                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22836                ipw.println();
22837                ipw.println("Loaded volumes:");
22838                ipw.increaseIndent();
22839                if (mLoadedVolumes.size() == 0) {
22840                    ipw.println("(none)");
22841                } else {
22842                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22843                        ipw.println(mLoadedVolumes.valueAt(i));
22844                    }
22845                }
22846                ipw.decreaseIndent();
22847            }
22848
22849            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22850                if (dumpState.onTitlePrinted()) pw.println();
22851                dumpDexoptStateLPr(pw, packageName);
22852            }
22853
22854            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22855                if (dumpState.onTitlePrinted()) pw.println();
22856                dumpCompilerStatsLPr(pw, packageName);
22857            }
22858
22859            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22860                if (dumpState.onTitlePrinted()) pw.println();
22861                mSettings.dumpReadMessagesLPr(pw, dumpState);
22862
22863                pw.println();
22864                pw.println("Package warning messages:");
22865                BufferedReader in = null;
22866                String line = null;
22867                try {
22868                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22869                    while ((line = in.readLine()) != null) {
22870                        if (line.contains("ignored: updated version")) continue;
22871                        pw.println(line);
22872                    }
22873                } catch (IOException ignored) {
22874                } finally {
22875                    IoUtils.closeQuietly(in);
22876                }
22877            }
22878
22879            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22880                BufferedReader in = null;
22881                String line = null;
22882                try {
22883                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22884                    while ((line = in.readLine()) != null) {
22885                        if (line.contains("ignored: updated version")) continue;
22886                        pw.print("msg,");
22887                        pw.println(line);
22888                    }
22889                } catch (IOException ignored) {
22890                } finally {
22891                    IoUtils.closeQuietly(in);
22892                }
22893            }
22894        }
22895
22896        // PackageInstaller should be called outside of mPackages lock
22897        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22898            // XXX should handle packageName != null by dumping only install data that
22899            // the given package is involved with.
22900            if (dumpState.onTitlePrinted()) pw.println();
22901            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22902        }
22903    }
22904
22905    private void dumpProto(FileDescriptor fd) {
22906        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22907
22908        synchronized (mPackages) {
22909            final long requiredVerifierPackageToken =
22910                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22911            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22912            proto.write(
22913                    PackageServiceDumpProto.PackageShortProto.UID,
22914                    getPackageUid(
22915                            mRequiredVerifierPackage,
22916                            MATCH_DEBUG_TRIAGED_MISSING,
22917                            UserHandle.USER_SYSTEM));
22918            proto.end(requiredVerifierPackageToken);
22919
22920            if (mIntentFilterVerifierComponent != null) {
22921                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22922                final long verifierPackageToken =
22923                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22924                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22925                proto.write(
22926                        PackageServiceDumpProto.PackageShortProto.UID,
22927                        getPackageUid(
22928                                verifierPackageName,
22929                                MATCH_DEBUG_TRIAGED_MISSING,
22930                                UserHandle.USER_SYSTEM));
22931                proto.end(verifierPackageToken);
22932            }
22933
22934            dumpSharedLibrariesProto(proto);
22935            dumpFeaturesProto(proto);
22936            mSettings.dumpPackagesProto(proto);
22937            mSettings.dumpSharedUsersProto(proto);
22938            dumpMessagesProto(proto);
22939        }
22940        proto.flush();
22941    }
22942
22943    private void dumpMessagesProto(ProtoOutputStream proto) {
22944        BufferedReader in = null;
22945        String line = null;
22946        try {
22947            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22948            while ((line = in.readLine()) != null) {
22949                if (line.contains("ignored: updated version")) continue;
22950                proto.write(PackageServiceDumpProto.MESSAGES, line);
22951            }
22952        } catch (IOException ignored) {
22953        } finally {
22954            IoUtils.closeQuietly(in);
22955        }
22956    }
22957
22958    private void dumpFeaturesProto(ProtoOutputStream proto) {
22959        synchronized (mAvailableFeatures) {
22960            final int count = mAvailableFeatures.size();
22961            for (int i = 0; i < count; i++) {
22962                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22963                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22964                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22965                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22966                proto.end(featureToken);
22967            }
22968        }
22969    }
22970
22971    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22972        final int count = mSharedLibraries.size();
22973        for (int i = 0; i < count; i++) {
22974            final String libName = mSharedLibraries.keyAt(i);
22975            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22976            if (versionedLib == null) {
22977                continue;
22978            }
22979            final int versionCount = versionedLib.size();
22980            for (int j = 0; j < versionCount; j++) {
22981                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22982                final long sharedLibraryToken =
22983                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22984                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22985                final boolean isJar = (libEntry.path != null);
22986                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22987                if (isJar) {
22988                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22989                } else {
22990                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22991                }
22992                proto.end(sharedLibraryToken);
22993            }
22994        }
22995    }
22996
22997    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22998        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22999        ipw.println();
23000        ipw.println("Dexopt state:");
23001        ipw.increaseIndent();
23002        Collection<PackageParser.Package> packages = null;
23003        if (packageName != null) {
23004            PackageParser.Package targetPackage = mPackages.get(packageName);
23005            if (targetPackage != null) {
23006                packages = Collections.singletonList(targetPackage);
23007            } else {
23008                ipw.println("Unable to find package: " + packageName);
23009                return;
23010            }
23011        } else {
23012            packages = mPackages.values();
23013        }
23014
23015        for (PackageParser.Package pkg : packages) {
23016            ipw.println("[" + pkg.packageName + "]");
23017            ipw.increaseIndent();
23018            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23019                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23020            ipw.decreaseIndent();
23021        }
23022    }
23023
23024    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23025        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23026        ipw.println();
23027        ipw.println("Compiler stats:");
23028        ipw.increaseIndent();
23029        Collection<PackageParser.Package> packages = null;
23030        if (packageName != null) {
23031            PackageParser.Package targetPackage = mPackages.get(packageName);
23032            if (targetPackage != null) {
23033                packages = Collections.singletonList(targetPackage);
23034            } else {
23035                ipw.println("Unable to find package: " + packageName);
23036                return;
23037            }
23038        } else {
23039            packages = mPackages.values();
23040        }
23041
23042        for (PackageParser.Package pkg : packages) {
23043            ipw.println("[" + pkg.packageName + "]");
23044            ipw.increaseIndent();
23045
23046            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23047            if (stats == null) {
23048                ipw.println("(No recorded stats)");
23049            } else {
23050                stats.dump(ipw);
23051            }
23052            ipw.decreaseIndent();
23053        }
23054    }
23055
23056    private String dumpDomainString(String packageName) {
23057        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23058                .getList();
23059        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23060
23061        ArraySet<String> result = new ArraySet<>();
23062        if (iviList.size() > 0) {
23063            for (IntentFilterVerificationInfo ivi : iviList) {
23064                for (String host : ivi.getDomains()) {
23065                    result.add(host);
23066                }
23067            }
23068        }
23069        if (filters != null && filters.size() > 0) {
23070            for (IntentFilter filter : filters) {
23071                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23072                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23073                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23074                    result.addAll(filter.getHostsList());
23075                }
23076            }
23077        }
23078
23079        StringBuilder sb = new StringBuilder(result.size() * 16);
23080        for (String domain : result) {
23081            if (sb.length() > 0) sb.append(" ");
23082            sb.append(domain);
23083        }
23084        return sb.toString();
23085    }
23086
23087    // ------- apps on sdcard specific code -------
23088    static final boolean DEBUG_SD_INSTALL = false;
23089
23090    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23091
23092    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23093
23094    private boolean mMediaMounted = false;
23095
23096    static String getEncryptKey() {
23097        try {
23098            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23099                    SD_ENCRYPTION_KEYSTORE_NAME);
23100            if (sdEncKey == null) {
23101                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23102                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23103                if (sdEncKey == null) {
23104                    Slog.e(TAG, "Failed to create encryption keys");
23105                    return null;
23106                }
23107            }
23108            return sdEncKey;
23109        } catch (NoSuchAlgorithmException nsae) {
23110            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23111            return null;
23112        } catch (IOException ioe) {
23113            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23114            return null;
23115        }
23116    }
23117
23118    /*
23119     * Update media status on PackageManager.
23120     */
23121    @Override
23122    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23123        enforceSystemOrRoot("Media status can only be updated by the system");
23124        // reader; this apparently protects mMediaMounted, but should probably
23125        // be a different lock in that case.
23126        synchronized (mPackages) {
23127            Log.i(TAG, "Updating external media status from "
23128                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23129                    + (mediaStatus ? "mounted" : "unmounted"));
23130            if (DEBUG_SD_INSTALL)
23131                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23132                        + ", mMediaMounted=" + mMediaMounted);
23133            if (mediaStatus == mMediaMounted) {
23134                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23135                        : 0, -1);
23136                mHandler.sendMessage(msg);
23137                return;
23138            }
23139            mMediaMounted = mediaStatus;
23140        }
23141        // Queue up an async operation since the package installation may take a
23142        // little while.
23143        mHandler.post(new Runnable() {
23144            public void run() {
23145                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23146            }
23147        });
23148    }
23149
23150    /**
23151     * Called by StorageManagerService when the initial ASECs to scan are available.
23152     * Should block until all the ASEC containers are finished being scanned.
23153     */
23154    public void scanAvailableAsecs() {
23155        updateExternalMediaStatusInner(true, false, false);
23156    }
23157
23158    /*
23159     * Collect information of applications on external media, map them against
23160     * existing containers and update information based on current mount status.
23161     * Please note that we always have to report status if reportStatus has been
23162     * set to true especially when unloading packages.
23163     */
23164    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23165            boolean externalStorage) {
23166        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23167        int[] uidArr = EmptyArray.INT;
23168
23169        final String[] list = PackageHelper.getSecureContainerList();
23170        if (ArrayUtils.isEmpty(list)) {
23171            Log.i(TAG, "No secure containers found");
23172        } else {
23173            // Process list of secure containers and categorize them
23174            // as active or stale based on their package internal state.
23175
23176            // reader
23177            synchronized (mPackages) {
23178                for (String cid : list) {
23179                    // Leave stages untouched for now; installer service owns them
23180                    if (PackageInstallerService.isStageName(cid)) continue;
23181
23182                    if (DEBUG_SD_INSTALL)
23183                        Log.i(TAG, "Processing container " + cid);
23184                    String pkgName = getAsecPackageName(cid);
23185                    if (pkgName == null) {
23186                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23187                        continue;
23188                    }
23189                    if (DEBUG_SD_INSTALL)
23190                        Log.i(TAG, "Looking for pkg : " + pkgName);
23191
23192                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23193                    if (ps == null) {
23194                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23195                        continue;
23196                    }
23197
23198                    /*
23199                     * Skip packages that are not external if we're unmounting
23200                     * external storage.
23201                     */
23202                    if (externalStorage && !isMounted && !isExternal(ps)) {
23203                        continue;
23204                    }
23205
23206                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23207                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23208                    // The package status is changed only if the code path
23209                    // matches between settings and the container id.
23210                    if (ps.codePathString != null
23211                            && ps.codePathString.startsWith(args.getCodePath())) {
23212                        if (DEBUG_SD_INSTALL) {
23213                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23214                                    + " at code path: " + ps.codePathString);
23215                        }
23216
23217                        // We do have a valid package installed on sdcard
23218                        processCids.put(args, ps.codePathString);
23219                        final int uid = ps.appId;
23220                        if (uid != -1) {
23221                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23222                        }
23223                    } else {
23224                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23225                                + ps.codePathString);
23226                    }
23227                }
23228            }
23229
23230            Arrays.sort(uidArr);
23231        }
23232
23233        // Process packages with valid entries.
23234        if (isMounted) {
23235            if (DEBUG_SD_INSTALL)
23236                Log.i(TAG, "Loading packages");
23237            loadMediaPackages(processCids, uidArr, externalStorage);
23238            startCleaningPackages();
23239            mInstallerService.onSecureContainersAvailable();
23240        } else {
23241            if (DEBUG_SD_INSTALL)
23242                Log.i(TAG, "Unloading packages");
23243            unloadMediaPackages(processCids, uidArr, reportStatus);
23244        }
23245    }
23246
23247    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23248            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23249        final int size = infos.size();
23250        final String[] packageNames = new String[size];
23251        final int[] packageUids = new int[size];
23252        for (int i = 0; i < size; i++) {
23253            final ApplicationInfo info = infos.get(i);
23254            packageNames[i] = info.packageName;
23255            packageUids[i] = info.uid;
23256        }
23257        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23258                finishedReceiver);
23259    }
23260
23261    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23262            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23263        sendResourcesChangedBroadcast(mediaStatus, replacing,
23264                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23265    }
23266
23267    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23268            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23269        int size = pkgList.length;
23270        if (size > 0) {
23271            // Send broadcasts here
23272            Bundle extras = new Bundle();
23273            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23274            if (uidArr != null) {
23275                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23276            }
23277            if (replacing) {
23278                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23279            }
23280            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23281                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23282            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23283        }
23284    }
23285
23286   /*
23287     * Look at potentially valid container ids from processCids If package
23288     * information doesn't match the one on record or package scanning fails,
23289     * the cid is added to list of removeCids. We currently don't delete stale
23290     * containers.
23291     */
23292    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23293            boolean externalStorage) {
23294        ArrayList<String> pkgList = new ArrayList<String>();
23295        Set<AsecInstallArgs> keys = processCids.keySet();
23296
23297        for (AsecInstallArgs args : keys) {
23298            String codePath = processCids.get(args);
23299            if (DEBUG_SD_INSTALL)
23300                Log.i(TAG, "Loading container : " + args.cid);
23301            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23302            try {
23303                // Make sure there are no container errors first.
23304                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23305                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23306                            + " when installing from sdcard");
23307                    continue;
23308                }
23309                // Check code path here.
23310                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23311                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23312                            + " does not match one in settings " + codePath);
23313                    continue;
23314                }
23315                // Parse package
23316                int parseFlags = mDefParseFlags;
23317                if (args.isExternalAsec()) {
23318                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23319                }
23320                if (args.isFwdLocked()) {
23321                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23322                }
23323
23324                synchronized (mInstallLock) {
23325                    PackageParser.Package pkg = null;
23326                    try {
23327                        // Sadly we don't know the package name yet to freeze it
23328                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23329                                SCAN_IGNORE_FROZEN, 0, null);
23330                    } catch (PackageManagerException e) {
23331                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23332                    }
23333                    // Scan the package
23334                    if (pkg != null) {
23335                        /*
23336                         * TODO why is the lock being held? doPostInstall is
23337                         * called in other places without the lock. This needs
23338                         * to be straightened out.
23339                         */
23340                        // writer
23341                        synchronized (mPackages) {
23342                            retCode = PackageManager.INSTALL_SUCCEEDED;
23343                            pkgList.add(pkg.packageName);
23344                            // Post process args
23345                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23346                                    pkg.applicationInfo.uid);
23347                        }
23348                    } else {
23349                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23350                    }
23351                }
23352
23353            } finally {
23354                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23355                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23356                }
23357            }
23358        }
23359        // writer
23360        synchronized (mPackages) {
23361            // If the platform SDK has changed since the last time we booted,
23362            // we need to re-grant app permission to catch any new ones that
23363            // appear. This is really a hack, and means that apps can in some
23364            // cases get permissions that the user didn't initially explicitly
23365            // allow... it would be nice to have some better way to handle
23366            // this situation.
23367            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23368                    : mSettings.getInternalVersion();
23369            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23370                    : StorageManager.UUID_PRIVATE_INTERNAL;
23371
23372            int updateFlags = UPDATE_PERMISSIONS_ALL;
23373            if (ver.sdkVersion != mSdkVersion) {
23374                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23375                        + mSdkVersion + "; regranting permissions for external");
23376                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23377            }
23378            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23379
23380            // Yay, everything is now upgraded
23381            ver.forceCurrent();
23382
23383            // can downgrade to reader
23384            // Persist settings
23385            mSettings.writeLPr();
23386        }
23387        // Send a broadcast to let everyone know we are done processing
23388        if (pkgList.size() > 0) {
23389            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23390        }
23391    }
23392
23393   /*
23394     * Utility method to unload a list of specified containers
23395     */
23396    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23397        // Just unmount all valid containers.
23398        for (AsecInstallArgs arg : cidArgs) {
23399            synchronized (mInstallLock) {
23400                arg.doPostDeleteLI(false);
23401           }
23402       }
23403   }
23404
23405    /*
23406     * Unload packages mounted on external media. This involves deleting package
23407     * data from internal structures, sending broadcasts about disabled packages,
23408     * gc'ing to free up references, unmounting all secure containers
23409     * corresponding to packages on external media, and posting a
23410     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23411     * that we always have to post this message if status has been requested no
23412     * matter what.
23413     */
23414    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23415            final boolean reportStatus) {
23416        if (DEBUG_SD_INSTALL)
23417            Log.i(TAG, "unloading media packages");
23418        ArrayList<String> pkgList = new ArrayList<String>();
23419        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23420        final Set<AsecInstallArgs> keys = processCids.keySet();
23421        for (AsecInstallArgs args : keys) {
23422            String pkgName = args.getPackageName();
23423            if (DEBUG_SD_INSTALL)
23424                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23425            // Delete package internally
23426            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23427            synchronized (mInstallLock) {
23428                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23429                final boolean res;
23430                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23431                        "unloadMediaPackages")) {
23432                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23433                            null);
23434                }
23435                if (res) {
23436                    pkgList.add(pkgName);
23437                } else {
23438                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23439                    failedList.add(args);
23440                }
23441            }
23442        }
23443
23444        // reader
23445        synchronized (mPackages) {
23446            // We didn't update the settings after removing each package;
23447            // write them now for all packages.
23448            mSettings.writeLPr();
23449        }
23450
23451        // We have to absolutely send UPDATED_MEDIA_STATUS only
23452        // after confirming that all the receivers processed the ordered
23453        // broadcast when packages get disabled, force a gc to clean things up.
23454        // and unload all the containers.
23455        if (pkgList.size() > 0) {
23456            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23457                    new IIntentReceiver.Stub() {
23458                public void performReceive(Intent intent, int resultCode, String data,
23459                        Bundle extras, boolean ordered, boolean sticky,
23460                        int sendingUser) throws RemoteException {
23461                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23462                            reportStatus ? 1 : 0, 1, keys);
23463                    mHandler.sendMessage(msg);
23464                }
23465            });
23466        } else {
23467            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23468                    keys);
23469            mHandler.sendMessage(msg);
23470        }
23471    }
23472
23473    private void loadPrivatePackages(final VolumeInfo vol) {
23474        mHandler.post(new Runnable() {
23475            @Override
23476            public void run() {
23477                loadPrivatePackagesInner(vol);
23478            }
23479        });
23480    }
23481
23482    private void loadPrivatePackagesInner(VolumeInfo vol) {
23483        final String volumeUuid = vol.fsUuid;
23484        if (TextUtils.isEmpty(volumeUuid)) {
23485            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23486            return;
23487        }
23488
23489        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23490        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23491        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23492
23493        final VersionInfo ver;
23494        final List<PackageSetting> packages;
23495        synchronized (mPackages) {
23496            ver = mSettings.findOrCreateVersion(volumeUuid);
23497            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23498        }
23499
23500        for (PackageSetting ps : packages) {
23501            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23502            synchronized (mInstallLock) {
23503                final PackageParser.Package pkg;
23504                try {
23505                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23506                    loaded.add(pkg.applicationInfo);
23507
23508                } catch (PackageManagerException e) {
23509                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23510                }
23511
23512                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23513                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23514                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23515                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23516                }
23517            }
23518        }
23519
23520        // Reconcile app data for all started/unlocked users
23521        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23522        final UserManager um = mContext.getSystemService(UserManager.class);
23523        UserManagerInternal umInternal = getUserManagerInternal();
23524        for (UserInfo user : um.getUsers()) {
23525            final int flags;
23526            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23527                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23528            } else if (umInternal.isUserRunning(user.id)) {
23529                flags = StorageManager.FLAG_STORAGE_DE;
23530            } else {
23531                continue;
23532            }
23533
23534            try {
23535                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23536                synchronized (mInstallLock) {
23537                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23538                }
23539            } catch (IllegalStateException e) {
23540                // Device was probably ejected, and we'll process that event momentarily
23541                Slog.w(TAG, "Failed to prepare storage: " + e);
23542            }
23543        }
23544
23545        synchronized (mPackages) {
23546            int updateFlags = UPDATE_PERMISSIONS_ALL;
23547            if (ver.sdkVersion != mSdkVersion) {
23548                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23549                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23550                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23551            }
23552            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23553
23554            // Yay, everything is now upgraded
23555            ver.forceCurrent();
23556
23557            mSettings.writeLPr();
23558        }
23559
23560        for (PackageFreezer freezer : freezers) {
23561            freezer.close();
23562        }
23563
23564        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23565        sendResourcesChangedBroadcast(true, false, loaded, null);
23566        mLoadedVolumes.add(vol.getId());
23567    }
23568
23569    private void unloadPrivatePackages(final VolumeInfo vol) {
23570        mHandler.post(new Runnable() {
23571            @Override
23572            public void run() {
23573                unloadPrivatePackagesInner(vol);
23574            }
23575        });
23576    }
23577
23578    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23579        final String volumeUuid = vol.fsUuid;
23580        if (TextUtils.isEmpty(volumeUuid)) {
23581            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23582            return;
23583        }
23584
23585        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23586        synchronized (mInstallLock) {
23587        synchronized (mPackages) {
23588            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23589            for (PackageSetting ps : packages) {
23590                if (ps.pkg == null) continue;
23591
23592                final ApplicationInfo info = ps.pkg.applicationInfo;
23593                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23594                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23595
23596                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23597                        "unloadPrivatePackagesInner")) {
23598                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23599                            false, null)) {
23600                        unloaded.add(info);
23601                    } else {
23602                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23603                    }
23604                }
23605
23606                // Try very hard to release any references to this package
23607                // so we don't risk the system server being killed due to
23608                // open FDs
23609                AttributeCache.instance().removePackage(ps.name);
23610            }
23611
23612            mSettings.writeLPr();
23613        }
23614        }
23615
23616        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23617        sendResourcesChangedBroadcast(false, false, unloaded, null);
23618        mLoadedVolumes.remove(vol.getId());
23619
23620        // Try very hard to release any references to this path so we don't risk
23621        // the system server being killed due to open FDs
23622        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23623
23624        for (int i = 0; i < 3; i++) {
23625            System.gc();
23626            System.runFinalization();
23627        }
23628    }
23629
23630    private void assertPackageKnown(String volumeUuid, String packageName)
23631            throws PackageManagerException {
23632        synchronized (mPackages) {
23633            // Normalize package name to handle renamed packages
23634            packageName = normalizePackageNameLPr(packageName);
23635
23636            final PackageSetting ps = mSettings.mPackages.get(packageName);
23637            if (ps == null) {
23638                throw new PackageManagerException("Package " + packageName + " is unknown");
23639            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23640                throw new PackageManagerException(
23641                        "Package " + packageName + " found on unknown volume " + volumeUuid
23642                                + "; expected volume " + ps.volumeUuid);
23643            }
23644        }
23645    }
23646
23647    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23648            throws PackageManagerException {
23649        synchronized (mPackages) {
23650            // Normalize package name to handle renamed packages
23651            packageName = normalizePackageNameLPr(packageName);
23652
23653            final PackageSetting ps = mSettings.mPackages.get(packageName);
23654            if (ps == null) {
23655                throw new PackageManagerException("Package " + packageName + " is unknown");
23656            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23657                throw new PackageManagerException(
23658                        "Package " + packageName + " found on unknown volume " + volumeUuid
23659                                + "; expected volume " + ps.volumeUuid);
23660            } else if (!ps.getInstalled(userId)) {
23661                throw new PackageManagerException(
23662                        "Package " + packageName + " not installed for user " + userId);
23663            }
23664        }
23665    }
23666
23667    private List<String> collectAbsoluteCodePaths() {
23668        synchronized (mPackages) {
23669            List<String> codePaths = new ArrayList<>();
23670            final int packageCount = mSettings.mPackages.size();
23671            for (int i = 0; i < packageCount; i++) {
23672                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23673                codePaths.add(ps.codePath.getAbsolutePath());
23674            }
23675            return codePaths;
23676        }
23677    }
23678
23679    /**
23680     * Examine all apps present on given mounted volume, and destroy apps that
23681     * aren't expected, either due to uninstallation or reinstallation on
23682     * another volume.
23683     */
23684    private void reconcileApps(String volumeUuid) {
23685        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23686        List<File> filesToDelete = null;
23687
23688        final File[] files = FileUtils.listFilesOrEmpty(
23689                Environment.getDataAppDirectory(volumeUuid));
23690        for (File file : files) {
23691            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23692                    && !PackageInstallerService.isStageName(file.getName());
23693            if (!isPackage) {
23694                // Ignore entries which are not packages
23695                continue;
23696            }
23697
23698            String absolutePath = file.getAbsolutePath();
23699
23700            boolean pathValid = false;
23701            final int absoluteCodePathCount = absoluteCodePaths.size();
23702            for (int i = 0; i < absoluteCodePathCount; i++) {
23703                String absoluteCodePath = absoluteCodePaths.get(i);
23704                if (absolutePath.startsWith(absoluteCodePath)) {
23705                    pathValid = true;
23706                    break;
23707                }
23708            }
23709
23710            if (!pathValid) {
23711                if (filesToDelete == null) {
23712                    filesToDelete = new ArrayList<>();
23713                }
23714                filesToDelete.add(file);
23715            }
23716        }
23717
23718        if (filesToDelete != null) {
23719            final int fileToDeleteCount = filesToDelete.size();
23720            for (int i = 0; i < fileToDeleteCount; i++) {
23721                File fileToDelete = filesToDelete.get(i);
23722                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23723                synchronized (mInstallLock) {
23724                    removeCodePathLI(fileToDelete);
23725                }
23726            }
23727        }
23728    }
23729
23730    /**
23731     * Reconcile all app data for the given user.
23732     * <p>
23733     * Verifies that directories exist and that ownership and labeling is
23734     * correct for all installed apps on all mounted volumes.
23735     */
23736    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23737        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23738        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23739            final String volumeUuid = vol.getFsUuid();
23740            synchronized (mInstallLock) {
23741                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23742            }
23743        }
23744    }
23745
23746    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23747            boolean migrateAppData) {
23748        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23749    }
23750
23751    /**
23752     * Reconcile all app data on given mounted volume.
23753     * <p>
23754     * Destroys app data that isn't expected, either due to uninstallation or
23755     * reinstallation on another volume.
23756     * <p>
23757     * Verifies that directories exist and that ownership and labeling is
23758     * correct for all installed apps.
23759     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23760     */
23761    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23762            boolean migrateAppData, boolean onlyCoreApps) {
23763        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23764                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23765        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23766
23767        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23768        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23769
23770        // First look for stale data that doesn't belong, and check if things
23771        // have changed since we did our last restorecon
23772        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23773            if (StorageManager.isFileEncryptedNativeOrEmulated()
23774                    && !StorageManager.isUserKeyUnlocked(userId)) {
23775                throw new RuntimeException(
23776                        "Yikes, someone asked us to reconcile CE storage while " + userId
23777                                + " was still locked; this would have caused massive data loss!");
23778            }
23779
23780            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23781            for (File file : files) {
23782                final String packageName = file.getName();
23783                try {
23784                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23785                } catch (PackageManagerException e) {
23786                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23787                    try {
23788                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23789                                StorageManager.FLAG_STORAGE_CE, 0);
23790                    } catch (InstallerException e2) {
23791                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23792                    }
23793                }
23794            }
23795        }
23796        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23797            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23798            for (File file : files) {
23799                final String packageName = file.getName();
23800                try {
23801                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23802                } catch (PackageManagerException e) {
23803                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23804                    try {
23805                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23806                                StorageManager.FLAG_STORAGE_DE, 0);
23807                    } catch (InstallerException e2) {
23808                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23809                    }
23810                }
23811            }
23812        }
23813
23814        // Ensure that data directories are ready to roll for all packages
23815        // installed for this volume and user
23816        final List<PackageSetting> packages;
23817        synchronized (mPackages) {
23818            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23819        }
23820        int preparedCount = 0;
23821        for (PackageSetting ps : packages) {
23822            final String packageName = ps.name;
23823            if (ps.pkg == null) {
23824                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23825                // TODO: might be due to legacy ASEC apps; we should circle back
23826                // and reconcile again once they're scanned
23827                continue;
23828            }
23829            // Skip non-core apps if requested
23830            if (onlyCoreApps && !ps.pkg.coreApp) {
23831                result.add(packageName);
23832                continue;
23833            }
23834
23835            if (ps.getInstalled(userId)) {
23836                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23837                preparedCount++;
23838            }
23839        }
23840
23841        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23842        return result;
23843    }
23844
23845    /**
23846     * Prepare app data for the given app just after it was installed or
23847     * upgraded. This method carefully only touches users that it's installed
23848     * for, and it forces a restorecon to handle any seinfo changes.
23849     * <p>
23850     * Verifies that directories exist and that ownership and labeling is
23851     * correct for all installed apps. If there is an ownership mismatch, it
23852     * will try recovering system apps by wiping data; third-party app data is
23853     * left intact.
23854     * <p>
23855     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23856     */
23857    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23858        final PackageSetting ps;
23859        synchronized (mPackages) {
23860            ps = mSettings.mPackages.get(pkg.packageName);
23861            mSettings.writeKernelMappingLPr(ps);
23862        }
23863
23864        final UserManager um = mContext.getSystemService(UserManager.class);
23865        UserManagerInternal umInternal = getUserManagerInternal();
23866        for (UserInfo user : um.getUsers()) {
23867            final int flags;
23868            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23869                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23870            } else if (umInternal.isUserRunning(user.id)) {
23871                flags = StorageManager.FLAG_STORAGE_DE;
23872            } else {
23873                continue;
23874            }
23875
23876            if (ps.getInstalled(user.id)) {
23877                // TODO: when user data is locked, mark that we're still dirty
23878                prepareAppDataLIF(pkg, user.id, flags);
23879            }
23880        }
23881    }
23882
23883    /**
23884     * Prepare app data for the given app.
23885     * <p>
23886     * Verifies that directories exist and that ownership and labeling is
23887     * correct for all installed apps. If there is an ownership mismatch, this
23888     * will try recovering system apps by wiping data; third-party app data is
23889     * left intact.
23890     */
23891    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23892        if (pkg == null) {
23893            Slog.wtf(TAG, "Package was null!", new Throwable());
23894            return;
23895        }
23896        prepareAppDataLeafLIF(pkg, userId, flags);
23897        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23898        for (int i = 0; i < childCount; i++) {
23899            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23900        }
23901    }
23902
23903    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23904            boolean maybeMigrateAppData) {
23905        prepareAppDataLIF(pkg, userId, flags);
23906
23907        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23908            // We may have just shuffled around app data directories, so
23909            // prepare them one more time
23910            prepareAppDataLIF(pkg, userId, flags);
23911        }
23912    }
23913
23914    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23915        if (DEBUG_APP_DATA) {
23916            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23917                    + Integer.toHexString(flags));
23918        }
23919
23920        final String volumeUuid = pkg.volumeUuid;
23921        final String packageName = pkg.packageName;
23922        final ApplicationInfo app = pkg.applicationInfo;
23923        final int appId = UserHandle.getAppId(app.uid);
23924
23925        Preconditions.checkNotNull(app.seInfo);
23926
23927        long ceDataInode = -1;
23928        try {
23929            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23930                    appId, app.seInfo, app.targetSdkVersion);
23931        } catch (InstallerException e) {
23932            if (app.isSystemApp()) {
23933                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23934                        + ", but trying to recover: " + e);
23935                destroyAppDataLeafLIF(pkg, userId, flags);
23936                try {
23937                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23938                            appId, app.seInfo, app.targetSdkVersion);
23939                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23940                } catch (InstallerException e2) {
23941                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23942                }
23943            } else {
23944                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23945            }
23946        }
23947
23948        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23949            // TODO: mark this structure as dirty so we persist it!
23950            synchronized (mPackages) {
23951                final PackageSetting ps = mSettings.mPackages.get(packageName);
23952                if (ps != null) {
23953                    ps.setCeDataInode(ceDataInode, userId);
23954                }
23955            }
23956        }
23957
23958        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23959    }
23960
23961    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23962        if (pkg == null) {
23963            Slog.wtf(TAG, "Package was null!", new Throwable());
23964            return;
23965        }
23966        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23967        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23968        for (int i = 0; i < childCount; i++) {
23969            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23970        }
23971    }
23972
23973    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23974        final String volumeUuid = pkg.volumeUuid;
23975        final String packageName = pkg.packageName;
23976        final ApplicationInfo app = pkg.applicationInfo;
23977
23978        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23979            // Create a native library symlink only if we have native libraries
23980            // and if the native libraries are 32 bit libraries. We do not provide
23981            // this symlink for 64 bit libraries.
23982            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23983                final String nativeLibPath = app.nativeLibraryDir;
23984                try {
23985                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23986                            nativeLibPath, userId);
23987                } catch (InstallerException e) {
23988                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23989                }
23990            }
23991        }
23992    }
23993
23994    /**
23995     * For system apps on non-FBE devices, this method migrates any existing
23996     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23997     * requested by the app.
23998     */
23999    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24000        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24001                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24002            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24003                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24004            try {
24005                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24006                        storageTarget);
24007            } catch (InstallerException e) {
24008                logCriticalInfo(Log.WARN,
24009                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24010            }
24011            return true;
24012        } else {
24013            return false;
24014        }
24015    }
24016
24017    public PackageFreezer freezePackage(String packageName, String killReason) {
24018        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24019    }
24020
24021    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24022        return new PackageFreezer(packageName, userId, killReason);
24023    }
24024
24025    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24026            String killReason) {
24027        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24028    }
24029
24030    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24031            String killReason) {
24032        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24033            return new PackageFreezer();
24034        } else {
24035            return freezePackage(packageName, userId, killReason);
24036        }
24037    }
24038
24039    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24040            String killReason) {
24041        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24042    }
24043
24044    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24045            String killReason) {
24046        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24047            return new PackageFreezer();
24048        } else {
24049            return freezePackage(packageName, userId, killReason);
24050        }
24051    }
24052
24053    /**
24054     * Class that freezes and kills the given package upon creation, and
24055     * unfreezes it upon closing. This is typically used when doing surgery on
24056     * app code/data to prevent the app from running while you're working.
24057     */
24058    private class PackageFreezer implements AutoCloseable {
24059        private final String mPackageName;
24060        private final PackageFreezer[] mChildren;
24061
24062        private final boolean mWeFroze;
24063
24064        private final AtomicBoolean mClosed = new AtomicBoolean();
24065        private final CloseGuard mCloseGuard = CloseGuard.get();
24066
24067        /**
24068         * Create and return a stub freezer that doesn't actually do anything,
24069         * typically used when someone requested
24070         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24071         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24072         */
24073        public PackageFreezer() {
24074            mPackageName = null;
24075            mChildren = null;
24076            mWeFroze = false;
24077            mCloseGuard.open("close");
24078        }
24079
24080        public PackageFreezer(String packageName, int userId, String killReason) {
24081            synchronized (mPackages) {
24082                mPackageName = packageName;
24083                mWeFroze = mFrozenPackages.add(mPackageName);
24084
24085                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24086                if (ps != null) {
24087                    killApplication(ps.name, ps.appId, userId, killReason);
24088                }
24089
24090                final PackageParser.Package p = mPackages.get(packageName);
24091                if (p != null && p.childPackages != null) {
24092                    final int N = p.childPackages.size();
24093                    mChildren = new PackageFreezer[N];
24094                    for (int i = 0; i < N; i++) {
24095                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24096                                userId, killReason);
24097                    }
24098                } else {
24099                    mChildren = null;
24100                }
24101            }
24102            mCloseGuard.open("close");
24103        }
24104
24105        @Override
24106        protected void finalize() throws Throwable {
24107            try {
24108                if (mCloseGuard != null) {
24109                    mCloseGuard.warnIfOpen();
24110                }
24111
24112                close();
24113            } finally {
24114                super.finalize();
24115            }
24116        }
24117
24118        @Override
24119        public void close() {
24120            mCloseGuard.close();
24121            if (mClosed.compareAndSet(false, true)) {
24122                synchronized (mPackages) {
24123                    if (mWeFroze) {
24124                        mFrozenPackages.remove(mPackageName);
24125                    }
24126
24127                    if (mChildren != null) {
24128                        for (PackageFreezer freezer : mChildren) {
24129                            freezer.close();
24130                        }
24131                    }
24132                }
24133            }
24134        }
24135    }
24136
24137    /**
24138     * Verify that given package is currently frozen.
24139     */
24140    private void checkPackageFrozen(String packageName) {
24141        synchronized (mPackages) {
24142            if (!mFrozenPackages.contains(packageName)) {
24143                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24144            }
24145        }
24146    }
24147
24148    @Override
24149    public int movePackage(final String packageName, final String volumeUuid) {
24150        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24151
24152        final int callingUid = Binder.getCallingUid();
24153        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24154        final int moveId = mNextMoveId.getAndIncrement();
24155        mHandler.post(new Runnable() {
24156            @Override
24157            public void run() {
24158                try {
24159                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24160                } catch (PackageManagerException e) {
24161                    Slog.w(TAG, "Failed to move " + packageName, e);
24162                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24163                }
24164            }
24165        });
24166        return moveId;
24167    }
24168
24169    private void movePackageInternal(final String packageName, final String volumeUuid,
24170            final int moveId, final int callingUid, UserHandle user)
24171                    throws PackageManagerException {
24172        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24173        final PackageManager pm = mContext.getPackageManager();
24174
24175        final boolean currentAsec;
24176        final String currentVolumeUuid;
24177        final File codeFile;
24178        final String installerPackageName;
24179        final String packageAbiOverride;
24180        final int appId;
24181        final String seinfo;
24182        final String label;
24183        final int targetSdkVersion;
24184        final PackageFreezer freezer;
24185        final int[] installedUserIds;
24186
24187        // reader
24188        synchronized (mPackages) {
24189            final PackageParser.Package pkg = mPackages.get(packageName);
24190            final PackageSetting ps = mSettings.mPackages.get(packageName);
24191            if (pkg == null
24192                    || ps == null
24193                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24194                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24195            }
24196            if (pkg.applicationInfo.isSystemApp()) {
24197                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24198                        "Cannot move system application");
24199            }
24200
24201            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24202            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24203                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24204            if (isInternalStorage && !allow3rdPartyOnInternal) {
24205                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24206                        "3rd party apps are not allowed on internal storage");
24207            }
24208
24209            if (pkg.applicationInfo.isExternalAsec()) {
24210                currentAsec = true;
24211                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24212            } else if (pkg.applicationInfo.isForwardLocked()) {
24213                currentAsec = true;
24214                currentVolumeUuid = "forward_locked";
24215            } else {
24216                currentAsec = false;
24217                currentVolumeUuid = ps.volumeUuid;
24218
24219                final File probe = new File(pkg.codePath);
24220                final File probeOat = new File(probe, "oat");
24221                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24222                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24223                            "Move only supported for modern cluster style installs");
24224                }
24225            }
24226
24227            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24228                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24229                        "Package already moved to " + volumeUuid);
24230            }
24231            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24232                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24233                        "Device admin cannot be moved");
24234            }
24235
24236            if (mFrozenPackages.contains(packageName)) {
24237                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24238                        "Failed to move already frozen package");
24239            }
24240
24241            codeFile = new File(pkg.codePath);
24242            installerPackageName = ps.installerPackageName;
24243            packageAbiOverride = ps.cpuAbiOverrideString;
24244            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24245            seinfo = pkg.applicationInfo.seInfo;
24246            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24247            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24248            freezer = freezePackage(packageName, "movePackageInternal");
24249            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24250        }
24251
24252        final Bundle extras = new Bundle();
24253        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24254        extras.putString(Intent.EXTRA_TITLE, label);
24255        mMoveCallbacks.notifyCreated(moveId, extras);
24256
24257        int installFlags;
24258        final boolean moveCompleteApp;
24259        final File measurePath;
24260
24261        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24262            installFlags = INSTALL_INTERNAL;
24263            moveCompleteApp = !currentAsec;
24264            measurePath = Environment.getDataAppDirectory(volumeUuid);
24265        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24266            installFlags = INSTALL_EXTERNAL;
24267            moveCompleteApp = false;
24268            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24269        } else {
24270            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24271            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24272                    || !volume.isMountedWritable()) {
24273                freezer.close();
24274                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24275                        "Move location not mounted private volume");
24276            }
24277
24278            Preconditions.checkState(!currentAsec);
24279
24280            installFlags = INSTALL_INTERNAL;
24281            moveCompleteApp = true;
24282            measurePath = Environment.getDataAppDirectory(volumeUuid);
24283        }
24284
24285        // If we're moving app data around, we need all the users unlocked
24286        if (moveCompleteApp) {
24287            for (int userId : installedUserIds) {
24288                if (StorageManager.isFileEncryptedNativeOrEmulated()
24289                        && !StorageManager.isUserKeyUnlocked(userId)) {
24290                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24291                            "User " + userId + " must be unlocked");
24292                }
24293            }
24294        }
24295
24296        final PackageStats stats = new PackageStats(null, -1);
24297        synchronized (mInstaller) {
24298            for (int userId : installedUserIds) {
24299                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24300                    freezer.close();
24301                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24302                            "Failed to measure package size");
24303                }
24304            }
24305        }
24306
24307        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24308                + stats.dataSize);
24309
24310        final long startFreeBytes = measurePath.getUsableSpace();
24311        final long sizeBytes;
24312        if (moveCompleteApp) {
24313            sizeBytes = stats.codeSize + stats.dataSize;
24314        } else {
24315            sizeBytes = stats.codeSize;
24316        }
24317
24318        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24319            freezer.close();
24320            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24321                    "Not enough free space to move");
24322        }
24323
24324        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24325
24326        final CountDownLatch installedLatch = new CountDownLatch(1);
24327        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24328            @Override
24329            public void onUserActionRequired(Intent intent) throws RemoteException {
24330                throw new IllegalStateException();
24331            }
24332
24333            @Override
24334            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24335                    Bundle extras) throws RemoteException {
24336                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24337                        + PackageManager.installStatusToString(returnCode, msg));
24338
24339                installedLatch.countDown();
24340                freezer.close();
24341
24342                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24343                switch (status) {
24344                    case PackageInstaller.STATUS_SUCCESS:
24345                        mMoveCallbacks.notifyStatusChanged(moveId,
24346                                PackageManager.MOVE_SUCCEEDED);
24347                        break;
24348                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24349                        mMoveCallbacks.notifyStatusChanged(moveId,
24350                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24351                        break;
24352                    default:
24353                        mMoveCallbacks.notifyStatusChanged(moveId,
24354                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24355                        break;
24356                }
24357            }
24358        };
24359
24360        final MoveInfo move;
24361        if (moveCompleteApp) {
24362            // Kick off a thread to report progress estimates
24363            new Thread() {
24364                @Override
24365                public void run() {
24366                    while (true) {
24367                        try {
24368                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24369                                break;
24370                            }
24371                        } catch (InterruptedException ignored) {
24372                        }
24373
24374                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24375                        final int progress = 10 + (int) MathUtils.constrain(
24376                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24377                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24378                    }
24379                }
24380            }.start();
24381
24382            final String dataAppName = codeFile.getName();
24383            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24384                    dataAppName, appId, seinfo, targetSdkVersion);
24385        } else {
24386            move = null;
24387        }
24388
24389        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24390
24391        final Message msg = mHandler.obtainMessage(INIT_COPY);
24392        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24393        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24394                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24395                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24396                PackageManager.INSTALL_REASON_UNKNOWN);
24397        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24398        msg.obj = params;
24399
24400        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24401                System.identityHashCode(msg.obj));
24402        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24403                System.identityHashCode(msg.obj));
24404
24405        mHandler.sendMessage(msg);
24406    }
24407
24408    @Override
24409    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24410        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24411
24412        final int realMoveId = mNextMoveId.getAndIncrement();
24413        final Bundle extras = new Bundle();
24414        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24415        mMoveCallbacks.notifyCreated(realMoveId, extras);
24416
24417        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24418            @Override
24419            public void onCreated(int moveId, Bundle extras) {
24420                // Ignored
24421            }
24422
24423            @Override
24424            public void onStatusChanged(int moveId, int status, long estMillis) {
24425                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24426            }
24427        };
24428
24429        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24430        storage.setPrimaryStorageUuid(volumeUuid, callback);
24431        return realMoveId;
24432    }
24433
24434    @Override
24435    public int getMoveStatus(int moveId) {
24436        mContext.enforceCallingOrSelfPermission(
24437                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24438        return mMoveCallbacks.mLastStatus.get(moveId);
24439    }
24440
24441    @Override
24442    public void registerMoveCallback(IPackageMoveObserver callback) {
24443        mContext.enforceCallingOrSelfPermission(
24444                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24445        mMoveCallbacks.register(callback);
24446    }
24447
24448    @Override
24449    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24450        mContext.enforceCallingOrSelfPermission(
24451                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24452        mMoveCallbacks.unregister(callback);
24453    }
24454
24455    @Override
24456    public boolean setInstallLocation(int loc) {
24457        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24458                null);
24459        if (getInstallLocation() == loc) {
24460            return true;
24461        }
24462        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24463                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24464            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24465                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24466            return true;
24467        }
24468        return false;
24469   }
24470
24471    @Override
24472    public int getInstallLocation() {
24473        // allow instant app access
24474        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24475                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24476                PackageHelper.APP_INSTALL_AUTO);
24477    }
24478
24479    /** Called by UserManagerService */
24480    void cleanUpUser(UserManagerService userManager, int userHandle) {
24481        synchronized (mPackages) {
24482            mDirtyUsers.remove(userHandle);
24483            mUserNeedsBadging.delete(userHandle);
24484            mSettings.removeUserLPw(userHandle);
24485            mPendingBroadcasts.remove(userHandle);
24486            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24487            removeUnusedPackagesLPw(userManager, userHandle);
24488        }
24489    }
24490
24491    /**
24492     * We're removing userHandle and would like to remove any downloaded packages
24493     * that are no longer in use by any other user.
24494     * @param userHandle the user being removed
24495     */
24496    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24497        final boolean DEBUG_CLEAN_APKS = false;
24498        int [] users = userManager.getUserIds();
24499        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24500        while (psit.hasNext()) {
24501            PackageSetting ps = psit.next();
24502            if (ps.pkg == null) {
24503                continue;
24504            }
24505            final String packageName = ps.pkg.packageName;
24506            // Skip over if system app
24507            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24508                continue;
24509            }
24510            if (DEBUG_CLEAN_APKS) {
24511                Slog.i(TAG, "Checking package " + packageName);
24512            }
24513            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24514            if (keep) {
24515                if (DEBUG_CLEAN_APKS) {
24516                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24517                }
24518            } else {
24519                for (int i = 0; i < users.length; i++) {
24520                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24521                        keep = true;
24522                        if (DEBUG_CLEAN_APKS) {
24523                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24524                                    + users[i]);
24525                        }
24526                        break;
24527                    }
24528                }
24529            }
24530            if (!keep) {
24531                if (DEBUG_CLEAN_APKS) {
24532                    Slog.i(TAG, "  Removing package " + packageName);
24533                }
24534                mHandler.post(new Runnable() {
24535                    public void run() {
24536                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24537                                userHandle, 0);
24538                    } //end run
24539                });
24540            }
24541        }
24542    }
24543
24544    /** Called by UserManagerService */
24545    void createNewUser(int userId, String[] disallowedPackages) {
24546        synchronized (mInstallLock) {
24547            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24548        }
24549        synchronized (mPackages) {
24550            scheduleWritePackageRestrictionsLocked(userId);
24551            scheduleWritePackageListLocked(userId);
24552            applyFactoryDefaultBrowserLPw(userId);
24553            primeDomainVerificationsLPw(userId);
24554        }
24555    }
24556
24557    void onNewUserCreated(final int userId) {
24558        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24559        // If permission review for legacy apps is required, we represent
24560        // dagerous permissions for such apps as always granted runtime
24561        // permissions to keep per user flag state whether review is needed.
24562        // Hence, if a new user is added we have to propagate dangerous
24563        // permission grants for these legacy apps.
24564        if (mPermissionReviewRequired) {
24565            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24566                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24567        }
24568    }
24569
24570    @Override
24571    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24572        mContext.enforceCallingOrSelfPermission(
24573                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24574                "Only package verification agents can read the verifier device identity");
24575
24576        synchronized (mPackages) {
24577            return mSettings.getVerifierDeviceIdentityLPw();
24578        }
24579    }
24580
24581    @Override
24582    public void setPermissionEnforced(String permission, boolean enforced) {
24583        // TODO: Now that we no longer change GID for storage, this should to away.
24584        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24585                "setPermissionEnforced");
24586        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24587            synchronized (mPackages) {
24588                if (mSettings.mReadExternalStorageEnforced == null
24589                        || mSettings.mReadExternalStorageEnforced != enforced) {
24590                    mSettings.mReadExternalStorageEnforced = enforced;
24591                    mSettings.writeLPr();
24592                }
24593            }
24594            // kill any non-foreground processes so we restart them and
24595            // grant/revoke the GID.
24596            final IActivityManager am = ActivityManager.getService();
24597            if (am != null) {
24598                final long token = Binder.clearCallingIdentity();
24599                try {
24600                    am.killProcessesBelowForeground("setPermissionEnforcement");
24601                } catch (RemoteException e) {
24602                } finally {
24603                    Binder.restoreCallingIdentity(token);
24604                }
24605            }
24606        } else {
24607            throw new IllegalArgumentException("No selective enforcement for " + permission);
24608        }
24609    }
24610
24611    @Override
24612    @Deprecated
24613    public boolean isPermissionEnforced(String permission) {
24614        // allow instant applications
24615        return true;
24616    }
24617
24618    @Override
24619    public boolean isStorageLow() {
24620        // allow instant applications
24621        final long token = Binder.clearCallingIdentity();
24622        try {
24623            final DeviceStorageMonitorInternal
24624                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24625            if (dsm != null) {
24626                return dsm.isMemoryLow();
24627            } else {
24628                return false;
24629            }
24630        } finally {
24631            Binder.restoreCallingIdentity(token);
24632        }
24633    }
24634
24635    @Override
24636    public IPackageInstaller getPackageInstaller() {
24637        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24638            return null;
24639        }
24640        return mInstallerService;
24641    }
24642
24643    private boolean userNeedsBadging(int userId) {
24644        int index = mUserNeedsBadging.indexOfKey(userId);
24645        if (index < 0) {
24646            final UserInfo userInfo;
24647            final long token = Binder.clearCallingIdentity();
24648            try {
24649                userInfo = sUserManager.getUserInfo(userId);
24650            } finally {
24651                Binder.restoreCallingIdentity(token);
24652            }
24653            final boolean b;
24654            if (userInfo != null && userInfo.isManagedProfile()) {
24655                b = true;
24656            } else {
24657                b = false;
24658            }
24659            mUserNeedsBadging.put(userId, b);
24660            return b;
24661        }
24662        return mUserNeedsBadging.valueAt(index);
24663    }
24664
24665    @Override
24666    public KeySet getKeySetByAlias(String packageName, String alias) {
24667        if (packageName == null || alias == null) {
24668            return null;
24669        }
24670        synchronized(mPackages) {
24671            final PackageParser.Package pkg = mPackages.get(packageName);
24672            if (pkg == null) {
24673                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24674                throw new IllegalArgumentException("Unknown package: " + packageName);
24675            }
24676            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24677            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24678                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24679                throw new IllegalArgumentException("Unknown package: " + packageName);
24680            }
24681            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24682            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24683        }
24684    }
24685
24686    @Override
24687    public KeySet getSigningKeySet(String packageName) {
24688        if (packageName == null) {
24689            return null;
24690        }
24691        synchronized(mPackages) {
24692            final int callingUid = Binder.getCallingUid();
24693            final int callingUserId = UserHandle.getUserId(callingUid);
24694            final PackageParser.Package pkg = mPackages.get(packageName);
24695            if (pkg == null) {
24696                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24697                throw new IllegalArgumentException("Unknown package: " + packageName);
24698            }
24699            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24700            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24701                // filter and pretend the package doesn't exist
24702                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24703                        + ", uid:" + callingUid);
24704                throw new IllegalArgumentException("Unknown package: " + packageName);
24705            }
24706            if (pkg.applicationInfo.uid != callingUid
24707                    && Process.SYSTEM_UID != callingUid) {
24708                throw new SecurityException("May not access signing KeySet of other apps.");
24709            }
24710            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24711            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24712        }
24713    }
24714
24715    @Override
24716    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24717        final int callingUid = Binder.getCallingUid();
24718        if (getInstantAppPackageName(callingUid) != null) {
24719            return false;
24720        }
24721        if (packageName == null || ks == null) {
24722            return false;
24723        }
24724        synchronized(mPackages) {
24725            final PackageParser.Package pkg = mPackages.get(packageName);
24726            if (pkg == null
24727                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24728                            UserHandle.getUserId(callingUid))) {
24729                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24730                throw new IllegalArgumentException("Unknown package: " + packageName);
24731            }
24732            IBinder ksh = ks.getToken();
24733            if (ksh instanceof KeySetHandle) {
24734                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24735                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24736            }
24737            return false;
24738        }
24739    }
24740
24741    @Override
24742    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24743        final int callingUid = Binder.getCallingUid();
24744        if (getInstantAppPackageName(callingUid) != null) {
24745            return false;
24746        }
24747        if (packageName == null || ks == null) {
24748            return false;
24749        }
24750        synchronized(mPackages) {
24751            final PackageParser.Package pkg = mPackages.get(packageName);
24752            if (pkg == null
24753                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24754                            UserHandle.getUserId(callingUid))) {
24755                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24756                throw new IllegalArgumentException("Unknown package: " + packageName);
24757            }
24758            IBinder ksh = ks.getToken();
24759            if (ksh instanceof KeySetHandle) {
24760                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24761                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24762            }
24763            return false;
24764        }
24765    }
24766
24767    private void deletePackageIfUnusedLPr(final String packageName) {
24768        PackageSetting ps = mSettings.mPackages.get(packageName);
24769        if (ps == null) {
24770            return;
24771        }
24772        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24773            // TODO Implement atomic delete if package is unused
24774            // It is currently possible that the package will be deleted even if it is installed
24775            // after this method returns.
24776            mHandler.post(new Runnable() {
24777                public void run() {
24778                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24779                            0, PackageManager.DELETE_ALL_USERS);
24780                }
24781            });
24782        }
24783    }
24784
24785    /**
24786     * Check and throw if the given before/after packages would be considered a
24787     * downgrade.
24788     */
24789    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24790            throws PackageManagerException {
24791        if (after.versionCode < before.mVersionCode) {
24792            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24793                    "Update version code " + after.versionCode + " is older than current "
24794                    + before.mVersionCode);
24795        } else if (after.versionCode == before.mVersionCode) {
24796            if (after.baseRevisionCode < before.baseRevisionCode) {
24797                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24798                        "Update base revision code " + after.baseRevisionCode
24799                        + " is older than current " + before.baseRevisionCode);
24800            }
24801
24802            if (!ArrayUtils.isEmpty(after.splitNames)) {
24803                for (int i = 0; i < after.splitNames.length; i++) {
24804                    final String splitName = after.splitNames[i];
24805                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24806                    if (j != -1) {
24807                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24808                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24809                                    "Update split " + splitName + " revision code "
24810                                    + after.splitRevisionCodes[i] + " is older than current "
24811                                    + before.splitRevisionCodes[j]);
24812                        }
24813                    }
24814                }
24815            }
24816        }
24817    }
24818
24819    private static class MoveCallbacks extends Handler {
24820        private static final int MSG_CREATED = 1;
24821        private static final int MSG_STATUS_CHANGED = 2;
24822
24823        private final RemoteCallbackList<IPackageMoveObserver>
24824                mCallbacks = new RemoteCallbackList<>();
24825
24826        private final SparseIntArray mLastStatus = new SparseIntArray();
24827
24828        public MoveCallbacks(Looper looper) {
24829            super(looper);
24830        }
24831
24832        public void register(IPackageMoveObserver callback) {
24833            mCallbacks.register(callback);
24834        }
24835
24836        public void unregister(IPackageMoveObserver callback) {
24837            mCallbacks.unregister(callback);
24838        }
24839
24840        @Override
24841        public void handleMessage(Message msg) {
24842            final SomeArgs args = (SomeArgs) msg.obj;
24843            final int n = mCallbacks.beginBroadcast();
24844            for (int i = 0; i < n; i++) {
24845                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24846                try {
24847                    invokeCallback(callback, msg.what, args);
24848                } catch (RemoteException ignored) {
24849                }
24850            }
24851            mCallbacks.finishBroadcast();
24852            args.recycle();
24853        }
24854
24855        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24856                throws RemoteException {
24857            switch (what) {
24858                case MSG_CREATED: {
24859                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24860                    break;
24861                }
24862                case MSG_STATUS_CHANGED: {
24863                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24864                    break;
24865                }
24866            }
24867        }
24868
24869        private void notifyCreated(int moveId, Bundle extras) {
24870            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24871
24872            final SomeArgs args = SomeArgs.obtain();
24873            args.argi1 = moveId;
24874            args.arg2 = extras;
24875            obtainMessage(MSG_CREATED, args).sendToTarget();
24876        }
24877
24878        private void notifyStatusChanged(int moveId, int status) {
24879            notifyStatusChanged(moveId, status, -1);
24880        }
24881
24882        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24883            Slog.v(TAG, "Move " + moveId + " status " + status);
24884
24885            final SomeArgs args = SomeArgs.obtain();
24886            args.argi1 = moveId;
24887            args.argi2 = status;
24888            args.arg3 = estMillis;
24889            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24890
24891            synchronized (mLastStatus) {
24892                mLastStatus.put(moveId, status);
24893            }
24894        }
24895    }
24896
24897    private final static class OnPermissionChangeListeners extends Handler {
24898        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24899
24900        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24901                new RemoteCallbackList<>();
24902
24903        public OnPermissionChangeListeners(Looper looper) {
24904            super(looper);
24905        }
24906
24907        @Override
24908        public void handleMessage(Message msg) {
24909            switch (msg.what) {
24910                case MSG_ON_PERMISSIONS_CHANGED: {
24911                    final int uid = msg.arg1;
24912                    handleOnPermissionsChanged(uid);
24913                } break;
24914            }
24915        }
24916
24917        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24918            mPermissionListeners.register(listener);
24919
24920        }
24921
24922        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24923            mPermissionListeners.unregister(listener);
24924        }
24925
24926        public void onPermissionsChanged(int uid) {
24927            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24928                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24929            }
24930        }
24931
24932        private void handleOnPermissionsChanged(int uid) {
24933            final int count = mPermissionListeners.beginBroadcast();
24934            try {
24935                for (int i = 0; i < count; i++) {
24936                    IOnPermissionsChangeListener callback = mPermissionListeners
24937                            .getBroadcastItem(i);
24938                    try {
24939                        callback.onPermissionsChanged(uid);
24940                    } catch (RemoteException e) {
24941                        Log.e(TAG, "Permission listener is dead", e);
24942                    }
24943                }
24944            } finally {
24945                mPermissionListeners.finishBroadcast();
24946            }
24947        }
24948    }
24949
24950    private class PackageManagerNative extends IPackageManagerNative.Stub {
24951        @Override
24952        public String[] getNamesForUids(int[] uids) throws RemoteException {
24953            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24954            // massage results so they can be parsed by the native binder
24955            for (int i = results.length - 1; i >= 0; --i) {
24956                if (results[i] == null) {
24957                    results[i] = "";
24958                }
24959            }
24960            return results;
24961        }
24962    }
24963
24964    private class PackageManagerInternalImpl extends PackageManagerInternal {
24965        @Override
24966        public void setLocationPackagesProvider(PackagesProvider provider) {
24967            synchronized (mPackages) {
24968                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24969            }
24970        }
24971
24972        @Override
24973        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24974            synchronized (mPackages) {
24975                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24976            }
24977        }
24978
24979        @Override
24980        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24981            synchronized (mPackages) {
24982                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24983            }
24984        }
24985
24986        @Override
24987        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24988            synchronized (mPackages) {
24989                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24990            }
24991        }
24992
24993        @Override
24994        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24995            synchronized (mPackages) {
24996                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24997            }
24998        }
24999
25000        @Override
25001        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25002            synchronized (mPackages) {
25003                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25004            }
25005        }
25006
25007        @Override
25008        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25009            synchronized (mPackages) {
25010                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25011                        packageName, userId);
25012            }
25013        }
25014
25015        @Override
25016        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25017            synchronized (mPackages) {
25018                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25019                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25020                        packageName, userId);
25021            }
25022        }
25023
25024        @Override
25025        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25026            synchronized (mPackages) {
25027                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25028                        packageName, userId);
25029            }
25030        }
25031
25032        @Override
25033        public void setKeepUninstalledPackages(final List<String> packageList) {
25034            Preconditions.checkNotNull(packageList);
25035            List<String> removedFromList = null;
25036            synchronized (mPackages) {
25037                if (mKeepUninstalledPackages != null) {
25038                    final int packagesCount = mKeepUninstalledPackages.size();
25039                    for (int i = 0; i < packagesCount; i++) {
25040                        String oldPackage = mKeepUninstalledPackages.get(i);
25041                        if (packageList != null && packageList.contains(oldPackage)) {
25042                            continue;
25043                        }
25044                        if (removedFromList == null) {
25045                            removedFromList = new ArrayList<>();
25046                        }
25047                        removedFromList.add(oldPackage);
25048                    }
25049                }
25050                mKeepUninstalledPackages = new ArrayList<>(packageList);
25051                if (removedFromList != null) {
25052                    final int removedCount = removedFromList.size();
25053                    for (int i = 0; i < removedCount; i++) {
25054                        deletePackageIfUnusedLPr(removedFromList.get(i));
25055                    }
25056                }
25057            }
25058        }
25059
25060        @Override
25061        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25062            synchronized (mPackages) {
25063                // If we do not support permission review, done.
25064                if (!mPermissionReviewRequired) {
25065                    return false;
25066                }
25067
25068                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25069                if (packageSetting == null) {
25070                    return false;
25071                }
25072
25073                // Permission review applies only to apps not supporting the new permission model.
25074                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25075                    return false;
25076                }
25077
25078                // Legacy apps have the permission and get user consent on launch.
25079                PermissionsState permissionsState = packageSetting.getPermissionsState();
25080                return permissionsState.isPermissionReviewRequired(userId);
25081            }
25082        }
25083
25084        @Override
25085        public PackageInfo getPackageInfo(
25086                String packageName, int flags, int filterCallingUid, int userId) {
25087            return PackageManagerService.this
25088                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25089                            flags, filterCallingUid, userId);
25090        }
25091
25092        @Override
25093        public ApplicationInfo getApplicationInfo(
25094                String packageName, int flags, int filterCallingUid, int userId) {
25095            return PackageManagerService.this
25096                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25097        }
25098
25099        @Override
25100        public ActivityInfo getActivityInfo(
25101                ComponentName component, int flags, int filterCallingUid, int userId) {
25102            return PackageManagerService.this
25103                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25104        }
25105
25106        @Override
25107        public List<ResolveInfo> queryIntentActivities(
25108                Intent intent, int flags, int filterCallingUid, int userId) {
25109            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25110            return PackageManagerService.this
25111                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25112                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25113        }
25114
25115        @Override
25116        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25117                int userId) {
25118            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25119        }
25120
25121        @Override
25122        public void setDeviceAndProfileOwnerPackages(
25123                int deviceOwnerUserId, String deviceOwnerPackage,
25124                SparseArray<String> profileOwnerPackages) {
25125            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25126                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25127        }
25128
25129        @Override
25130        public boolean isPackageDataProtected(int userId, String packageName) {
25131            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25132        }
25133
25134        @Override
25135        public boolean isPackageEphemeral(int userId, String packageName) {
25136            synchronized (mPackages) {
25137                final PackageSetting ps = mSettings.mPackages.get(packageName);
25138                return ps != null ? ps.getInstantApp(userId) : false;
25139            }
25140        }
25141
25142        @Override
25143        public boolean wasPackageEverLaunched(String packageName, int userId) {
25144            synchronized (mPackages) {
25145                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25146            }
25147        }
25148
25149        @Override
25150        public void grantRuntimePermission(String packageName, String name, int userId,
25151                boolean overridePolicy) {
25152            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25153                    overridePolicy);
25154        }
25155
25156        @Override
25157        public void revokeRuntimePermission(String packageName, String name, int userId,
25158                boolean overridePolicy) {
25159            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25160                    overridePolicy);
25161        }
25162
25163        @Override
25164        public String getNameForUid(int uid) {
25165            return PackageManagerService.this.getNameForUid(uid);
25166        }
25167
25168        @Override
25169        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25170                Intent origIntent, String resolvedType, String callingPackage,
25171                Bundle verificationBundle, int userId) {
25172            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25173                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25174                    userId);
25175        }
25176
25177        @Override
25178        public void grantEphemeralAccess(int userId, Intent intent,
25179                int targetAppId, int ephemeralAppId) {
25180            synchronized (mPackages) {
25181                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25182                        targetAppId, ephemeralAppId);
25183            }
25184        }
25185
25186        @Override
25187        public boolean isInstantAppInstallerComponent(ComponentName component) {
25188            synchronized (mPackages) {
25189                return mInstantAppInstallerActivity != null
25190                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25191            }
25192        }
25193
25194        @Override
25195        public void pruneInstantApps() {
25196            mInstantAppRegistry.pruneInstantApps();
25197        }
25198
25199        @Override
25200        public String getSetupWizardPackageName() {
25201            return mSetupWizardPackage;
25202        }
25203
25204        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25205            if (policy != null) {
25206                mExternalSourcesPolicy = policy;
25207            }
25208        }
25209
25210        @Override
25211        public boolean isPackagePersistent(String packageName) {
25212            synchronized (mPackages) {
25213                PackageParser.Package pkg = mPackages.get(packageName);
25214                return pkg != null
25215                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25216                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25217                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25218                        : false;
25219            }
25220        }
25221
25222        @Override
25223        public List<PackageInfo> getOverlayPackages(int userId) {
25224            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25225            synchronized (mPackages) {
25226                for (PackageParser.Package p : mPackages.values()) {
25227                    if (p.mOverlayTarget != null) {
25228                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25229                        if (pkg != null) {
25230                            overlayPackages.add(pkg);
25231                        }
25232                    }
25233                }
25234            }
25235            return overlayPackages;
25236        }
25237
25238        @Override
25239        public List<String> getTargetPackageNames(int userId) {
25240            List<String> targetPackages = new ArrayList<>();
25241            synchronized (mPackages) {
25242                for (PackageParser.Package p : mPackages.values()) {
25243                    if (p.mOverlayTarget == null) {
25244                        targetPackages.add(p.packageName);
25245                    }
25246                }
25247            }
25248            return targetPackages;
25249        }
25250
25251        @Override
25252        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25253                @Nullable List<String> overlayPackageNames) {
25254            synchronized (mPackages) {
25255                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25256                    Slog.e(TAG, "failed to find package " + targetPackageName);
25257                    return false;
25258                }
25259                ArrayList<String> overlayPaths = null;
25260                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25261                    final int N = overlayPackageNames.size();
25262                    overlayPaths = new ArrayList<>(N);
25263                    for (int i = 0; i < N; i++) {
25264                        final String packageName = overlayPackageNames.get(i);
25265                        final PackageParser.Package pkg = mPackages.get(packageName);
25266                        if (pkg == null) {
25267                            Slog.e(TAG, "failed to find package " + packageName);
25268                            return false;
25269                        }
25270                        overlayPaths.add(pkg.baseCodePath);
25271                    }
25272                }
25273
25274                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25275                ps.setOverlayPaths(overlayPaths, userId);
25276                return true;
25277            }
25278        }
25279
25280        @Override
25281        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25282                int flags, int userId) {
25283            return resolveIntentInternal(
25284                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25285        }
25286
25287        @Override
25288        public ResolveInfo resolveService(Intent intent, String resolvedType,
25289                int flags, int userId, int callingUid) {
25290            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25291        }
25292
25293        @Override
25294        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25295            synchronized (mPackages) {
25296                mIsolatedOwners.put(isolatedUid, ownerUid);
25297            }
25298        }
25299
25300        @Override
25301        public void removeIsolatedUid(int isolatedUid) {
25302            synchronized (mPackages) {
25303                mIsolatedOwners.delete(isolatedUid);
25304            }
25305        }
25306
25307        @Override
25308        public int getUidTargetSdkVersion(int uid) {
25309            synchronized (mPackages) {
25310                return getUidTargetSdkVersionLockedLPr(uid);
25311            }
25312        }
25313
25314        @Override
25315        public boolean canAccessInstantApps(int callingUid, int userId) {
25316            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25317        }
25318    }
25319
25320    @Override
25321    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25322        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25323        synchronized (mPackages) {
25324            final long identity = Binder.clearCallingIdentity();
25325            try {
25326                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25327                        packageNames, userId);
25328            } finally {
25329                Binder.restoreCallingIdentity(identity);
25330            }
25331        }
25332    }
25333
25334    @Override
25335    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25336        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25337        synchronized (mPackages) {
25338            final long identity = Binder.clearCallingIdentity();
25339            try {
25340                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25341                        packageNames, userId);
25342            } finally {
25343                Binder.restoreCallingIdentity(identity);
25344            }
25345        }
25346    }
25347
25348    private static void enforceSystemOrPhoneCaller(String tag) {
25349        int callingUid = Binder.getCallingUid();
25350        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25351            throw new SecurityException(
25352                    "Cannot call " + tag + " from UID " + callingUid);
25353        }
25354    }
25355
25356    boolean isHistoricalPackageUsageAvailable() {
25357        return mPackageUsage.isHistoricalPackageUsageAvailable();
25358    }
25359
25360    /**
25361     * Return a <b>copy</b> of the collection of packages known to the package manager.
25362     * @return A copy of the values of mPackages.
25363     */
25364    Collection<PackageParser.Package> getPackages() {
25365        synchronized (mPackages) {
25366            return new ArrayList<>(mPackages.values());
25367        }
25368    }
25369
25370    /**
25371     * Logs process start information (including base APK hash) to the security log.
25372     * @hide
25373     */
25374    @Override
25375    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25376            String apkFile, int pid) {
25377        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25378            return;
25379        }
25380        if (!SecurityLog.isLoggingEnabled()) {
25381            return;
25382        }
25383        Bundle data = new Bundle();
25384        data.putLong("startTimestamp", System.currentTimeMillis());
25385        data.putString("processName", processName);
25386        data.putInt("uid", uid);
25387        data.putString("seinfo", seinfo);
25388        data.putString("apkFile", apkFile);
25389        data.putInt("pid", pid);
25390        Message msg = mProcessLoggingHandler.obtainMessage(
25391                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25392        msg.setData(data);
25393        mProcessLoggingHandler.sendMessage(msg);
25394    }
25395
25396    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25397        return mCompilerStats.getPackageStats(pkgName);
25398    }
25399
25400    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25401        return getOrCreateCompilerPackageStats(pkg.packageName);
25402    }
25403
25404    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25405        return mCompilerStats.getOrCreatePackageStats(pkgName);
25406    }
25407
25408    public void deleteCompilerPackageStats(String pkgName) {
25409        mCompilerStats.deletePackageStats(pkgName);
25410    }
25411
25412    @Override
25413    public int getInstallReason(String packageName, int userId) {
25414        final int callingUid = Binder.getCallingUid();
25415        enforceCrossUserPermission(callingUid, userId,
25416                true /* requireFullPermission */, false /* checkShell */,
25417                "get install reason");
25418        synchronized (mPackages) {
25419            final PackageSetting ps = mSettings.mPackages.get(packageName);
25420            if (filterAppAccessLPr(ps, callingUid, userId)) {
25421                return PackageManager.INSTALL_REASON_UNKNOWN;
25422            }
25423            if (ps != null) {
25424                return ps.getInstallReason(userId);
25425            }
25426        }
25427        return PackageManager.INSTALL_REASON_UNKNOWN;
25428    }
25429
25430    @Override
25431    public boolean canRequestPackageInstalls(String packageName, int userId) {
25432        return canRequestPackageInstallsInternal(packageName, 0, userId,
25433                true /* throwIfPermNotDeclared*/);
25434    }
25435
25436    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25437            boolean throwIfPermNotDeclared) {
25438        int callingUid = Binder.getCallingUid();
25439        int uid = getPackageUid(packageName, 0, userId);
25440        if (callingUid != uid && callingUid != Process.ROOT_UID
25441                && callingUid != Process.SYSTEM_UID) {
25442            throw new SecurityException(
25443                    "Caller uid " + callingUid + " does not own package " + packageName);
25444        }
25445        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25446        if (info == null) {
25447            return false;
25448        }
25449        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25450            return false;
25451        }
25452        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25453        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25454        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25455            if (throwIfPermNotDeclared) {
25456                throw new SecurityException("Need to declare " + appOpPermission
25457                        + " to call this api");
25458            } else {
25459                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25460                return false;
25461            }
25462        }
25463        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25464            return false;
25465        }
25466        if (mExternalSourcesPolicy != null) {
25467            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25468            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25469                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25470            }
25471        }
25472        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25473    }
25474
25475    @Override
25476    public ComponentName getInstantAppResolverSettingsComponent() {
25477        return mInstantAppResolverSettingsComponent;
25478    }
25479
25480    @Override
25481    public ComponentName getInstantAppInstallerComponent() {
25482        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25483            return null;
25484        }
25485        return mInstantAppInstallerActivity == null
25486                ? null : mInstantAppInstallerActivity.getComponentName();
25487    }
25488
25489    @Override
25490    public String getInstantAppAndroidId(String packageName, int userId) {
25491        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25492                "getInstantAppAndroidId");
25493        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25494                true /* requireFullPermission */, false /* checkShell */,
25495                "getInstantAppAndroidId");
25496        // Make sure the target is an Instant App.
25497        if (!isInstantApp(packageName, userId)) {
25498            return null;
25499        }
25500        synchronized (mPackages) {
25501            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25502        }
25503    }
25504
25505    boolean canHaveOatDir(String packageName) {
25506        synchronized (mPackages) {
25507            PackageParser.Package p = mPackages.get(packageName);
25508            if (p == null) {
25509                return false;
25510            }
25511            return p.canHaveOatDir();
25512        }
25513    }
25514
25515    private String getOatDir(PackageParser.Package pkg) {
25516        if (!pkg.canHaveOatDir()) {
25517            return null;
25518        }
25519        File codePath = new File(pkg.codePath);
25520        if (codePath.isDirectory()) {
25521            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25522        }
25523        return null;
25524    }
25525
25526    void deleteOatArtifactsOfPackage(String packageName) {
25527        final String[] instructionSets;
25528        final List<String> codePaths;
25529        final String oatDir;
25530        final PackageParser.Package pkg;
25531        synchronized (mPackages) {
25532            pkg = mPackages.get(packageName);
25533        }
25534        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25535        codePaths = pkg.getAllCodePaths();
25536        oatDir = getOatDir(pkg);
25537
25538        for (String codePath : codePaths) {
25539            for (String isa : instructionSets) {
25540                try {
25541                    mInstaller.deleteOdex(codePath, isa, oatDir);
25542                } catch (InstallerException e) {
25543                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25544                }
25545            }
25546        }
25547    }
25548
25549    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25550        Set<String> unusedPackages = new HashSet<>();
25551        long currentTimeInMillis = System.currentTimeMillis();
25552        synchronized (mPackages) {
25553            for (PackageParser.Package pkg : mPackages.values()) {
25554                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25555                if (ps == null) {
25556                    continue;
25557                }
25558                PackageDexUsage.PackageUseInfo packageUseInfo =
25559                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25560                if (PackageManagerServiceUtils
25561                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25562                                downgradeTimeThresholdMillis, packageUseInfo,
25563                                pkg.getLatestPackageUseTimeInMills(),
25564                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25565                    unusedPackages.add(pkg.packageName);
25566                }
25567            }
25568        }
25569        return unusedPackages;
25570    }
25571}
25572
25573interface PackageSender {
25574    void sendPackageBroadcast(final String action, final String pkg,
25575        final Bundle extras, final int flags, final String targetPkg,
25576        final IIntentReceiver finishedReceiver, final int[] userIds);
25577    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25578        boolean includeStopped, int appId, int... userIds);
25579}
25580