PackageManagerService.java revision ce54397368dc98182d7b4eb2ff3c142bbd87e39d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.storage.DeviceStorageMonitorInternal;
287
288import dalvik.system.CloseGuard;
289import dalvik.system.DexFile;
290import dalvik.system.VMRuntime;
291
292import libcore.io.IoUtils;
293import libcore.util.EmptyArray;
294
295import org.xmlpull.v1.XmlPullParser;
296import org.xmlpull.v1.XmlPullParserException;
297import org.xmlpull.v1.XmlSerializer;
298
299import java.io.BufferedOutputStream;
300import java.io.BufferedReader;
301import java.io.ByteArrayInputStream;
302import java.io.ByteArrayOutputStream;
303import java.io.File;
304import java.io.FileDescriptor;
305import java.io.FileInputStream;
306import java.io.FileOutputStream;
307import java.io.FileReader;
308import java.io.FilenameFilter;
309import java.io.IOException;
310import java.io.PrintWriter;
311import java.lang.annotation.Retention;
312import java.lang.annotation.RetentionPolicy;
313import java.nio.charset.StandardCharsets;
314import java.security.DigestInputStream;
315import java.security.MessageDigest;
316import java.security.NoSuchAlgorithmException;
317import java.security.PublicKey;
318import java.security.SecureRandom;
319import java.security.cert.Certificate;
320import java.security.cert.CertificateEncodingException;
321import java.security.cert.CertificateException;
322import java.text.SimpleDateFormat;
323import java.util.ArrayList;
324import java.util.Arrays;
325import java.util.Collection;
326import java.util.Collections;
327import java.util.Comparator;
328import java.util.Date;
329import java.util.HashMap;
330import java.util.HashSet;
331import java.util.Iterator;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564
565    public static final int REASON_LAST = REASON_AB_OTA;
566
567    /** All dangerous permission names in the same order as the events in MetricsEvent */
568    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
569            Manifest.permission.READ_CALENDAR,
570            Manifest.permission.WRITE_CALENDAR,
571            Manifest.permission.CAMERA,
572            Manifest.permission.READ_CONTACTS,
573            Manifest.permission.WRITE_CONTACTS,
574            Manifest.permission.GET_ACCOUNTS,
575            Manifest.permission.ACCESS_FINE_LOCATION,
576            Manifest.permission.ACCESS_COARSE_LOCATION,
577            Manifest.permission.RECORD_AUDIO,
578            Manifest.permission.READ_PHONE_STATE,
579            Manifest.permission.CALL_PHONE,
580            Manifest.permission.READ_CALL_LOG,
581            Manifest.permission.WRITE_CALL_LOG,
582            Manifest.permission.ADD_VOICEMAIL,
583            Manifest.permission.USE_SIP,
584            Manifest.permission.PROCESS_OUTGOING_CALLS,
585            Manifest.permission.READ_CELL_BROADCASTS,
586            Manifest.permission.BODY_SENSORS,
587            Manifest.permission.SEND_SMS,
588            Manifest.permission.RECEIVE_SMS,
589            Manifest.permission.READ_SMS,
590            Manifest.permission.RECEIVE_WAP_PUSH,
591            Manifest.permission.RECEIVE_MMS,
592            Manifest.permission.READ_EXTERNAL_STORAGE,
593            Manifest.permission.WRITE_EXTERNAL_STORAGE,
594            Manifest.permission.READ_PHONE_NUMBERS,
595            Manifest.permission.ANSWER_PHONE_CALLS);
596
597
598    /**
599     * Version number for the package parser cache. Increment this whenever the format or
600     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
601     */
602    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
603
604    /**
605     * Whether the package parser cache is enabled.
606     */
607    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
608
609    final ServiceThread mHandlerThread;
610
611    final PackageHandler mHandler;
612
613    private final ProcessLoggingHandler mProcessLoggingHandler;
614
615    /**
616     * Messages for {@link #mHandler} that need to wait for system ready before
617     * being dispatched.
618     */
619    private ArrayList<Message> mPostSystemReadyMessages;
620
621    final int mSdkVersion = Build.VERSION.SDK_INT;
622
623    final Context mContext;
624    final boolean mFactoryTest;
625    final boolean mOnlyCore;
626    final DisplayMetrics mMetrics;
627    final int mDefParseFlags;
628    final String[] mSeparateProcesses;
629    final boolean mIsUpgrade;
630    final boolean mIsPreNUpgrade;
631    final boolean mIsPreNMR1Upgrade;
632
633    // Have we told the Activity Manager to whitelist the default container service by uid yet?
634    @GuardedBy("mPackages")
635    boolean mDefaultContainerWhitelisted = false;
636
637    @GuardedBy("mPackages")
638    private boolean mDexOptDialogShown;
639
640    /** The location for ASEC container files on internal storage. */
641    final String mAsecInternalPath;
642
643    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
644    // LOCK HELD.  Can be called with mInstallLock held.
645    @GuardedBy("mInstallLock")
646    final Installer mInstaller;
647
648    /** Directory where installed third-party apps stored */
649    final File mAppInstallDir;
650
651    /**
652     * Directory to which applications installed internally have their
653     * 32 bit native libraries copied.
654     */
655    private File mAppLib32InstallDir;
656
657    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
658    // apps.
659    final File mDrmAppPrivateInstallDir;
660
661    // ----------------------------------------------------------------
662
663    // Lock for state used when installing and doing other long running
664    // operations.  Methods that must be called with this lock held have
665    // the suffix "LI".
666    final Object mInstallLock = new Object();
667
668    // ----------------------------------------------------------------
669
670    // Keys are String (package name), values are Package.  This also serves
671    // as the lock for the global state.  Methods that must be called with
672    // this lock held have the prefix "LP".
673    @GuardedBy("mPackages")
674    final ArrayMap<String, PackageParser.Package> mPackages =
675            new ArrayMap<String, PackageParser.Package>();
676
677    final ArrayMap<String, Set<String>> mKnownCodebase =
678            new ArrayMap<String, Set<String>>();
679
680    // Keys are isolated uids and values are the uid of the application
681    // that created the isolated proccess.
682    @GuardedBy("mPackages")
683    final SparseIntArray mIsolatedOwners = new SparseIntArray();
684
685    /**
686     * Tracks new system packages [received in an OTA] that we expect to
687     * find updated user-installed versions. Keys are package name, values
688     * are package location.
689     */
690    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
691    /**
692     * Tracks high priority intent filters for protected actions. During boot, certain
693     * filter actions are protected and should never be allowed to have a high priority
694     * intent filter for them. However, there is one, and only one exception -- the
695     * setup wizard. It must be able to define a high priority intent filter for these
696     * actions to ensure there are no escapes from the wizard. We need to delay processing
697     * of these during boot as we need to look at all of the system packages in order
698     * to know which component is the setup wizard.
699     */
700    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
701    /**
702     * Whether or not processing protected filters should be deferred.
703     */
704    private boolean mDeferProtectedFilters = true;
705
706    /**
707     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
708     */
709    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
710    /**
711     * Whether or not system app permissions should be promoted from install to runtime.
712     */
713    boolean mPromoteSystemApps;
714
715    @GuardedBy("mPackages")
716    final Settings mSettings;
717
718    /**
719     * Set of package names that are currently "frozen", which means active
720     * surgery is being done on the code/data for that package. The platform
721     * will refuse to launch frozen packages to avoid race conditions.
722     *
723     * @see PackageFreezer
724     */
725    @GuardedBy("mPackages")
726    final ArraySet<String> mFrozenPackages = new ArraySet<>();
727
728    final ProtectedPackages mProtectedPackages;
729
730    @GuardedBy("mLoadedVolumes")
731    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
732
733    boolean mFirstBoot;
734
735    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
736
737    // System configuration read by SystemConfig.
738    final int[] mGlobalGids;
739    final SparseArray<ArraySet<String>> mSystemPermissions;
740    @GuardedBy("mAvailableFeatures")
741    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
742
743    // If mac_permissions.xml was found for seinfo labeling.
744    boolean mFoundPolicyFile;
745
746    private final InstantAppRegistry mInstantAppRegistry;
747
748    @GuardedBy("mPackages")
749    int mChangedPackagesSequenceNumber;
750    /**
751     * List of changed [installed, removed or updated] packages.
752     * mapping from user id -> sequence number -> package name
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
756    /**
757     * The sequence number of the last change to a package.
758     * mapping from user id -> package name -> sequence number
759     */
760    @GuardedBy("mPackages")
761    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
762
763    class PackageParserCallback implements PackageParser.Callback {
764        @Override public final boolean hasFeature(String feature) {
765            return PackageManagerService.this.hasSystemFeature(feature, 0);
766        }
767
768        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
769                Collection<PackageParser.Package> allPackages, String targetPackageName) {
770            List<PackageParser.Package> overlayPackages = null;
771            for (PackageParser.Package p : allPackages) {
772                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
773                    if (overlayPackages == null) {
774                        overlayPackages = new ArrayList<PackageParser.Package>();
775                    }
776                    overlayPackages.add(p);
777                }
778            }
779            if (overlayPackages != null) {
780                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
781                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
782                        return p1.mOverlayPriority - p2.mOverlayPriority;
783                    }
784                };
785                Collections.sort(overlayPackages, cmp);
786            }
787            return overlayPackages;
788        }
789
790        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
791                String targetPackageName, String targetPath) {
792            if ("android".equals(targetPackageName)) {
793                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
794                // native AssetManager.
795                return null;
796            }
797            List<PackageParser.Package> overlayPackages =
798                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
799            if (overlayPackages == null || overlayPackages.isEmpty()) {
800                return null;
801            }
802            List<String> overlayPathList = null;
803            for (PackageParser.Package overlayPackage : overlayPackages) {
804                if (targetPath == null) {
805                    if (overlayPathList == null) {
806                        overlayPathList = new ArrayList<String>();
807                    }
808                    overlayPathList.add(overlayPackage.baseCodePath);
809                    continue;
810                }
811
812                try {
813                    // Creates idmaps for system to parse correctly the Android manifest of the
814                    // target package.
815                    //
816                    // OverlayManagerService will update each of them with a correct gid from its
817                    // target package app id.
818                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
819                            UserHandle.getSharedAppGid(
820                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                } catch (InstallerException e) {
826                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
827                            overlayPackage.baseCodePath);
828                }
829            }
830            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
831        }
832
833        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
834            synchronized (mPackages) {
835                return getStaticOverlayPathsLocked(
836                        mPackages.values(), targetPackageName, targetPath);
837            }
838        }
839
840        @Override public final String[] getOverlayApks(String targetPackageName) {
841            return getStaticOverlayPaths(targetPackageName, null);
842        }
843
844        @Override public final String[] getOverlayPaths(String targetPackageName,
845                String targetPath) {
846            return getStaticOverlayPaths(targetPackageName, targetPath);
847        }
848    };
849
850    class ParallelPackageParserCallback extends PackageParserCallback {
851        List<PackageParser.Package> mOverlayPackages = null;
852
853        void findStaticOverlayPackages() {
854            synchronized (mPackages) {
855                for (PackageParser.Package p : mPackages.values()) {
856                    if (p.mIsStaticOverlay) {
857                        if (mOverlayPackages == null) {
858                            mOverlayPackages = new ArrayList<PackageParser.Package>();
859                        }
860                        mOverlayPackages.add(p);
861                    }
862                }
863            }
864        }
865
866        @Override
867        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
868            // We can trust mOverlayPackages without holding mPackages because package uninstall
869            // can't happen while running parallel parsing.
870            // Moreover holding mPackages on each parsing thread causes dead-lock.
871            return mOverlayPackages == null ? null :
872                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
873        }
874    }
875
876    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
877    final ParallelPackageParserCallback mParallelPackageParserCallback =
878            new ParallelPackageParserCallback();
879
880    public static final class SharedLibraryEntry {
881        public final @Nullable String path;
882        public final @Nullable String apk;
883        public final @NonNull SharedLibraryInfo info;
884
885        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
886                String declaringPackageName, int declaringPackageVersionCode) {
887            path = _path;
888            apk = _apk;
889            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
890                    declaringPackageName, declaringPackageVersionCode), null);
891        }
892    }
893
894    // Currently known shared libraries.
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
896    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
897            new ArrayMap<>();
898
899    // All available activities, for your resolving pleasure.
900    final ActivityIntentResolver mActivities =
901            new ActivityIntentResolver();
902
903    // All available receivers, for your resolving pleasure.
904    final ActivityIntentResolver mReceivers =
905            new ActivityIntentResolver();
906
907    // All available services, for your resolving pleasure.
908    final ServiceIntentResolver mServices = new ServiceIntentResolver();
909
910    // All available providers, for your resolving pleasure.
911    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
912
913    // Mapping from provider base names (first directory in content URI codePath)
914    // to the provider information.
915    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
916            new ArrayMap<String, PackageParser.Provider>();
917
918    // Mapping from instrumentation class names to info about them.
919    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
920            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
921
922    // Mapping from permission names to info about them.
923    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
924            new ArrayMap<String, PackageParser.PermissionGroup>();
925
926    // Packages whose data we have transfered into another package, thus
927    // should no longer exist.
928    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
929
930    // Broadcast actions that are only available to the system.
931    @GuardedBy("mProtectedBroadcasts")
932    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
933
934    /** List of packages waiting for verification. */
935    final SparseArray<PackageVerificationState> mPendingVerification
936            = new SparseArray<PackageVerificationState>();
937
938    /** Set of packages associated with each app op permission. */
939    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
940
941    final PackageInstallerService mInstallerService;
942
943    private final PackageDexOptimizer mPackageDexOptimizer;
944    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
945    // is used by other apps).
946    private final DexManager mDexManager;
947
948    private AtomicInteger mNextMoveId = new AtomicInteger();
949    private final MoveCallbacks mMoveCallbacks;
950
951    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
952
953    // Cache of users who need badging.
954    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
955
956    /** Token for keys in mPendingVerification. */
957    private int mPendingVerificationToken = 0;
958
959    volatile boolean mSystemReady;
960    volatile boolean mSafeMode;
961    volatile boolean mHasSystemUidErrors;
962    private volatile boolean mEphemeralAppsDisabled;
963
964    ApplicationInfo mAndroidApplication;
965    final ActivityInfo mResolveActivity = new ActivityInfo();
966    final ResolveInfo mResolveInfo = new ResolveInfo();
967    ComponentName mResolveComponentName;
968    PackageParser.Package mPlatformPackage;
969    ComponentName mCustomResolverComponentName;
970
971    boolean mResolverReplaced = false;
972
973    private final @Nullable ComponentName mIntentFilterVerifierComponent;
974    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
975
976    private int mIntentFilterVerificationToken = 0;
977
978    /** The service connection to the ephemeral resolver */
979    final EphemeralResolverConnection mInstantAppResolverConnection;
980    /** Component used to show resolver settings for Instant Apps */
981    final ComponentName mInstantAppResolverSettingsComponent;
982
983    /** Activity used to install instant applications */
984    ActivityInfo mInstantAppInstallerActivity;
985    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
986
987    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
988            = new SparseArray<IntentFilterVerificationState>();
989
990    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
991
992    // List of packages names to keep cached, even if they are uninstalled for all users
993    private List<String> mKeepUninstalledPackages;
994
995    private UserManagerInternal mUserManagerInternal;
996
997    private DeviceIdleController.LocalService mDeviceIdleController;
998
999    private File mCacheDir;
1000
1001    private ArraySet<String> mPrivappPermissionsViolations;
1002
1003    private Future<?> mPrepareAppDataFuture;
1004
1005    private static class IFVerificationParams {
1006        PackageParser.Package pkg;
1007        boolean replacing;
1008        int userId;
1009        int verifierUid;
1010
1011        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1012                int _userId, int _verifierUid) {
1013            pkg = _pkg;
1014            replacing = _replacing;
1015            userId = _userId;
1016            replacing = _replacing;
1017            verifierUid = _verifierUid;
1018        }
1019    }
1020
1021    private interface IntentFilterVerifier<T extends IntentFilter> {
1022        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1023                                               T filter, String packageName);
1024        void startVerifications(int userId);
1025        void receiveVerificationResponse(int verificationId);
1026    }
1027
1028    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1029        private Context mContext;
1030        private ComponentName mIntentFilterVerifierComponent;
1031        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1032
1033        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1034            mContext = context;
1035            mIntentFilterVerifierComponent = verifierComponent;
1036        }
1037
1038        private String getDefaultScheme() {
1039            return IntentFilter.SCHEME_HTTPS;
1040        }
1041
1042        @Override
1043        public void startVerifications(int userId) {
1044            // Launch verifications requests
1045            int count = mCurrentIntentFilterVerifications.size();
1046            for (int n=0; n<count; n++) {
1047                int verificationId = mCurrentIntentFilterVerifications.get(n);
1048                final IntentFilterVerificationState ivs =
1049                        mIntentFilterVerificationStates.get(verificationId);
1050
1051                String packageName = ivs.getPackageName();
1052
1053                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1054                final int filterCount = filters.size();
1055                ArraySet<String> domainsSet = new ArraySet<>();
1056                for (int m=0; m<filterCount; m++) {
1057                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1058                    domainsSet.addAll(filter.getHostsList());
1059                }
1060                synchronized (mPackages) {
1061                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1062                            packageName, domainsSet) != null) {
1063                        scheduleWriteSettingsLocked();
1064                    }
1065                }
1066                sendVerificationRequest(verificationId, ivs);
1067            }
1068            mCurrentIntentFilterVerifications.clear();
1069        }
1070
1071        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1072            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1075                    verificationId);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1078                    getDefaultScheme());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1081                    ivs.getHostsString());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1084                    ivs.getPackageName());
1085            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1086            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1087
1088            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1089            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1090                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1091                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1092
1093            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1095                    "Sending IntentFilter verification broadcast");
1096        }
1097
1098        public void receiveVerificationResponse(int verificationId) {
1099            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1100
1101            final boolean verified = ivs.isVerified();
1102
1103            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1104            final int count = filters.size();
1105            if (DEBUG_DOMAIN_VERIFICATION) {
1106                Slog.i(TAG, "Received verification response " + verificationId
1107                        + " for " + count + " filters, verified=" + verified);
1108            }
1109            for (int n=0; n<count; n++) {
1110                PackageParser.ActivityIntentInfo filter = filters.get(n);
1111                filter.setVerified(verified);
1112
1113                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1114                        + " verified with result:" + verified + " and hosts:"
1115                        + ivs.getHostsString());
1116            }
1117
1118            mIntentFilterVerificationStates.remove(verificationId);
1119
1120            final String packageName = ivs.getPackageName();
1121            IntentFilterVerificationInfo ivi = null;
1122
1123            synchronized (mPackages) {
1124                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1125            }
1126            if (ivi == null) {
1127                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1128                        + verificationId + " packageName:" + packageName);
1129                return;
1130            }
1131            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1132                    "Updating IntentFilterVerificationInfo for package " + packageName
1133                            +" verificationId:" + verificationId);
1134
1135            synchronized (mPackages) {
1136                if (verified) {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1138                } else {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1140                }
1141                scheduleWriteSettingsLocked();
1142
1143                final int userId = ivs.getUserId();
1144                if (userId != UserHandle.USER_ALL) {
1145                    final int userStatus =
1146                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1147
1148                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1149                    boolean needUpdate = false;
1150
1151                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1152                    // already been set by the User thru the Disambiguation dialog
1153                    switch (userStatus) {
1154                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1155                            if (verified) {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1157                            } else {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1159                            }
1160                            needUpdate = true;
1161                            break;
1162
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                                needUpdate = true;
1167                            }
1168                            break;
1169
1170                        default:
1171                            // Nothing to do
1172                    }
1173
1174                    if (needUpdate) {
1175                        mSettings.updateIntentFilterVerificationStatusLPw(
1176                                packageName, updatedStatus, userId);
1177                        scheduleWritePackageRestrictionsLocked(userId);
1178                    }
1179                }
1180            }
1181        }
1182
1183        @Override
1184        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1185                    ActivityIntentInfo filter, String packageName) {
1186            if (!hasValidDomains(filter)) {
1187                return false;
1188            }
1189            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1190            if (ivs == null) {
1191                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1192                        packageName);
1193            }
1194            if (DEBUG_DOMAIN_VERIFICATION) {
1195                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1196            }
1197            ivs.addFilter(filter);
1198            return true;
1199        }
1200
1201        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1202                int userId, int verificationId, String packageName) {
1203            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1204                    verifierUid, userId, packageName);
1205            ivs.setPendingState();
1206            synchronized (mPackages) {
1207                mIntentFilterVerificationStates.append(verificationId, ivs);
1208                mCurrentIntentFilterVerifications.add(verificationId);
1209            }
1210            return ivs;
1211        }
1212    }
1213
1214    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1215        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1216                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1217                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1218    }
1219
1220    // Set of pending broadcasts for aggregating enable/disable of components.
1221    static class PendingPackageBroadcasts {
1222        // for each user id, a map of <package name -> components within that package>
1223        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1224
1225        public PendingPackageBroadcasts() {
1226            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1227        }
1228
1229        public ArrayList<String> get(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            return packages.get(packageName);
1232        }
1233
1234        public void put(int userId, String packageName, ArrayList<String> components) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            packages.put(packageName, components);
1237        }
1238
1239        public void remove(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1241            if (packages != null) {
1242                packages.remove(packageName);
1243            }
1244        }
1245
1246        public void remove(int userId) {
1247            mUidMap.remove(userId);
1248        }
1249
1250        public int userIdCount() {
1251            return mUidMap.size();
1252        }
1253
1254        public int userIdAt(int n) {
1255            return mUidMap.keyAt(n);
1256        }
1257
1258        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1259            return mUidMap.get(userId);
1260        }
1261
1262        public int size() {
1263            // total number of pending broadcast entries across all userIds
1264            int num = 0;
1265            for (int i = 0; i< mUidMap.size(); i++) {
1266                num += mUidMap.valueAt(i).size();
1267            }
1268            return num;
1269        }
1270
1271        public void clear() {
1272            mUidMap.clear();
1273        }
1274
1275        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1276            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1277            if (map == null) {
1278                map = new ArrayMap<String, ArrayList<String>>();
1279                mUidMap.put(userId, map);
1280            }
1281            return map;
1282        }
1283    }
1284    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1285
1286    // Service Connection to remote media container service to copy
1287    // package uri's from external media onto secure containers
1288    // or internal storage.
1289    private IMediaContainerService mContainerService = null;
1290
1291    static final int SEND_PENDING_BROADCAST = 1;
1292    static final int MCS_BOUND = 3;
1293    static final int END_COPY = 4;
1294    static final int INIT_COPY = 5;
1295    static final int MCS_UNBIND = 6;
1296    static final int START_CLEANING_PACKAGE = 7;
1297    static final int FIND_INSTALL_LOC = 8;
1298    static final int POST_INSTALL = 9;
1299    static final int MCS_RECONNECT = 10;
1300    static final int MCS_GIVE_UP = 11;
1301    static final int UPDATED_MEDIA_STATUS = 12;
1302    static final int WRITE_SETTINGS = 13;
1303    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1304    static final int PACKAGE_VERIFIED = 15;
1305    static final int CHECK_PENDING_VERIFICATION = 16;
1306    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1307    static final int INTENT_FILTER_VERIFIED = 18;
1308    static final int WRITE_PACKAGE_LIST = 19;
1309    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1310
1311    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1312
1313    // Delay time in millisecs
1314    static final int BROADCAST_DELAY = 10 * 1000;
1315
1316    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1317            2 * 60 * 60 * 1000L; /* two hours */
1318
1319    static UserManagerService sUserManager;
1320
1321    // Stores a list of users whose package restrictions file needs to be updated
1322    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1323
1324    final private DefaultContainerConnection mDefContainerConn =
1325            new DefaultContainerConnection();
1326    class DefaultContainerConnection implements ServiceConnection {
1327        public void onServiceConnected(ComponentName name, IBinder service) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1329            final IMediaContainerService imcs = IMediaContainerService.Stub
1330                    .asInterface(Binder.allowBlocking(service));
1331            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1332        }
1333
1334        public void onServiceDisconnected(ComponentName name) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1336        }
1337    }
1338
1339    // Recordkeeping of restore-after-install operations that are currently in flight
1340    // between the Package Manager and the Backup Manager
1341    static class PostInstallData {
1342        public InstallArgs args;
1343        public PackageInstalledInfo res;
1344
1345        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346            args = _a;
1347            res = _r;
1348        }
1349    }
1350
1351    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1352    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1353
1354    // XML tags for backup/restore of various bits of state
1355    private static final String TAG_PREFERRED_BACKUP = "pa";
1356    private static final String TAG_DEFAULT_APPS = "da";
1357    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1358
1359    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1360    private static final String TAG_ALL_GRANTS = "rt-grants";
1361    private static final String TAG_GRANT = "grant";
1362    private static final String ATTR_PACKAGE_NAME = "pkg";
1363
1364    private static final String TAG_PERMISSION = "perm";
1365    private static final String ATTR_PERMISSION_NAME = "name";
1366    private static final String ATTR_IS_GRANTED = "g";
1367    private static final String ATTR_USER_SET = "set";
1368    private static final String ATTR_USER_FIXED = "fixed";
1369    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1370
1371    // System/policy permission grants are not backed up
1372    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_POLICY_FIXED
1374            | FLAG_PERMISSION_SYSTEM_FIXED
1375            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1376
1377    // And we back up these user-adjusted states
1378    private static final int USER_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_USER_SET
1380            | FLAG_PERMISSION_USER_FIXED
1381            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1382
1383    final @Nullable String mRequiredVerifierPackage;
1384    final @NonNull String mRequiredInstallerPackage;
1385    final @NonNull String mRequiredUninstallerPackage;
1386    final @Nullable String mSetupWizardPackage;
1387    final @Nullable String mStorageManagerPackage;
1388    final @NonNull String mServicesSystemSharedLibraryPackageName;
1389    final @NonNull String mSharedSystemSharedLibraryPackageName;
1390
1391    final boolean mPermissionReviewRequired;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final String[] grantedPermissions = args.installGrantPermissions;
1671
1672                        // Handle the parent package
1673                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1674                                grantedPermissions, didRestore, args.installerPackageName,
1675                                args.observer);
1676
1677                        // Handle the child packages
1678                        final int childCount = (parentRes.addedChildPackages != null)
1679                                ? parentRes.addedChildPackages.size() : 0;
1680                        for (int i = 0; i < childCount; i++) {
1681                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1682                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1683                                    grantedPermissions, false, args.installerPackageName,
1684                                    args.observer);
1685                        }
1686
1687                        // Log tracing if needed
1688                        if (args.traceMethod != null) {
1689                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1690                                    args.traceCookie);
1691                        }
1692                    } else {
1693                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1694                    }
1695
1696                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1697                } break;
1698                case UPDATED_MEDIA_STATUS: {
1699                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1700                    boolean reportStatus = msg.arg1 == 1;
1701                    boolean doGc = msg.arg2 == 1;
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1703                    if (doGc) {
1704                        // Force a gc to clear up stale containers.
1705                        Runtime.getRuntime().gc();
1706                    }
1707                    if (msg.obj != null) {
1708                        @SuppressWarnings("unchecked")
1709                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1710                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1711                        // Unload containers
1712                        unloadAllContainers(args);
1713                    }
1714                    if (reportStatus) {
1715                        try {
1716                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1717                                    "Invoking StorageManagerService call back");
1718                            PackageHelper.getStorageManager().finishMediaUpdate();
1719                        } catch (RemoteException e) {
1720                            Log.e(TAG, "StorageManagerService not running?");
1721                        }
1722                    }
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1895            boolean killApp, String[] grantedPermissions,
1896            boolean launchedForRestore, String installerPackage,
1897            IPackageInstallObserver2 installObserver) {
1898        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1899            // Send the removed broadcasts
1900            if (res.removedInfo != null) {
1901                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1902            }
1903
1904            // Now that we successfully installed the package, grant runtime
1905            // permissions if requested before broadcasting the install. Also
1906            // for legacy apps in permission review mode we clear the permission
1907            // review flag which is used to emulate runtime permissions for
1908            // legacy apps.
1909            if (grantPermissions) {
1910                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1911            }
1912
1913            final boolean update = res.removedInfo != null
1914                    && res.removedInfo.removedPackage != null;
1915            final String origInstallerPackageName = res.removedInfo != null
1916                    ? res.removedInfo.installerPackageName : null;
1917
1918            // If this is the first time we have child packages for a disabled privileged
1919            // app that had no children, we grant requested runtime permissions to the new
1920            // children if the parent on the system image had them already granted.
1921            if (res.pkg.parentPackage != null) {
1922                synchronized (mPackages) {
1923                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1924                }
1925            }
1926
1927            synchronized (mPackages) {
1928                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1929            }
1930
1931            final String packageName = res.pkg.applicationInfo.packageName;
1932
1933            // Determine the set of users who are adding this package for
1934            // the first time vs. those who are seeing an update.
1935            int[] firstUsers = EMPTY_INT_ARRAY;
1936            int[] updateUsers = EMPTY_INT_ARRAY;
1937            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1938            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1939            for (int newUser : res.newUsers) {
1940                if (ps.getInstantApp(newUser)) {
1941                    continue;
1942                }
1943                if (allNewUsers) {
1944                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1945                    continue;
1946                }
1947                boolean isNew = true;
1948                for (int origUser : res.origUsers) {
1949                    if (origUser == newUser) {
1950                        isNew = false;
1951                        break;
1952                    }
1953                }
1954                if (isNew) {
1955                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1956                } else {
1957                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1958                }
1959            }
1960
1961            // Send installed broadcasts if the package is not a static shared lib.
1962            if (res.pkg.staticSharedLibName == null) {
1963                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1964
1965                // Send added for users that see the package for the first time
1966                // sendPackageAddedForNewUsers also deals with system apps
1967                int appId = UserHandle.getAppId(res.uid);
1968                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1969                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1970
1971                // Send added for users that don't see the package for the first time
1972                Bundle extras = new Bundle(1);
1973                extras.putInt(Intent.EXTRA_UID, res.uid);
1974                if (update) {
1975                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1976                }
1977                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                        extras, 0 /*flags*/,
1979                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1980                if (origInstallerPackageName != null) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1982                            extras, 0 /*flags*/,
1983                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1984                }
1985
1986                // Send replaced for users that don't see the package for the first time
1987                if (update) {
1988                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1989                            packageName, extras, 0 /*flags*/,
1990                            null /*targetPackage*/, null /*finishedReceiver*/,
1991                            updateUsers);
1992                    if (origInstallerPackageName != null) {
1993                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1994                                extras, 0 /*flags*/,
1995                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1996                    }
1997                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1998                            null /*package*/, null /*extras*/, 0 /*flags*/,
1999                            packageName /*targetPackage*/,
2000                            null /*finishedReceiver*/, updateUsers);
2001                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2002                    // First-install and we did a restore, so we're responsible for the
2003                    // first-launch broadcast.
2004                    if (DEBUG_BACKUP) {
2005                        Slog.i(TAG, "Post-restore of " + packageName
2006                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2007                    }
2008                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2009                }
2010
2011                // Send broadcast package appeared if forward locked/external for all users
2012                // treat asec-hosted packages like removable media on upgrade
2013                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2014                    if (DEBUG_INSTALL) {
2015                        Slog.i(TAG, "upgrading pkg " + res.pkg
2016                                + " is ASEC-hosted -> AVAILABLE");
2017                    }
2018                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2019                    ArrayList<String> pkgList = new ArrayList<>(1);
2020                    pkgList.add(packageName);
2021                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2022                }
2023            }
2024
2025            // Work that needs to happen on first install within each user
2026            if (firstUsers != null && firstUsers.length > 0) {
2027                synchronized (mPackages) {
2028                    for (int userId : firstUsers) {
2029                        // If this app is a browser and it's newly-installed for some
2030                        // users, clear any default-browser state in those users. The
2031                        // app's nature doesn't depend on the user, so we can just check
2032                        // its browser nature in any user and generalize.
2033                        if (packageIsBrowser(packageName, userId)) {
2034                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2035                        }
2036
2037                        // We may also need to apply pending (restored) runtime
2038                        // permission grants within these users.
2039                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2040                    }
2041                }
2042            }
2043
2044            // Log current value of "unknown sources" setting
2045            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2046                    getUnknownSourcesSettings());
2047
2048            // Remove the replaced package's older resources safely now
2049            // We delete after a gc for applications  on sdcard.
2050            if (res.removedInfo != null && res.removedInfo.args != null) {
2051                Runtime.getRuntime().gc();
2052                synchronized (mInstallLock) {
2053                    res.removedInfo.args.doPostDeleteLI(true);
2054                }
2055            } else {
2056                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2057                // and not block here.
2058                VMRuntime.getRuntime().requestConcurrentGC();
2059            }
2060
2061            // Notify DexManager that the package was installed for new users.
2062            // The updated users should already be indexed and the package code paths
2063            // should not change.
2064            // Don't notify the manager for ephemeral apps as they are not expected to
2065            // survive long enough to benefit of background optimizations.
2066            for (int userId : firstUsers) {
2067                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2068                // There's a race currently where some install events may interleave with an uninstall.
2069                // This can lead to package info being null (b/36642664).
2070                if (info != null) {
2071                    mDexManager.notifyPackageInstalled(info, userId);
2072                }
2073            }
2074        }
2075
2076        // If someone is watching installs - notify them
2077        if (installObserver != null) {
2078            try {
2079                Bundle extras = extrasForInstallResult(res);
2080                installObserver.onPackageInstalled(res.name, res.returnCode,
2081                        res.returnMsg, extras);
2082            } catch (RemoteException e) {
2083                Slog.i(TAG, "Observer no longer exists.");
2084            }
2085        }
2086    }
2087
2088    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2089            PackageParser.Package pkg) {
2090        if (pkg.parentPackage == null) {
2091            return;
2092        }
2093        if (pkg.requestedPermissions == null) {
2094            return;
2095        }
2096        final PackageSetting disabledSysParentPs = mSettings
2097                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2098        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2099                || !disabledSysParentPs.isPrivileged()
2100                || (disabledSysParentPs.childPackageNames != null
2101                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2102            return;
2103        }
2104        final int[] allUserIds = sUserManager.getUserIds();
2105        final int permCount = pkg.requestedPermissions.size();
2106        for (int i = 0; i < permCount; i++) {
2107            String permission = pkg.requestedPermissions.get(i);
2108            BasePermission bp = mSettings.mPermissions.get(permission);
2109            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2110                continue;
2111            }
2112            for (int userId : allUserIds) {
2113                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2114                        permission, userId)) {
2115                    grantRuntimePermission(pkg.packageName, permission, userId);
2116                }
2117            }
2118        }
2119    }
2120
2121    private StorageEventListener mStorageListener = new StorageEventListener() {
2122        @Override
2123        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2124            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    final String volumeUuid = vol.getFsUuid();
2127
2128                    // Clean up any users or apps that were removed or recreated
2129                    // while this volume was missing
2130                    sUserManager.reconcileUsers(volumeUuid);
2131                    reconcileApps(volumeUuid);
2132
2133                    // Clean up any install sessions that expired or were
2134                    // cancelled while this volume was missing
2135                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2136
2137                    loadPrivatePackages(vol);
2138
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    unloadPrivatePackages(vol);
2141                }
2142            }
2143
2144            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2145                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2146                    updateExternalMediaStatus(true, false);
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    updateExternalMediaStatus(false, false);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2182            String[] grantedPermissions) {
2183        for (int userId : userIds) {
2184            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2185        }
2186    }
2187
2188    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2189            String[] grantedPermissions) {
2190        PackageSetting ps = (PackageSetting) pkg.mExtras;
2191        if (ps == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = ps.getPermissionsState();
2196
2197        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2198                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2199
2200        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2201                >= Build.VERSION_CODES.M;
2202
2203        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2204
2205        for (String permission : pkg.requestedPermissions) {
2206            final BasePermission bp;
2207            synchronized (mPackages) {
2208                bp = mSettings.mPermissions.get(permission);
2209            }
2210            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2211                    && (!instantApp || bp.isInstant())
2212                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2213                    && (grantedPermissions == null
2214                           || ArrayUtils.contains(grantedPermissions, permission))) {
2215                final int flags = permissionsState.getPermissionFlags(permission, userId);
2216                if (supportsRuntimePermissions) {
2217                    // Installer cannot change immutable permissions.
2218                    if ((flags & immutableFlags) == 0) {
2219                        grantRuntimePermission(pkg.packageName, permission, userId);
2220                    }
2221                } else if (mPermissionReviewRequired) {
2222                    // In permission review mode we clear the review flag when we
2223                    // are asked to install the app with all permissions granted.
2224                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2225                        updatePermissionFlags(permission, pkg.packageName,
2226                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227                    }
2228                }
2229            }
2230        }
2231    }
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        return m;
2295    }
2296
2297    private void enableSystemUserPackages() {
2298        if (!UserManager.isSplitSystemUser()) {
2299            return;
2300        }
2301        // For system user, enable apps based on the following conditions:
2302        // - app is whitelisted or belong to one of these groups:
2303        //   -- system app which has no launcher icons
2304        //   -- system app which has INTERACT_ACROSS_USERS permission
2305        //   -- system IME app
2306        // - app is not in the blacklist
2307        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2308        Set<String> enableApps = new ArraySet<>();
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2310                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2311                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2312        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2313        enableApps.addAll(wlApps);
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2315                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2316        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2317        enableApps.removeAll(blApps);
2318        Log.i(TAG, "Applications installed for system user: " + enableApps);
2319        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2320                UserHandle.SYSTEM);
2321        final int allAppsSize = allAps.size();
2322        synchronized (mPackages) {
2323            for (int i = 0; i < allAppsSize; i++) {
2324                String pName = allAps.get(i);
2325                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2326                // Should not happen, but we shouldn't be failing if it does
2327                if (pkgSetting == null) {
2328                    continue;
2329                }
2330                boolean install = enableApps.contains(pName);
2331                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2332                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2333                            + " for system user");
2334                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2335                }
2336            }
2337            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2338        }
2339    }
2340
2341    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2342        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2343                Context.DISPLAY_SERVICE);
2344        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2345    }
2346
2347    /**
2348     * Requests that files preopted on a secondary system partition be copied to the data partition
2349     * if possible.  Note that the actual copying of the files is accomplished by init for security
2350     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2351     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2352     */
2353    private static void requestCopyPreoptedFiles() {
2354        final int WAIT_TIME_MS = 100;
2355        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2356        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2357            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2358            // We will wait for up to 100 seconds.
2359            final long timeStart = SystemClock.uptimeMillis();
2360            final long timeEnd = timeStart + 100 * 1000;
2361            long timeNow = timeStart;
2362            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2363                try {
2364                    Thread.sleep(WAIT_TIME_MS);
2365                } catch (InterruptedException e) {
2366                    // Do nothing
2367                }
2368                timeNow = SystemClock.uptimeMillis();
2369                if (timeNow > timeEnd) {
2370                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2371                    Slog.wtf(TAG, "cppreopt did not finish!");
2372                    break;
2373                }
2374            }
2375
2376            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2377        }
2378    }
2379
2380    public PackageManagerService(Context context, Installer installer,
2381            boolean factoryTest, boolean onlyCore) {
2382        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2383        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2384        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2385                SystemClock.uptimeMillis());
2386
2387        if (mSdkVersion <= 0) {
2388            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2389        }
2390
2391        mContext = context;
2392
2393        mPermissionReviewRequired = context.getResources().getBoolean(
2394                R.bool.config_permissionReviewRequired);
2395
2396        mFactoryTest = factoryTest;
2397        mOnlyCore = onlyCore;
2398        mMetrics = new DisplayMetrics();
2399        mSettings = new Settings(mPackages);
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412
2413        String separateProcesses = SystemProperties.get("debug.separate_processes");
2414        if (separateProcesses != null && separateProcesses.length() > 0) {
2415            if ("*".equals(separateProcesses)) {
2416                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2417                mSeparateProcesses = null;
2418                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2419            } else {
2420                mDefParseFlags = 0;
2421                mSeparateProcesses = separateProcesses.split(",");
2422                Slog.w(TAG, "Running with debug.separate_processes: "
2423                        + separateProcesses);
2424            }
2425        } else {
2426            mDefParseFlags = 0;
2427            mSeparateProcesses = null;
2428        }
2429
2430        mInstaller = installer;
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2434        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2435
2436        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2437                FgThread.get().getLooper());
2438
2439        getDefaultDisplayMetrics(context, mMetrics);
2440
2441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2442        SystemConfig systemConfig = SystemConfig.getInstance();
2443        mGlobalGids = systemConfig.getGlobalGids();
2444        mSystemPermissions = systemConfig.getSystemPermissions();
2445        mAvailableFeatures = systemConfig.getAvailableFeatures();
2446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2447
2448        mProtectedPackages = new ProtectedPackages(mContext);
2449
2450        synchronized (mInstallLock) {
2451        // writer
2452        synchronized (mPackages) {
2453            mHandlerThread = new ServiceThread(TAG,
2454                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2455            mHandlerThread.start();
2456            mHandler = new PackageHandler(mHandlerThread.getLooper());
2457            mProcessLoggingHandler = new ProcessLoggingHandler();
2458            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2459
2460            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            File dataDir = Environment.getDataDirectory();
2464            mAppInstallDir = new File(dataDir, "app");
2465            mAppLib32InstallDir = new File(dataDir, "app-lib");
2466            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2467            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2468            sUserManager = new UserManagerService(context, this,
2469                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2470
2471            // Propagate permission configuration in to package manager.
2472            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2473                    = systemConfig.getPermissions();
2474            for (int i=0; i<permConfig.size(); i++) {
2475                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2476                BasePermission bp = mSettings.mPermissions.get(perm.name);
2477                if (bp == null) {
2478                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2479                    mSettings.mPermissions.put(perm.name, bp);
2480                }
2481                if (perm.gids != null) {
2482                    bp.setGids(perm.gids, perm.perUser);
2483                }
2484            }
2485
2486            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2487            final int builtInLibCount = libConfig.size();
2488            for (int i = 0; i < builtInLibCount; i++) {
2489                String name = libConfig.keyAt(i);
2490                String path = libConfig.valueAt(i);
2491                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2492                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2493            }
2494
2495            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2496
2497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2498            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2500
2501            // Clean up orphaned packages for which the code path doesn't exist
2502            // and they are an update to a system app - caused by bug/32321269
2503            final int packageSettingCount = mSettings.mPackages.size();
2504            for (int i = packageSettingCount - 1; i >= 0; i--) {
2505                PackageSetting ps = mSettings.mPackages.valueAt(i);
2506                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2507                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2508                    mSettings.mPackages.removeAt(i);
2509                    mSettings.enableSystemPackageLPw(ps.name);
2510                }
2511            }
2512
2513            if (mFirstBoot) {
2514                requestCopyPreoptedFiles();
2515            }
2516
2517            String customResolverActivity = Resources.getSystem().getString(
2518                    R.string.config_customResolverActivity);
2519            if (TextUtils.isEmpty(customResolverActivity)) {
2520                customResolverActivity = null;
2521            } else {
2522                mCustomResolverComponentName = ComponentName.unflattenFromString(
2523                        customResolverActivity);
2524            }
2525
2526            long startTime = SystemClock.uptimeMillis();
2527
2528            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2529                    startTime);
2530
2531            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2532            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2533
2534            if (bootClassPath == null) {
2535                Slog.w(TAG, "No BOOTCLASSPATH found!");
2536            }
2537
2538            if (systemServerClassPath == null) {
2539                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2540            }
2541
2542            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2543
2544            final VersionInfo ver = mSettings.getInternalVersion();
2545            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2546            if (mIsUpgrade) {
2547                logCriticalInfo(Log.INFO,
2548                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2549            }
2550
2551            // when upgrading from pre-M, promote system app permissions from install to runtime
2552            mPromoteSystemApps =
2553                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2554
2555            // When upgrading from pre-N, we need to handle package extraction like first boot,
2556            // as there is no profiling data available.
2557            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2558
2559            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2560
2561            // save off the names of pre-existing system packages prior to scanning; we don't
2562            // want to automatically grant runtime permissions for new system apps
2563            if (mPromoteSystemApps) {
2564                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2565                while (pkgSettingIter.hasNext()) {
2566                    PackageSetting ps = pkgSettingIter.next();
2567                    if (isSystemApp(ps)) {
2568                        mExistingSystemPackages.add(ps.name);
2569                    }
2570                }
2571            }
2572
2573            mCacheDir = preparePackageParserCache(mIsUpgrade);
2574
2575            // Set flag to monitor and not change apk file paths when
2576            // scanning install directories.
2577            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2578
2579            if (mIsUpgrade || mFirstBoot) {
2580                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2581            }
2582
2583            // Collect vendor overlay packages. (Do this before scanning any apps.)
2584            // For security and version matching reason, only consider
2585            // overlay packages if they reside in the right directory.
2586            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED,
2598                    scanFlags | SCAN_NO_DEX, 0);
2599
2600            // Collected privileged system packages.
2601            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2602            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2606
2607            // Collect ordinary system packages.
2608            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2609            scanDirTracedLI(systemAppDir, mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2612
2613            // Collect all vendor packages.
2614            File vendorAppDir = new File("/vendor/app");
2615            try {
2616                vendorAppDir = vendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(vendorAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Collect all OEM packages.
2625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2626            scanDirTracedLI(oemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Prune any system packages that no longer exist.
2631            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2632            if (!mOnlyCore) {
2633                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2678                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2679                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2680                        }
2681                    }
2682                }
2683            }
2684
2685            //look for any incomplete package installations
2686            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2687            for (int i = 0; i < deletePkgsList.size(); i++) {
2688                // Actual deletion of code and data will be handled by later
2689                // reconciliation step
2690                final String packageName = deletePkgsList.get(i).name;
2691                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2692                synchronized (mPackages) {
2693                    mSettings.removePackageLPw(packageName);
2694                }
2695            }
2696
2697            //delete tmp files
2698            deleteTempPackageFiles();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702
2703            if (!mOnlyCore) {
2704                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2705                        SystemClock.uptimeMillis());
2706                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2709                        | PackageParser.PARSE_FORWARD_LOCK,
2710                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2711
2712                /**
2713                 * Remove disable package settings for any updated system
2714                 * apps that were removed via an OTA. If they're not a
2715                 * previously-updated app, remove them completely.
2716                 * Otherwise, just revoke their system-level permissions.
2717                 */
2718                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2719                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2720                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2721
2722                    String msg;
2723                    if (deletedPkg == null) {
2724                        msg = "Updated system package " + deletedAppName
2725                                + " no longer exists; it's data will be wiped";
2726                        // Actual deletion of code and data will be handled by later
2727                        // reconciliation step
2728                    } else {
2729                        msg = "Updated system app + " + deletedAppName
2730                                + " no longer present; removing system privileges for "
2731                                + deletedAppName;
2732
2733                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2734
2735                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2736                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2737                    }
2738                    logCriticalInfo(Log.WARN, msg);
2739                }
2740
2741                /**
2742                 * Make sure all system apps that we expected to appear on
2743                 * the userdata partition actually showed up. If they never
2744                 * appeared, crawl back and revive the system version.
2745                 */
2746                for (int i = 0; i < mExpectingBetter.size(); i++) {
2747                    final String packageName = mExpectingBetter.keyAt(i);
2748                    if (!mPackages.containsKey(packageName)) {
2749                        final File scanFile = mExpectingBetter.valueAt(i);
2750
2751                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2752                                + " but never showed up; reverting to system");
2753
2754                        int reparseFlags = mDefParseFlags;
2755                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2758                                    | PackageParser.PARSE_IS_PRIVILEGED;
2759                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2765                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else {
2769                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2770                            continue;
2771                        }
2772
2773                        mSettings.enableSystemPackageLPw(packageName);
2774
2775                        try {
2776                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2777                        } catch (PackageManagerException e) {
2778                            Slog.e(TAG, "Failed to parse original system package: "
2779                                    + e.getMessage());
2780                        }
2781                    }
2782                }
2783            }
2784            mExpectingBetter.clear();
2785
2786            // Resolve the storage manager.
2787            mStorageManagerPackage = getStorageManagerPackageName();
2788
2789            // Resolve protected action filters. Only the setup wizard is allowed to
2790            // have a high priority filter for these actions.
2791            mSetupWizardPackage = getSetupWizardPackageName();
2792            if (mProtectedFilters.size() > 0) {
2793                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2794                    Slog.i(TAG, "No setup wizard;"
2795                        + " All protected intents capped to priority 0");
2796                }
2797                for (ActivityIntentInfo filter : mProtectedFilters) {
2798                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2799                        if (DEBUG_FILTERS) {
2800                            Slog.i(TAG, "Found setup wizard;"
2801                                + " allow priority " + filter.getPriority() + ";"
2802                                + " package: " + filter.activity.info.packageName
2803                                + " activity: " + filter.activity.className
2804                                + " priority: " + filter.getPriority());
2805                        }
2806                        // skip setup wizard; allow it to keep the high priority filter
2807                        continue;
2808                    }
2809                    if (DEBUG_FILTERS) {
2810                        Slog.i(TAG, "Protected action; cap priority to 0;"
2811                                + " package: " + filter.activity.info.packageName
2812                                + " activity: " + filter.activity.className
2813                                + " origPrio: " + filter.getPriority());
2814                    }
2815                    filter.setPriority(0);
2816                }
2817            }
2818            mDeferProtectedFilters = false;
2819            mProtectedFilters.clear();
2820
2821            // Now that we know all of the shared libraries, update all clients to have
2822            // the correct library paths.
2823            updateAllSharedLibrariesLPw(null);
2824
2825            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2826                // NOTE: We ignore potential failures here during a system scan (like
2827                // the rest of the commands above) because there's precious little we
2828                // can do about it. A settings error is reported, though.
2829                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2830            }
2831
2832            // Now that we know all the packages we are keeping,
2833            // read and update their last usage times.
2834            mPackageUsage.read(mPackages);
2835            mCompilerStats.read();
2836
2837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2838                    SystemClock.uptimeMillis());
2839            Slog.i(TAG, "Time to scan packages: "
2840                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2841                    + " seconds");
2842
2843            // If the platform SDK has changed since the last time we booted,
2844            // we need to re-grant app permission to catch any new ones that
2845            // appear.  This is really a hack, and means that apps can in some
2846            // cases get permissions that the user didn't initially explicitly
2847            // allow...  it would be nice to have some better way to handle
2848            // this situation.
2849            int updateFlags = UPDATE_PERMISSIONS_ALL;
2850            if (ver.sdkVersion != mSdkVersion) {
2851                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2852                        + mSdkVersion + "; regranting permissions for internal storage");
2853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2854            }
2855            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2856            ver.sdkVersion = mSdkVersion;
2857
2858            // If this is the first boot or an update from pre-M, and it is a normal
2859            // boot, then we need to initialize the default preferred apps across
2860            // all defined users.
2861            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2862                for (UserInfo user : sUserManager.getUsers(true)) {
2863                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2864                    applyFactoryDefaultBrowserLPw(user.id);
2865                    primeDomainVerificationsLPw(user.id);
2866                }
2867            }
2868
2869            // Prepare storage for system user really early during boot,
2870            // since core system apps like SettingsProvider and SystemUI
2871            // can't wait for user to start
2872            final int storageFlags;
2873            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2874                storageFlags = StorageManager.FLAG_STORAGE_DE;
2875            } else {
2876                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2877            }
2878            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2879                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2880                    true /* onlyCoreApps */);
2881            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2882                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2883                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2884                traceLog.traceBegin("AppDataFixup");
2885                try {
2886                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2887                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2888                } catch (InstallerException e) {
2889                    Slog.w(TAG, "Trouble fixing GIDs", e);
2890                }
2891                traceLog.traceEnd();
2892
2893                traceLog.traceBegin("AppDataPrepare");
2894                if (deferPackages == null || deferPackages.isEmpty()) {
2895                    return;
2896                }
2897                int count = 0;
2898                for (String pkgName : deferPackages) {
2899                    PackageParser.Package pkg = null;
2900                    synchronized (mPackages) {
2901                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2902                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2903                            pkg = ps.pkg;
2904                        }
2905                    }
2906                    if (pkg != null) {
2907                        synchronized (mInstallLock) {
2908                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2909                                    true /* maybeMigrateAppData */);
2910                        }
2911                        count++;
2912                    }
2913                }
2914                traceLog.traceEnd();
2915                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2916            }, "prepareAppData");
2917
2918            // If this is first boot after an OTA, and a normal boot, then
2919            // we need to clear code cache directories.
2920            // Note that we do *not* clear the application profiles. These remain valid
2921            // across OTAs and are used to drive profile verification (post OTA) and
2922            // profile compilation (without waiting to collect a fresh set of profiles).
2923            if (mIsUpgrade && !onlyCore) {
2924                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2925                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2926                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2927                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2928                        // No apps are running this early, so no need to freeze
2929                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2930                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2931                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2932                    }
2933                }
2934                ver.fingerprint = Build.FINGERPRINT;
2935            }
2936
2937            checkDefaultBrowser();
2938
2939            // clear only after permissions and other defaults have been updated
2940            mExistingSystemPackages.clear();
2941            mPromoteSystemApps = false;
2942
2943            // All the changes are done during package scanning.
2944            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2945
2946            // can downgrade to reader
2947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2948            mSettings.writeLPr();
2949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2950            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2951                    SystemClock.uptimeMillis());
2952
2953            if (!mOnlyCore) {
2954                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2955                mRequiredInstallerPackage = getRequiredInstallerLPr();
2956                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2957                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2958                if (mIntentFilterVerifierComponent != null) {
2959                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2960                            mIntentFilterVerifierComponent);
2961                } else {
2962                    mIntentFilterVerifier = null;
2963                }
2964                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970            } else {
2971                mRequiredVerifierPackage = null;
2972                mRequiredInstallerPackage = null;
2973                mRequiredUninstallerPackage = null;
2974                mIntentFilterVerifierComponent = null;
2975                mIntentFilterVerifier = null;
2976                mServicesSystemSharedLibraryPackageName = null;
2977                mSharedSystemSharedLibraryPackageName = null;
2978            }
2979
2980            mInstallerService = new PackageInstallerService(context, this);
2981            final Pair<ComponentName, String> instantAppResolverComponent =
2982                    getInstantAppResolverLPr();
2983            if (instantAppResolverComponent != null) {
2984                if (DEBUG_EPHEMERAL) {
2985                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2986                }
2987                mInstantAppResolverConnection = new EphemeralResolverConnection(
2988                        mContext, instantAppResolverComponent.first,
2989                        instantAppResolverComponent.second);
2990                mInstantAppResolverSettingsComponent =
2991                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2992            } else {
2993                mInstantAppResolverConnection = null;
2994                mInstantAppResolverSettingsComponent = null;
2995            }
2996            updateInstantAppInstallerLocked(null);
2997
2998            // Read and update the usage of dex files.
2999            // Do this at the end of PM init so that all the packages have their
3000            // data directory reconciled.
3001            // At this point we know the code paths of the packages, so we can validate
3002            // the disk file and build the internal cache.
3003            // The usage file is expected to be small so loading and verifying it
3004            // should take a fairly small time compare to the other activities (e.g. package
3005            // scanning).
3006            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3007            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3008            for (int userId : currentUserIds) {
3009                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3010            }
3011            mDexManager.load(userPackages);
3012        } // synchronized (mPackages)
3013        } // synchronized (mInstallLock)
3014
3015        // Now after opening every single application zip, make sure they
3016        // are all flushed.  Not really needed, but keeps things nice and
3017        // tidy.
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3019        Runtime.getRuntime().gc();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3023        FallbackCategoryProvider.loadFallbacks();
3024        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3025
3026        // The initial scanning above does many calls into installd while
3027        // holding the mPackages lock, but we're mostly interested in yelling
3028        // once we have a booted system.
3029        mInstaller.setWarnIfHeld(mPackages);
3030
3031        // Expose private service for system components to use.
3032        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034    }
3035
3036    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3037        // we're only interested in updating the installer appliction when 1) it's not
3038        // already set or 2) the modified package is the installer
3039        if (mInstantAppInstallerActivity != null
3040                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3041                        .equals(modifiedPackage)) {
3042            return;
3043        }
3044        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3045    }
3046
3047    private static File preparePackageParserCache(boolean isUpgrade) {
3048        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3049            return null;
3050        }
3051
3052        // Disable package parsing on eng builds to allow for faster incremental development.
3053        if (Build.IS_ENG) {
3054            return null;
3055        }
3056
3057        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3058            Slog.i(TAG, "Disabling package parser cache due to system property.");
3059            return null;
3060        }
3061
3062        // The base directory for the package parser cache lives under /data/system/.
3063        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3064                "package_cache");
3065        if (cacheBaseDir == null) {
3066            return null;
3067        }
3068
3069        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3070        // This also serves to "GC" unused entries when the package cache version changes (which
3071        // can only happen during upgrades).
3072        if (isUpgrade) {
3073            FileUtils.deleteContents(cacheBaseDir);
3074        }
3075
3076
3077        // Return the versioned package cache directory. This is something like
3078        // "/data/system/package_cache/1"
3079        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080
3081        // The following is a workaround to aid development on non-numbered userdebug
3082        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3083        // the system partition is newer.
3084        //
3085        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3086        // that starts with "eng." to signify that this is an engineering build and not
3087        // destined for release.
3088        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3089            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3090
3091            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3092            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3093            // in general and should not be used for production changes. In this specific case,
3094            // we know that they will work.
3095            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3096            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3097                FileUtils.deleteContents(cacheBaseDir);
3098                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3099            }
3100        }
3101
3102        return cacheDir;
3103    }
3104
3105    @Override
3106    public boolean isFirstBoot() {
3107        // allow instant applications
3108        return mFirstBoot;
3109    }
3110
3111    @Override
3112    public boolean isOnlyCoreApps() {
3113        // allow instant applications
3114        return mOnlyCore;
3115    }
3116
3117    @Override
3118    public boolean isUpgrade() {
3119        // allow instant applications
3120        return mIsUpgrade;
3121    }
3122
3123    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3125
3126        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            return matches.get(0).getComponentInfo().packageName;
3131        } else if (matches.size() == 0) {
3132            Log.e(TAG, "There should probably be a verifier, but, none were found");
3133            return null;
3134        }
3135        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3136    }
3137
3138    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3139        synchronized (mPackages) {
3140            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3141            if (libraryEntry == null) {
3142                throw new IllegalStateException("Missing required shared library:" + name);
3143            }
3144            return libraryEntry.apk;
3145        }
3146    }
3147
3148    private @NonNull String getRequiredInstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3152
3153        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (matches.size() == 1) {
3157            ResolveInfo resolveInfo = matches.get(0);
3158            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3159                throw new RuntimeException("The installer must be a privileged app");
3160            }
3161            return matches.get(0).getComponentInfo().packageName;
3162        } else {
3163            throw new RuntimeException("There must be exactly one installer; found " + matches);
3164        }
3165    }
3166
3167    private @NonNull String getRequiredUninstallerLPr() {
3168        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3169        intent.addCategory(Intent.CATEGORY_DEFAULT);
3170        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3171
3172        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3173                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3174                UserHandle.USER_SYSTEM);
3175        if (resolveInfo == null ||
3176                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3177            throw new RuntimeException("There must be exactly one uninstaller; found "
3178                    + resolveInfo);
3179        }
3180        return resolveInfo.getComponentInfo().packageName;
3181    }
3182
3183    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3184        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3185
3186        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3187                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3188                UserHandle.USER_SYSTEM);
3189        ResolveInfo best = null;
3190        final int N = matches.size();
3191        for (int i = 0; i < N; i++) {
3192            final ResolveInfo cur = matches.get(i);
3193            final String packageName = cur.getComponentInfo().packageName;
3194            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3195                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3196                continue;
3197            }
3198
3199            if (best == null || cur.priority > best.priority) {
3200                best = cur;
3201            }
3202        }
3203
3204        if (best != null) {
3205            return best.getComponentInfo().getComponentName();
3206        }
3207        Slog.w(TAG, "Intent filter verifier not found");
3208        return null;
3209    }
3210
3211    @Override
3212    public @Nullable ComponentName getInstantAppResolverComponent() {
3213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3214            return null;
3215        }
3216        synchronized (mPackages) {
3217            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3218            if (instantAppResolver == null) {
3219                return null;
3220            }
3221            return instantAppResolver.first;
3222        }
3223    }
3224
3225    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3226        final String[] packageArray =
3227                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3228        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3229            if (DEBUG_EPHEMERAL) {
3230                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231            }
3232            return null;
3233        }
3234
3235        final int callingUid = Binder.getCallingUid();
3236        final int resolveFlags =
3237                MATCH_DIRECT_BOOT_AWARE
3238                | MATCH_DIRECT_BOOT_UNAWARE
3239                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3240        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3241        final Intent resolverIntent = new Intent(actionName);
3242        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3243                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3244        // temporarily look for the old action
3245        if (resolvers.size() == 0) {
3246            if (DEBUG_EPHEMERAL) {
3247                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3248            }
3249            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3250            resolverIntent.setAction(actionName);
3251            resolvers = queryIntentServicesInternal(resolverIntent, null,
3252                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3253        }
3254        final int N = resolvers.size();
3255        if (N == 0) {
3256            if (DEBUG_EPHEMERAL) {
3257                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258            }
3259            return null;
3260        }
3261
3262        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3263        for (int i = 0; i < N; i++) {
3264            final ResolveInfo info = resolvers.get(i);
3265
3266            if (info.serviceInfo == null) {
3267                continue;
3268            }
3269
3270            final String packageName = info.serviceInfo.packageName;
3271            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3272                if (DEBUG_EPHEMERAL) {
3273                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3274                            + " pkg: " + packageName + ", info:" + info);
3275                }
3276                continue;
3277            }
3278
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.v(TAG, "Ephemeral resolver found;"
3281                        + " pkg: " + packageName + ", info:" + info);
3282            }
3283            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3284        }
3285        if (DEBUG_EPHEMERAL) {
3286            Slog.v(TAG, "Ephemeral resolver NOT found");
3287        }
3288        return null;
3289    }
3290
3291    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3292        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3293        intent.addCategory(Intent.CATEGORY_DEFAULT);
3294        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3295
3296        final int resolveFlags =
3297                MATCH_DIRECT_BOOT_AWARE
3298                | MATCH_DIRECT_BOOT_UNAWARE
3299                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3300        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3301                resolveFlags, UserHandle.USER_SYSTEM);
3302        // temporarily look for the old action
3303        if (matches.isEmpty()) {
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3306            }
3307            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3308            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3309                    resolveFlags, UserHandle.USER_SYSTEM);
3310        }
3311        Iterator<ResolveInfo> iter = matches.iterator();
3312        while (iter.hasNext()) {
3313            final ResolveInfo rInfo = iter.next();
3314            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3315            if (ps != null) {
3316                final PermissionsState permissionsState = ps.getPermissionsState();
3317                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318                    continue;
3319                }
3320            }
3321            iter.remove();
3322        }
3323        if (matches.size() == 0) {
3324            return null;
3325        } else if (matches.size() == 1) {
3326            return (ActivityInfo) matches.get(0).getComponentInfo();
3327        } else {
3328            throw new RuntimeException(
3329                    "There must be at most one ephemeral installer; found " + matches);
3330        }
3331    }
3332
3333    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3334            @NonNull ComponentName resolver) {
3335        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3336                .addCategory(Intent.CATEGORY_DEFAULT)
3337                .setPackage(resolver.getPackageName());
3338        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3339        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3340                UserHandle.USER_SYSTEM);
3341        // temporarily look for the old action
3342        if (matches.isEmpty()) {
3343            if (DEBUG_EPHEMERAL) {
3344                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3345            }
3346            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3347            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3348                    UserHandle.USER_SYSTEM);
3349        }
3350        if (matches.isEmpty()) {
3351            return null;
3352        }
3353        return matches.get(0).getComponentInfo().getComponentName();
3354    }
3355
3356    private void primeDomainVerificationsLPw(int userId) {
3357        if (DEBUG_DOMAIN_VERIFICATION) {
3358            Slog.d(TAG, "Priming domain verifications in user " + userId);
3359        }
3360
3361        SystemConfig systemConfig = SystemConfig.getInstance();
3362        ArraySet<String> packages = systemConfig.getLinkedApps();
3363
3364        for (String packageName : packages) {
3365            PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg != null) {
3367                if (!pkg.isSystemApp()) {
3368                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3369                    continue;
3370                }
3371
3372                ArraySet<String> domains = null;
3373                for (PackageParser.Activity a : pkg.activities) {
3374                    for (ActivityIntentInfo filter : a.intents) {
3375                        if (hasValidDomains(filter)) {
3376                            if (domains == null) {
3377                                domains = new ArraySet<String>();
3378                            }
3379                            domains.addAll(filter.getHostsList());
3380                        }
3381                    }
3382                }
3383
3384                if (domains != null && domains.size() > 0) {
3385                    if (DEBUG_DOMAIN_VERIFICATION) {
3386                        Slog.v(TAG, "      + " + packageName);
3387                    }
3388                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3389                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3390                    // and then 'always' in the per-user state actually used for intent resolution.
3391                    final IntentFilterVerificationInfo ivi;
3392                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3393                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3394                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3395                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3396                } else {
3397                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3398                            + "' does not handle web links");
3399                }
3400            } else {
3401                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3402            }
3403        }
3404
3405        scheduleWritePackageRestrictionsLocked(userId);
3406        scheduleWriteSettingsLocked();
3407    }
3408
3409    private void applyFactoryDefaultBrowserLPw(int userId) {
3410        // The default browser app's package name is stored in a string resource,
3411        // with a product-specific overlay used for vendor customization.
3412        String browserPkg = mContext.getResources().getString(
3413                com.android.internal.R.string.default_browser);
3414        if (!TextUtils.isEmpty(browserPkg)) {
3415            // non-empty string => required to be a known package
3416            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3417            if (ps == null) {
3418                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3419                browserPkg = null;
3420            } else {
3421                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3422            }
3423        }
3424
3425        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3426        // default.  If there's more than one, just leave everything alone.
3427        if (browserPkg == null) {
3428            calculateDefaultBrowserLPw(userId);
3429        }
3430    }
3431
3432    private void calculateDefaultBrowserLPw(int userId) {
3433        List<String> allBrowsers = resolveAllBrowserApps(userId);
3434        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3435        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3436    }
3437
3438    private List<String> resolveAllBrowserApps(int userId) {
3439        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3440        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3441                PackageManager.MATCH_ALL, userId);
3442
3443        final int count = list.size();
3444        List<String> result = new ArrayList<String>(count);
3445        for (int i=0; i<count; i++) {
3446            ResolveInfo info = list.get(i);
3447            if (info.activityInfo == null
3448                    || !info.handleAllWebDataURI
3449                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3450                    || result.contains(info.activityInfo.packageName)) {
3451                continue;
3452            }
3453            result.add(info.activityInfo.packageName);
3454        }
3455
3456        return result;
3457    }
3458
3459    private boolean packageIsBrowser(String packageName, int userId) {
3460        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3461                PackageManager.MATCH_ALL, userId);
3462        final int N = list.size();
3463        for (int i = 0; i < N; i++) {
3464            ResolveInfo info = list.get(i);
3465            if (packageName.equals(info.activityInfo.packageName)) {
3466                return true;
3467            }
3468        }
3469        return false;
3470    }
3471
3472    private void checkDefaultBrowser() {
3473        final int myUserId = UserHandle.myUserId();
3474        final String packageName = getDefaultBrowserPackageName(myUserId);
3475        if (packageName != null) {
3476            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3477            if (info == null) {
3478                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3479                synchronized (mPackages) {
3480                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3481                }
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3488            throws RemoteException {
3489        try {
3490            return super.onTransact(code, data, reply, flags);
3491        } catch (RuntimeException e) {
3492            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3493                Slog.wtf(TAG, "Package Manager Crash", e);
3494            }
3495            throw e;
3496        }
3497    }
3498
3499    static int[] appendInts(int[] cur, int[] add) {
3500        if (add == null) return cur;
3501        if (cur == null) return add;
3502        final int N = add.length;
3503        for (int i=0; i<N; i++) {
3504            cur = appendInt(cur, add[i]);
3505        }
3506        return cur;
3507    }
3508
3509    /**
3510     * Returns whether or not a full application can see an instant application.
3511     * <p>
3512     * Currently, there are three cases in which this can occur:
3513     * <ol>
3514     * <li>The calling application is a "special" process. The special
3515     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3516     *     and {@code 0}</li>
3517     * <li>The calling application has the permission
3518     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3519     * <li>The calling application is the default launcher on the
3520     *     system partition.</li>
3521     * </ol>
3522     */
3523    private boolean canViewInstantApps(int callingUid, int userId) {
3524        if (callingUid == Process.SYSTEM_UID
3525                || callingUid == Process.SHELL_UID
3526                || callingUid == Process.ROOT_UID) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            return true;
3532        }
3533        if (mContext.checkCallingOrSelfPermission(
3534                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3535            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3536            if (homeComponent != null
3537                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3538                return true;
3539            }
3540        }
3541        return false;
3542    }
3543
3544    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        if (ps == null) {
3547            return null;
3548        }
3549        PackageParser.Package p = ps.pkg;
3550        if (p == null) {
3551            return null;
3552        }
3553        final int callingUid = Binder.getCallingUid();
3554        // Filter out ephemeral app metadata:
3555        //   * The system/shell/root can see metadata for any app
3556        //   * An installed app can see metadata for 1) other installed apps
3557        //     and 2) ephemeral apps that have explicitly interacted with it
3558        //   * Ephemeral apps can only see their own data and exposed installed apps
3559        //   * Holding a signature permission allows seeing instant apps
3560        if (filterAppAccessLPr(ps, callingUid, userId)) {
3561            return null;
3562        }
3563
3564        final PermissionsState permissionsState = ps.getPermissionsState();
3565
3566        // Compute GIDs only if requested
3567        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3568                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3569        // Compute granted permissions only if package has requested permissions
3570        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3571                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3572        final PackageUserState state = ps.readUserState(userId);
3573
3574        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3575                && ps.isSystem()) {
3576            flags |= MATCH_ANY_USER;
3577        }
3578
3579        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3580                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3581
3582        if (packageInfo == null) {
3583            return null;
3584        }
3585
3586        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3587                resolveExternalPackageNameLPr(p);
3588
3589        return packageInfo;
3590    }
3591
3592    @Override
3593    public void checkPackageStartable(String packageName, int userId) {
3594        final int callingUid = Binder.getCallingUid();
3595        if (getInstantAppPackageName(callingUid) != null) {
3596            throw new SecurityException("Instant applications don't have access to this method");
3597        }
3598        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3599        synchronized (mPackages) {
3600            final PackageSetting ps = mSettings.mPackages.get(packageName);
3601            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3602                throw new SecurityException("Package " + packageName + " was not found!");
3603            }
3604
3605            if (!ps.getInstalled(userId)) {
3606                throw new SecurityException(
3607                        "Package " + packageName + " was not installed for user " + userId + "!");
3608            }
3609
3610            if (mSafeMode && !ps.isSystem()) {
3611                throw new SecurityException("Package " + packageName + " not a system app!");
3612            }
3613
3614            if (mFrozenPackages.contains(packageName)) {
3615                throw new SecurityException("Package " + packageName + " is currently frozen!");
3616            }
3617
3618            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3619                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3620                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3621            }
3622        }
3623    }
3624
3625    @Override
3626    public boolean isPackageAvailable(String packageName, int userId) {
3627        if (!sUserManager.exists(userId)) return false;
3628        final int callingUid = Binder.getCallingUid();
3629        enforceCrossUserPermission(callingUid, userId,
3630                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3631        synchronized (mPackages) {
3632            PackageParser.Package p = mPackages.get(packageName);
3633            if (p != null) {
3634                final PackageSetting ps = (PackageSetting) p.mExtras;
3635                if (filterAppAccessLPr(ps, callingUid, userId)) {
3636                    return false;
3637                }
3638                if (ps != null) {
3639                    final PackageUserState state = ps.readUserState(userId);
3640                    if (state != null) {
3641                        return PackageParser.isAvailable(state);
3642                    }
3643                }
3644            }
3645        }
3646        return false;
3647    }
3648
3649    @Override
3650    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3651        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3652                flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    @Override
3656    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3657            int flags, int userId) {
3658        return getPackageInfoInternal(versionedPackage.getPackageName(),
3659                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3660    }
3661
3662    /**
3663     * Important: The provided filterCallingUid is used exclusively to filter out packages
3664     * that can be seen based on user state. It's typically the original caller uid prior
3665     * to clearing. Because it can only be provided by trusted code, it's value can be
3666     * trusted and will be used as-is; unlike userId which will be validated by this method.
3667     */
3668    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3669            int flags, int filterCallingUid, int userId) {
3670        if (!sUserManager.exists(userId)) return null;
3671        flags = updateFlagsForPackage(flags, userId, packageName);
3672        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3673                false /* requireFullPermission */, false /* checkShell */, "get package info");
3674
3675        // reader
3676        synchronized (mPackages) {
3677            // Normalize package name to handle renamed packages and static libs
3678            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3679
3680            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3681            if (matchFactoryOnly) {
3682                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3683                if (ps != null) {
3684                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3685                        return null;
3686                    }
3687                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3688                        return null;
3689                    }
3690                    return generatePackageInfo(ps, flags, userId);
3691                }
3692            }
3693
3694            PackageParser.Package p = mPackages.get(packageName);
3695            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3696                return null;
3697            }
3698            if (DEBUG_PACKAGE_INFO)
3699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3700            if (p != null) {
3701                final PackageSetting ps = (PackageSetting) p.mExtras;
3702                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3703                    return null;
3704                }
3705                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3706                    return null;
3707                }
3708                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3709            }
3710            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3711                final PackageSetting ps = mSettings.mPackages.get(packageName);
3712                if (ps == null) return null;
3713                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3714                    return null;
3715                }
3716                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3717                    return null;
3718                }
3719                return generatePackageInfo(ps, flags, userId);
3720            }
3721        }
3722        return null;
3723    }
3724
3725    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3726        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3727            return true;
3728        }
3729        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3733            return true;
3734        }
3735        return false;
3736    }
3737
3738    private boolean isComponentVisibleToInstantApp(
3739            @Nullable ComponentName component, @ComponentType int type) {
3740        if (type == TYPE_ACTIVITY) {
3741            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_RECEIVER) {
3746            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3747            return activity != null
3748                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_SERVICE) {
3751            final PackageParser.Service service = mServices.mServices.get(component);
3752            return service != null
3753                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_PROVIDER) {
3756            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3757            return provider != null
3758                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3759                    : false;
3760        } else if (type == TYPE_UNKNOWN) {
3761            return isComponentVisibleToInstantApp(component);
3762        }
3763        return false;
3764    }
3765
3766    /**
3767     * Returns whether or not access to the application should be filtered.
3768     * <p>
3769     * Access may be limited based upon whether the calling or target applications
3770     * are instant applications.
3771     *
3772     * @see #canAccessInstantApps(int)
3773     */
3774    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3775            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3776        // if we're in an isolated process, get the real calling UID
3777        if (Process.isIsolated(callingUid)) {
3778            callingUid = mIsolatedOwners.get(callingUid);
3779        }
3780        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3781        final boolean callerIsInstantApp = instantAppPkgName != null;
3782        if (ps == null) {
3783            if (callerIsInstantApp) {
3784                // pretend the application exists, but, needs to be filtered
3785                return true;
3786            }
3787            return false;
3788        }
3789        // if the target and caller are the same application, don't filter
3790        if (isCallerSameApp(ps.name, callingUid)) {
3791            return false;
3792        }
3793        if (callerIsInstantApp) {
3794            // request for a specific component; if it hasn't been explicitly exposed, filter
3795            if (component != null) {
3796                return !isComponentVisibleToInstantApp(component, componentType);
3797            }
3798            // request for application; if no components have been explicitly exposed, filter
3799            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3800        }
3801        if (ps.getInstantApp(userId)) {
3802            // caller can see all components of all instant applications, don't filter
3803            if (canViewInstantApps(callingUid, userId)) {
3804                return false;
3805            }
3806            // request for a specific instant application component, filter
3807            if (component != null) {
3808                return true;
3809            }
3810            // request for an instant application; if the caller hasn't been granted access, filter
3811            return !mInstantAppRegistry.isInstantAccessGranted(
3812                    userId, UserHandle.getAppId(callingUid), ps.appId);
3813        }
3814        return false;
3815    }
3816
3817    /**
3818     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3819     */
3820    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3821        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3822    }
3823
3824    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3825            int flags) {
3826        // Callers can access only the libs they depend on, otherwise they need to explicitly
3827        // ask for the shared libraries given the caller is allowed to access all static libs.
3828        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3829            // System/shell/root get to see all static libs
3830            final int appId = UserHandle.getAppId(uid);
3831            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3832                    || appId == Process.ROOT_UID) {
3833                return false;
3834            }
3835        }
3836
3837        // No package means no static lib as it is always on internal storage
3838        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3839            return false;
3840        }
3841
3842        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3843                ps.pkg.staticSharedLibVersion);
3844        if (libEntry == null) {
3845            return false;
3846        }
3847
3848        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3849        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3850        if (uidPackageNames == null) {
3851            return true;
3852        }
3853
3854        for (String uidPackageName : uidPackageNames) {
3855            if (ps.name.equals(uidPackageName)) {
3856                return false;
3857            }
3858            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3859            if (uidPs != null) {
3860                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3861                        libEntry.info.getName());
3862                if (index < 0) {
3863                    continue;
3864                }
3865                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3866                    return false;
3867                }
3868            }
3869        }
3870        return true;
3871    }
3872
3873    @Override
3874    public String[] currentToCanonicalPackageNames(String[] names) {
3875        final int callingUid = Binder.getCallingUid();
3876        if (getInstantAppPackageName(callingUid) != null) {
3877            return names;
3878        }
3879        final String[] out = new String[names.length];
3880        // reader
3881        synchronized (mPackages) {
3882            final int callingUserId = UserHandle.getUserId(callingUid);
3883            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3884            for (int i=names.length-1; i>=0; i--) {
3885                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3886                boolean translateName = false;
3887                if (ps != null && ps.realName != null) {
3888                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3889                    translateName = !targetIsInstantApp
3890                            || canViewInstantApps
3891                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3892                                    UserHandle.getAppId(callingUid), ps.appId);
3893                }
3894                out[i] = translateName ? ps.realName : names[i];
3895            }
3896        }
3897        return out;
3898    }
3899
3900    @Override
3901    public String[] canonicalToCurrentPackageNames(String[] names) {
3902        final int callingUid = Binder.getCallingUid();
3903        if (getInstantAppPackageName(callingUid) != null) {
3904            return names;
3905        }
3906        final String[] out = new String[names.length];
3907        // reader
3908        synchronized (mPackages) {
3909            final int callingUserId = UserHandle.getUserId(callingUid);
3910            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3911            for (int i=names.length-1; i>=0; i--) {
3912                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3913                boolean translateName = false;
3914                if (cur != null) {
3915                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3916                    final boolean targetIsInstantApp =
3917                            ps != null && ps.getInstantApp(callingUserId);
3918                    translateName = !targetIsInstantApp
3919                            || canViewInstantApps
3920                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3921                                    UserHandle.getAppId(callingUid), ps.appId);
3922                }
3923                out[i] = translateName ? cur : names[i];
3924            }
3925        }
3926        return out;
3927    }
3928
3929    @Override
3930    public int getPackageUid(String packageName, int flags, int userId) {
3931        if (!sUserManager.exists(userId)) return -1;
3932        final int callingUid = Binder.getCallingUid();
3933        flags = updateFlagsForPackage(flags, userId, packageName);
3934        enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3936
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(packageName);
3940            if (p != null && p.isMatch(flags)) {
3941                PackageSetting ps = (PackageSetting) p.mExtras;
3942                if (filterAppAccessLPr(ps, callingUid, userId)) {
3943                    return -1;
3944                }
3945                return UserHandle.getUid(userId, p.applicationInfo.uid);
3946            }
3947            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3948                final PackageSetting ps = mSettings.mPackages.get(packageName);
3949                if (ps != null && ps.isMatch(flags)
3950                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3951                    return UserHandle.getUid(userId, ps.appId);
3952                }
3953            }
3954        }
3955
3956        return -1;
3957    }
3958
3959    @Override
3960    public int[] getPackageGids(String packageName, int flags, int userId) {
3961        if (!sUserManager.exists(userId)) return null;
3962        final int callingUid = Binder.getCallingUid();
3963        flags = updateFlagsForPackage(flags, userId, packageName);
3964        enforceCrossUserPermission(callingUid, userId,
3965                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3966
3967        // reader
3968        synchronized (mPackages) {
3969            final PackageParser.Package p = mPackages.get(packageName);
3970            if (p != null && p.isMatch(flags)) {
3971                PackageSetting ps = (PackageSetting) p.mExtras;
3972                if (filterAppAccessLPr(ps, callingUid, userId)) {
3973                    return null;
3974                }
3975                // TODO: Shouldn't this be checking for package installed state for userId and
3976                // return null?
3977                return ps.getPermissionsState().computeGids(userId);
3978            }
3979            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3980                final PackageSetting ps = mSettings.mPackages.get(packageName);
3981                if (ps != null && ps.isMatch(flags)
3982                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return ps.getPermissionsState().computeGids(userId);
3984                }
3985            }
3986        }
3987
3988        return null;
3989    }
3990
3991    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3992        if (bp.perm != null) {
3993            return PackageParser.generatePermissionInfo(bp.perm, flags);
3994        }
3995        PermissionInfo pi = new PermissionInfo();
3996        pi.name = bp.name;
3997        pi.packageName = bp.sourcePackage;
3998        pi.nonLocalizedLabel = bp.name;
3999        pi.protectionLevel = bp.protectionLevel;
4000        return pi;
4001    }
4002
4003    @Override
4004    public PermissionInfo getPermissionInfo(String name, int flags) {
4005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4006            return null;
4007        }
4008        // reader
4009        synchronized (mPackages) {
4010            final BasePermission p = mSettings.mPermissions.get(name);
4011            if (p != null) {
4012                return generatePermissionInfo(p, flags);
4013            }
4014            return null;
4015        }
4016    }
4017
4018    @Override
4019    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4020            int flags) {
4021        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4022            return null;
4023        }
4024        // reader
4025        synchronized (mPackages) {
4026            if (group != null && !mPermissionGroups.containsKey(group)) {
4027                // This is thrown as NameNotFoundException
4028                return null;
4029            }
4030
4031            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4032            for (BasePermission p : mSettings.mPermissions.values()) {
4033                if (group == null) {
4034                    if (p.perm == null || p.perm.info.group == null) {
4035                        out.add(generatePermissionInfo(p, flags));
4036                    }
4037                } else {
4038                    if (p.perm != null && group.equals(p.perm.info.group)) {
4039                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4040                    }
4041                }
4042            }
4043            return new ParceledListSlice<>(out);
4044        }
4045    }
4046
4047    @Override
4048    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4049        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4050            return null;
4051        }
4052        // reader
4053        synchronized (mPackages) {
4054            return PackageParser.generatePermissionGroupInfo(
4055                    mPermissionGroups.get(name), flags);
4056        }
4057    }
4058
4059    @Override
4060    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4061        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4062            return ParceledListSlice.emptyList();
4063        }
4064        // reader
4065        synchronized (mPackages) {
4066            final int N = mPermissionGroups.size();
4067            ArrayList<PermissionGroupInfo> out
4068                    = new ArrayList<PermissionGroupInfo>(N);
4069            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4070                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4071            }
4072            return new ParceledListSlice<>(out);
4073        }
4074    }
4075
4076    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4077            int filterCallingUid, int userId) {
4078        if (!sUserManager.exists(userId)) return null;
4079        PackageSetting ps = mSettings.mPackages.get(packageName);
4080        if (ps != null) {
4081            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4082                return null;
4083            }
4084            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4085                return null;
4086            }
4087            if (ps.pkg == null) {
4088                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4089                if (pInfo != null) {
4090                    return pInfo.applicationInfo;
4091                }
4092                return null;
4093            }
4094            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4095                    ps.readUserState(userId), userId);
4096            if (ai != null) {
4097                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4098            }
4099            return ai;
4100        }
4101        return null;
4102    }
4103
4104    @Override
4105    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4106        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4107    }
4108
4109    /**
4110     * Important: The provided filterCallingUid is used exclusively to filter out applications
4111     * that can be seen based on user state. It's typically the original caller uid prior
4112     * to clearing. Because it can only be provided by trusted code, it's value can be
4113     * trusted and will be used as-is; unlike userId which will be validated by this method.
4114     */
4115    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4116            int filterCallingUid, int userId) {
4117        if (!sUserManager.exists(userId)) return null;
4118        flags = updateFlagsForApplication(flags, userId, packageName);
4119        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4120                false /* requireFullPermission */, false /* checkShell */, "get application info");
4121
4122        // writer
4123        synchronized (mPackages) {
4124            // Normalize package name to handle renamed packages and static libs
4125            packageName = resolveInternalPackageNameLPr(packageName,
4126                    PackageManager.VERSION_CODE_HIGHEST);
4127
4128            PackageParser.Package p = mPackages.get(packageName);
4129            if (DEBUG_PACKAGE_INFO) Log.v(
4130                    TAG, "getApplicationInfo " + packageName
4131                    + ": " + p);
4132            if (p != null) {
4133                PackageSetting ps = mSettings.mPackages.get(packageName);
4134                if (ps == null) return null;
4135                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4136                    return null;
4137                }
4138                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4139                    return null;
4140                }
4141                // Note: isEnabledLP() does not apply here - always return info
4142                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4143                        p, flags, ps.readUserState(userId), userId);
4144                if (ai != null) {
4145                    ai.packageName = resolveExternalPackageNameLPr(p);
4146                }
4147                return ai;
4148            }
4149            if ("android".equals(packageName)||"system".equals(packageName)) {
4150                return mAndroidApplication;
4151            }
4152            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4153                // Already generates the external package name
4154                return generateApplicationInfoFromSettingsLPw(packageName,
4155                        flags, filterCallingUid, userId);
4156            }
4157        }
4158        return null;
4159    }
4160
4161    private String normalizePackageNameLPr(String packageName) {
4162        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4163        return normalizedPackageName != null ? normalizedPackageName : packageName;
4164    }
4165
4166    @Override
4167    public void deletePreloadsFileCache() {
4168        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4169            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4170        }
4171        File dir = Environment.getDataPreloadsFileCacheDirectory();
4172        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4173        FileUtils.deleteContents(dir);
4174    }
4175
4176    @Override
4177    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4178            final int storageFlags, final IPackageDataObserver observer) {
4179        mContext.enforceCallingOrSelfPermission(
4180                android.Manifest.permission.CLEAR_APP_CACHE, null);
4181        mHandler.post(() -> {
4182            boolean success = false;
4183            try {
4184                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4185                success = true;
4186            } catch (IOException e) {
4187                Slog.w(TAG, e);
4188            }
4189            if (observer != null) {
4190                try {
4191                    observer.onRemoveCompleted(null, success);
4192                } catch (RemoteException e) {
4193                    Slog.w(TAG, e);
4194                }
4195            }
4196        });
4197    }
4198
4199    @Override
4200    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4201            final int storageFlags, final IntentSender pi) {
4202        mContext.enforceCallingOrSelfPermission(
4203                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4204        mHandler.post(() -> {
4205            boolean success = false;
4206            try {
4207                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4208                success = true;
4209            } catch (IOException e) {
4210                Slog.w(TAG, e);
4211            }
4212            if (pi != null) {
4213                try {
4214                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4215                } catch (SendIntentException e) {
4216                    Slog.w(TAG, e);
4217                }
4218            }
4219        });
4220    }
4221
4222    /**
4223     * Blocking call to clear various types of cached data across the system
4224     * until the requested bytes are available.
4225     */
4226    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4227        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4228        final File file = storage.findPathForUuid(volumeUuid);
4229        if (file.getUsableSpace() >= bytes) return;
4230
4231        if (ENABLE_FREE_CACHE_V2) {
4232            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4233                    volumeUuid);
4234            final boolean aggressive = (storageFlags
4235                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4236            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4237
4238            // 1. Pre-flight to determine if we have any chance to succeed
4239            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4240            if (internalVolume && (aggressive || SystemProperties
4241                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4242                deletePreloadsFileCache();
4243                if (file.getUsableSpace() >= bytes) return;
4244            }
4245
4246            // 3. Consider parsed APK data (aggressive only)
4247            if (internalVolume && aggressive) {
4248                FileUtils.deleteContents(mCacheDir);
4249                if (file.getUsableSpace() >= bytes) return;
4250            }
4251
4252            // 4. Consider cached app data (above quotas)
4253            try {
4254                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4255                        Installer.FLAG_FREE_CACHE_V2);
4256            } catch (InstallerException ignored) {
4257            }
4258            if (file.getUsableSpace() >= bytes) return;
4259
4260            // 5. Consider shared libraries with refcount=0 and age>min cache period
4261            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4262                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4263                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4264                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4265                return;
4266            }
4267
4268            // 6. Consider dexopt output (aggressive only)
4269            // TODO: Implement
4270
4271            // 7. Consider installed instant apps unused longer than min cache period
4272            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4273                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4274                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4275                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4276                return;
4277            }
4278
4279            // 8. Consider cached app data (below quotas)
4280            try {
4281                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4282                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4283            } catch (InstallerException ignored) {
4284            }
4285            if (file.getUsableSpace() >= bytes) return;
4286
4287            // 9. Consider DropBox entries
4288            // TODO: Implement
4289
4290            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4291            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4292                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4293                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4294                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4295                return;
4296            }
4297        } else {
4298            try {
4299                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4300            } catch (InstallerException ignored) {
4301            }
4302            if (file.getUsableSpace() >= bytes) return;
4303        }
4304
4305        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4306    }
4307
4308    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4309            throws IOException {
4310        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4311        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4312
4313        List<VersionedPackage> packagesToDelete = null;
4314        final long now = System.currentTimeMillis();
4315
4316        synchronized (mPackages) {
4317            final int[] allUsers = sUserManager.getUserIds();
4318            final int libCount = mSharedLibraries.size();
4319            for (int i = 0; i < libCount; i++) {
4320                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4321                if (versionedLib == null) {
4322                    continue;
4323                }
4324                final int versionCount = versionedLib.size();
4325                for (int j = 0; j < versionCount; j++) {
4326                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4327                    // Skip packages that are not static shared libs.
4328                    if (!libInfo.isStatic()) {
4329                        break;
4330                    }
4331                    // Important: We skip static shared libs used for some user since
4332                    // in such a case we need to keep the APK on the device. The check for
4333                    // a lib being used for any user is performed by the uninstall call.
4334                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4335                    // Resolve the package name - we use synthetic package names internally
4336                    final String internalPackageName = resolveInternalPackageNameLPr(
4337                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4338                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4339                    // Skip unused static shared libs cached less than the min period
4340                    // to prevent pruning a lib needed by a subsequently installed package.
4341                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4342                        continue;
4343                    }
4344                    if (packagesToDelete == null) {
4345                        packagesToDelete = new ArrayList<>();
4346                    }
4347                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4348                            declaringPackage.getVersionCode()));
4349                }
4350            }
4351        }
4352
4353        if (packagesToDelete != null) {
4354            final int packageCount = packagesToDelete.size();
4355            for (int i = 0; i < packageCount; i++) {
4356                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4357                // Delete the package synchronously (will fail of the lib used for any user).
4358                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4359                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4360                                == PackageManager.DELETE_SUCCEEDED) {
4361                    if (volume.getUsableSpace() >= neededSpace) {
4362                        return true;
4363                    }
4364                }
4365            }
4366        }
4367
4368        return false;
4369    }
4370
4371    /**
4372     * Update given flags based on encryption status of current user.
4373     */
4374    private int updateFlags(int flags, int userId) {
4375        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4376                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4377            // Caller expressed an explicit opinion about what encryption
4378            // aware/unaware components they want to see, so fall through and
4379            // give them what they want
4380        } else {
4381            // Caller expressed no opinion, so match based on user state
4382            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4384            } else {
4385                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4386            }
4387        }
4388        return flags;
4389    }
4390
4391    private UserManagerInternal getUserManagerInternal() {
4392        if (mUserManagerInternal == null) {
4393            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4394        }
4395        return mUserManagerInternal;
4396    }
4397
4398    private DeviceIdleController.LocalService getDeviceIdleController() {
4399        if (mDeviceIdleController == null) {
4400            mDeviceIdleController =
4401                    LocalServices.getService(DeviceIdleController.LocalService.class);
4402        }
4403        return mDeviceIdleController;
4404    }
4405
4406    /**
4407     * Update given flags when being used to request {@link PackageInfo}.
4408     */
4409    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4410        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4411        boolean triaged = true;
4412        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4413                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4414            // Caller is asking for component details, so they'd better be
4415            // asking for specific encryption matching behavior, or be triaged
4416            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4417                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4418                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4419                triaged = false;
4420            }
4421        }
4422        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4423                | PackageManager.MATCH_SYSTEM_ONLY
4424                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4425            triaged = false;
4426        }
4427        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4428            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4429                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4430                    + Debug.getCallers(5));
4431        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4432                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4433            // If the caller wants all packages and has a restricted profile associated with it,
4434            // then match all users. This is to make sure that launchers that need to access work
4435            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4436            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4437            flags |= PackageManager.MATCH_ANY_USER;
4438        }
4439        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4440            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4441                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4442        }
4443        return updateFlags(flags, userId);
4444    }
4445
4446    /**
4447     * Update given flags when being used to request {@link ApplicationInfo}.
4448     */
4449    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4450        return updateFlagsForPackage(flags, userId, cookie);
4451    }
4452
4453    /**
4454     * Update given flags when being used to request {@link ComponentInfo}.
4455     */
4456    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4457        if (cookie instanceof Intent) {
4458            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4459                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4460            }
4461        }
4462
4463        boolean triaged = true;
4464        // Caller is asking for component details, so they'd better be
4465        // asking for specific encryption matching behavior, or be triaged
4466        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4467                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4468                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4469            triaged = false;
4470        }
4471        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4472            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4473                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4474        }
4475
4476        return updateFlags(flags, userId);
4477    }
4478
4479    /**
4480     * Update given intent when being used to request {@link ResolveInfo}.
4481     */
4482    private Intent updateIntentForResolve(Intent intent) {
4483        if (intent.getSelector() != null) {
4484            intent = intent.getSelector();
4485        }
4486        if (DEBUG_PREFERRED) {
4487            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4488        }
4489        return intent;
4490    }
4491
4492    /**
4493     * Update given flags when being used to request {@link ResolveInfo}.
4494     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4495     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4496     * flag set. However, this flag is only honoured in three circumstances:
4497     * <ul>
4498     * <li>when called from a system process</li>
4499     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4500     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4501     * action and a {@code android.intent.category.BROWSABLE} category</li>
4502     * </ul>
4503     */
4504    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4505        return updateFlagsForResolve(flags, userId, intent, callingUid,
4506                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4507    }
4508    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4509            boolean wantInstantApps) {
4510        return updateFlagsForResolve(flags, userId, intent, callingUid,
4511                wantInstantApps, false /*onlyExposedExplicitly*/);
4512    }
4513    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4514            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4515        // Safe mode means we shouldn't match any third-party components
4516        if (mSafeMode) {
4517            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4518        }
4519        if (getInstantAppPackageName(callingUid) != null) {
4520            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4521            if (onlyExposedExplicitly) {
4522                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4523            }
4524            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4525            flags |= PackageManager.MATCH_INSTANT;
4526        } else {
4527            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4528            final boolean allowMatchInstant =
4529                    (wantInstantApps
4530                            && Intent.ACTION_VIEW.equals(intent.getAction())
4531                            && hasWebURI(intent))
4532                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4533            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4534                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4535            if (!allowMatchInstant) {
4536                flags &= ~PackageManager.MATCH_INSTANT;
4537            }
4538        }
4539        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4540    }
4541
4542    @Override
4543    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4544        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4545    }
4546
4547    /**
4548     * Important: The provided filterCallingUid is used exclusively to filter out activities
4549     * that can be seen based on user state. It's typically the original caller uid prior
4550     * to clearing. Because it can only be provided by trusted code, it's value can be
4551     * trusted and will be used as-is; unlike userId which will be validated by this method.
4552     */
4553    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4554            int filterCallingUid, int userId) {
4555        if (!sUserManager.exists(userId)) return null;
4556        flags = updateFlagsForComponent(flags, userId, component);
4557        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4558                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4559        synchronized (mPackages) {
4560            PackageParser.Activity a = mActivities.mActivities.get(component);
4561
4562            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4563            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4564                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4565                if (ps == null) return null;
4566                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4567                    return null;
4568                }
4569                return PackageParser.generateActivityInfo(
4570                        a, flags, ps.readUserState(userId), userId);
4571            }
4572            if (mResolveComponentName.equals(component)) {
4573                return PackageParser.generateActivityInfo(
4574                        mResolveActivity, flags, new PackageUserState(), userId);
4575            }
4576        }
4577        return null;
4578    }
4579
4580    @Override
4581    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4582            String resolvedType) {
4583        synchronized (mPackages) {
4584            if (component.equals(mResolveComponentName)) {
4585                // The resolver supports EVERYTHING!
4586                return true;
4587            }
4588            final int callingUid = Binder.getCallingUid();
4589            final int callingUserId = UserHandle.getUserId(callingUid);
4590            PackageParser.Activity a = mActivities.mActivities.get(component);
4591            if (a == null) {
4592                return false;
4593            }
4594            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4595            if (ps == null) {
4596                return false;
4597            }
4598            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4599                return false;
4600            }
4601            for (int i=0; i<a.intents.size(); i++) {
4602                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4603                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4604                    return true;
4605                }
4606            }
4607            return false;
4608        }
4609    }
4610
4611    @Override
4612    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4613        if (!sUserManager.exists(userId)) return null;
4614        final int callingUid = Binder.getCallingUid();
4615        flags = updateFlagsForComponent(flags, userId, component);
4616        enforceCrossUserPermission(callingUid, userId,
4617                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4618        synchronized (mPackages) {
4619            PackageParser.Activity a = mReceivers.mActivities.get(component);
4620            if (DEBUG_PACKAGE_INFO) Log.v(
4621                TAG, "getReceiverInfo " + component + ": " + a);
4622            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4623                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4624                if (ps == null) return null;
4625                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4626                    return null;
4627                }
4628                return PackageParser.generateActivityInfo(
4629                        a, flags, ps.readUserState(userId), userId);
4630            }
4631        }
4632        return null;
4633    }
4634
4635    @Override
4636    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4637            int flags, int userId) {
4638        if (!sUserManager.exists(userId)) return null;
4639        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4640        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4641            return null;
4642        }
4643
4644        flags = updateFlagsForPackage(flags, userId, null);
4645
4646        final boolean canSeeStaticLibraries =
4647                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4648                        == PERMISSION_GRANTED
4649                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4650                        == PERMISSION_GRANTED
4651                || canRequestPackageInstallsInternal(packageName,
4652                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4653                        false  /* throwIfPermNotDeclared*/)
4654                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4655                        == PERMISSION_GRANTED;
4656
4657        synchronized (mPackages) {
4658            List<SharedLibraryInfo> result = null;
4659
4660            final int libCount = mSharedLibraries.size();
4661            for (int i = 0; i < libCount; i++) {
4662                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4663                if (versionedLib == null) {
4664                    continue;
4665                }
4666
4667                final int versionCount = versionedLib.size();
4668                for (int j = 0; j < versionCount; j++) {
4669                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4670                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4671                        break;
4672                    }
4673                    final long identity = Binder.clearCallingIdentity();
4674                    try {
4675                        PackageInfo packageInfo = getPackageInfoVersioned(
4676                                libInfo.getDeclaringPackage(), flags
4677                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4678                        if (packageInfo == null) {
4679                            continue;
4680                        }
4681                    } finally {
4682                        Binder.restoreCallingIdentity(identity);
4683                    }
4684
4685                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4686                            libInfo.getVersion(), libInfo.getType(),
4687                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4688                            flags, userId));
4689
4690                    if (result == null) {
4691                        result = new ArrayList<>();
4692                    }
4693                    result.add(resLibInfo);
4694                }
4695            }
4696
4697            return result != null ? new ParceledListSlice<>(result) : null;
4698        }
4699    }
4700
4701    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4702            SharedLibraryInfo libInfo, int flags, int userId) {
4703        List<VersionedPackage> versionedPackages = null;
4704        final int packageCount = mSettings.mPackages.size();
4705        for (int i = 0; i < packageCount; i++) {
4706            PackageSetting ps = mSettings.mPackages.valueAt(i);
4707
4708            if (ps == null) {
4709                continue;
4710            }
4711
4712            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4713                continue;
4714            }
4715
4716            final String libName = libInfo.getName();
4717            if (libInfo.isStatic()) {
4718                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4719                if (libIdx < 0) {
4720                    continue;
4721                }
4722                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4723                    continue;
4724                }
4725                if (versionedPackages == null) {
4726                    versionedPackages = new ArrayList<>();
4727                }
4728                // If the dependent is a static shared lib, use the public package name
4729                String dependentPackageName = ps.name;
4730                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4731                    dependentPackageName = ps.pkg.manifestPackageName;
4732                }
4733                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4734            } else if (ps.pkg != null) {
4735                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4736                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4737                    if (versionedPackages == null) {
4738                        versionedPackages = new ArrayList<>();
4739                    }
4740                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4741                }
4742            }
4743        }
4744
4745        return versionedPackages;
4746    }
4747
4748    @Override
4749    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4750        if (!sUserManager.exists(userId)) return null;
4751        final int callingUid = Binder.getCallingUid();
4752        flags = updateFlagsForComponent(flags, userId, component);
4753        enforceCrossUserPermission(callingUid, userId,
4754                false /* requireFullPermission */, false /* checkShell */, "get service info");
4755        synchronized (mPackages) {
4756            PackageParser.Service s = mServices.mServices.get(component);
4757            if (DEBUG_PACKAGE_INFO) Log.v(
4758                TAG, "getServiceInfo " + component + ": " + s);
4759            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4760                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4761                if (ps == null) return null;
4762                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4763                    return null;
4764                }
4765                return PackageParser.generateServiceInfo(
4766                        s, flags, ps.readUserState(userId), userId);
4767            }
4768        }
4769        return null;
4770    }
4771
4772    @Override
4773    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4774        if (!sUserManager.exists(userId)) return null;
4775        final int callingUid = Binder.getCallingUid();
4776        flags = updateFlagsForComponent(flags, userId, component);
4777        enforceCrossUserPermission(callingUid, userId,
4778                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4779        synchronized (mPackages) {
4780            PackageParser.Provider p = mProviders.mProviders.get(component);
4781            if (DEBUG_PACKAGE_INFO) Log.v(
4782                TAG, "getProviderInfo " + component + ": " + p);
4783            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4784                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4785                if (ps == null) return null;
4786                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4787                    return null;
4788                }
4789                return PackageParser.generateProviderInfo(
4790                        p, flags, ps.readUserState(userId), userId);
4791            }
4792        }
4793        return null;
4794    }
4795
4796    @Override
4797    public String[] getSystemSharedLibraryNames() {
4798        // allow instant applications
4799        synchronized (mPackages) {
4800            Set<String> libs = null;
4801            final int libCount = mSharedLibraries.size();
4802            for (int i = 0; i < libCount; i++) {
4803                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4804                if (versionedLib == null) {
4805                    continue;
4806                }
4807                final int versionCount = versionedLib.size();
4808                for (int j = 0; j < versionCount; j++) {
4809                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4810                    if (!libEntry.info.isStatic()) {
4811                        if (libs == null) {
4812                            libs = new ArraySet<>();
4813                        }
4814                        libs.add(libEntry.info.getName());
4815                        break;
4816                    }
4817                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4818                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4819                            UserHandle.getUserId(Binder.getCallingUid()),
4820                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4821                        if (libs == null) {
4822                            libs = new ArraySet<>();
4823                        }
4824                        libs.add(libEntry.info.getName());
4825                        break;
4826                    }
4827                }
4828            }
4829
4830            if (libs != null) {
4831                String[] libsArray = new String[libs.size()];
4832                libs.toArray(libsArray);
4833                return libsArray;
4834            }
4835
4836            return null;
4837        }
4838    }
4839
4840    @Override
4841    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4842        // allow instant applications
4843        synchronized (mPackages) {
4844            return mServicesSystemSharedLibraryPackageName;
4845        }
4846    }
4847
4848    @Override
4849    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4850        // allow instant applications
4851        synchronized (mPackages) {
4852            return mSharedSystemSharedLibraryPackageName;
4853        }
4854    }
4855
4856    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4857        for (int i = userList.length - 1; i >= 0; --i) {
4858            final int userId = userList[i];
4859            // don't add instant app to the list of updates
4860            if (pkgSetting.getInstantApp(userId)) {
4861                continue;
4862            }
4863            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4864            if (changedPackages == null) {
4865                changedPackages = new SparseArray<>();
4866                mChangedPackages.put(userId, changedPackages);
4867            }
4868            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4869            if (sequenceNumbers == null) {
4870                sequenceNumbers = new HashMap<>();
4871                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4872            }
4873            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4874            if (sequenceNumber != null) {
4875                changedPackages.remove(sequenceNumber);
4876            }
4877            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4878            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4879        }
4880        mChangedPackagesSequenceNumber++;
4881    }
4882
4883    @Override
4884    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4886            return null;
4887        }
4888        synchronized (mPackages) {
4889            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4890                return null;
4891            }
4892            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4893            if (changedPackages == null) {
4894                return null;
4895            }
4896            final List<String> packageNames =
4897                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4898            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4899                final String packageName = changedPackages.get(i);
4900                if (packageName != null) {
4901                    packageNames.add(packageName);
4902                }
4903            }
4904            return packageNames.isEmpty()
4905                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4906        }
4907    }
4908
4909    @Override
4910    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4911        // allow instant applications
4912        ArrayList<FeatureInfo> res;
4913        synchronized (mAvailableFeatures) {
4914            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4915            res.addAll(mAvailableFeatures.values());
4916        }
4917        final FeatureInfo fi = new FeatureInfo();
4918        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4919                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4920        res.add(fi);
4921
4922        return new ParceledListSlice<>(res);
4923    }
4924
4925    @Override
4926    public boolean hasSystemFeature(String name, int version) {
4927        // allow instant applications
4928        synchronized (mAvailableFeatures) {
4929            final FeatureInfo feat = mAvailableFeatures.get(name);
4930            if (feat == null) {
4931                return false;
4932            } else {
4933                return feat.version >= version;
4934            }
4935        }
4936    }
4937
4938    @Override
4939    public int checkPermission(String permName, String pkgName, int userId) {
4940        if (!sUserManager.exists(userId)) {
4941            return PackageManager.PERMISSION_DENIED;
4942        }
4943        final int callingUid = Binder.getCallingUid();
4944
4945        synchronized (mPackages) {
4946            final PackageParser.Package p = mPackages.get(pkgName);
4947            if (p != null && p.mExtras != null) {
4948                final PackageSetting ps = (PackageSetting) p.mExtras;
4949                if (filterAppAccessLPr(ps, callingUid, userId)) {
4950                    return PackageManager.PERMISSION_DENIED;
4951                }
4952                final boolean instantApp = ps.getInstantApp(userId);
4953                final PermissionsState permissionsState = ps.getPermissionsState();
4954                if (permissionsState.hasPermission(permName, userId)) {
4955                    if (instantApp) {
4956                        BasePermission bp = mSettings.mPermissions.get(permName);
4957                        if (bp != null && bp.isInstant()) {
4958                            return PackageManager.PERMISSION_GRANTED;
4959                        }
4960                    } else {
4961                        return PackageManager.PERMISSION_GRANTED;
4962                    }
4963                }
4964                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4965                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4966                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4967                    return PackageManager.PERMISSION_GRANTED;
4968                }
4969            }
4970        }
4971
4972        return PackageManager.PERMISSION_DENIED;
4973    }
4974
4975    @Override
4976    public int checkUidPermission(String permName, int uid) {
4977        final int callingUid = Binder.getCallingUid();
4978        final int callingUserId = UserHandle.getUserId(callingUid);
4979        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4980        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4981        final int userId = UserHandle.getUserId(uid);
4982        if (!sUserManager.exists(userId)) {
4983            return PackageManager.PERMISSION_DENIED;
4984        }
4985
4986        synchronized (mPackages) {
4987            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4988            if (obj != null) {
4989                if (obj instanceof SharedUserSetting) {
4990                    if (isCallerInstantApp) {
4991                        return PackageManager.PERMISSION_DENIED;
4992                    }
4993                } else if (obj instanceof PackageSetting) {
4994                    final PackageSetting ps = (PackageSetting) obj;
4995                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4996                        return PackageManager.PERMISSION_DENIED;
4997                    }
4998                }
4999                final SettingBase settingBase = (SettingBase) obj;
5000                final PermissionsState permissionsState = settingBase.getPermissionsState();
5001                if (permissionsState.hasPermission(permName, userId)) {
5002                    if (isUidInstantApp) {
5003                        BasePermission bp = mSettings.mPermissions.get(permName);
5004                        if (bp != null && bp.isInstant()) {
5005                            return PackageManager.PERMISSION_GRANTED;
5006                        }
5007                    } else {
5008                        return PackageManager.PERMISSION_GRANTED;
5009                    }
5010                }
5011                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5012                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5013                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5014                    return PackageManager.PERMISSION_GRANTED;
5015                }
5016            } else {
5017                ArraySet<String> perms = mSystemPermissions.get(uid);
5018                if (perms != null) {
5019                    if (perms.contains(permName)) {
5020                        return PackageManager.PERMISSION_GRANTED;
5021                    }
5022                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5023                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5024                        return PackageManager.PERMISSION_GRANTED;
5025                    }
5026                }
5027            }
5028        }
5029
5030        return PackageManager.PERMISSION_DENIED;
5031    }
5032
5033    @Override
5034    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5035        if (UserHandle.getCallingUserId() != userId) {
5036            mContext.enforceCallingPermission(
5037                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5038                    "isPermissionRevokedByPolicy for user " + userId);
5039        }
5040
5041        if (checkPermission(permission, packageName, userId)
5042                == PackageManager.PERMISSION_GRANTED) {
5043            return false;
5044        }
5045
5046        final int callingUid = Binder.getCallingUid();
5047        if (getInstantAppPackageName(callingUid) != null) {
5048            if (!isCallerSameApp(packageName, callingUid)) {
5049                return false;
5050            }
5051        } else {
5052            if (isInstantApp(packageName, userId)) {
5053                return false;
5054            }
5055        }
5056
5057        final long identity = Binder.clearCallingIdentity();
5058        try {
5059            final int flags = getPermissionFlags(permission, packageName, userId);
5060            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5061        } finally {
5062            Binder.restoreCallingIdentity(identity);
5063        }
5064    }
5065
5066    @Override
5067    public String getPermissionControllerPackageName() {
5068        synchronized (mPackages) {
5069            return mRequiredInstallerPackage;
5070        }
5071    }
5072
5073    /**
5074     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5075     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5076     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5077     * @param message the message to log on security exception
5078     */
5079    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5080            boolean checkShell, String message) {
5081        if (userId < 0) {
5082            throw new IllegalArgumentException("Invalid userId " + userId);
5083        }
5084        if (checkShell) {
5085            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5086        }
5087        if (userId == UserHandle.getUserId(callingUid)) return;
5088        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5089            if (requireFullPermission) {
5090                mContext.enforceCallingOrSelfPermission(
5091                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5092            } else {
5093                try {
5094                    mContext.enforceCallingOrSelfPermission(
5095                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5096                } catch (SecurityException se) {
5097                    mContext.enforceCallingOrSelfPermission(
5098                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5099                }
5100            }
5101        }
5102    }
5103
5104    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5105        if (callingUid == Process.SHELL_UID) {
5106            if (userHandle >= 0
5107                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5108                throw new SecurityException("Shell does not have permission to access user "
5109                        + userHandle);
5110            } else if (userHandle < 0) {
5111                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5112                        + Debug.getCallers(3));
5113            }
5114        }
5115    }
5116
5117    private BasePermission findPermissionTreeLP(String permName) {
5118        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5119            if (permName.startsWith(bp.name) &&
5120                    permName.length() > bp.name.length() &&
5121                    permName.charAt(bp.name.length()) == '.') {
5122                return bp;
5123            }
5124        }
5125        return null;
5126    }
5127
5128    private BasePermission checkPermissionTreeLP(String permName) {
5129        if (permName != null) {
5130            BasePermission bp = findPermissionTreeLP(permName);
5131            if (bp != null) {
5132                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5133                    return bp;
5134                }
5135                throw new SecurityException("Calling uid "
5136                        + Binder.getCallingUid()
5137                        + " is not allowed to add to permission tree "
5138                        + bp.name + " owned by uid " + bp.uid);
5139            }
5140        }
5141        throw new SecurityException("No permission tree found for " + permName);
5142    }
5143
5144    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5145        if (s1 == null) {
5146            return s2 == null;
5147        }
5148        if (s2 == null) {
5149            return false;
5150        }
5151        if (s1.getClass() != s2.getClass()) {
5152            return false;
5153        }
5154        return s1.equals(s2);
5155    }
5156
5157    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5158        if (pi1.icon != pi2.icon) return false;
5159        if (pi1.logo != pi2.logo) return false;
5160        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5161        if (!compareStrings(pi1.name, pi2.name)) return false;
5162        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5163        // We'll take care of setting this one.
5164        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5165        // These are not currently stored in settings.
5166        //if (!compareStrings(pi1.group, pi2.group)) return false;
5167        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5168        //if (pi1.labelRes != pi2.labelRes) return false;
5169        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5170        return true;
5171    }
5172
5173    int permissionInfoFootprint(PermissionInfo info) {
5174        int size = info.name.length();
5175        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5176        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5177        return size;
5178    }
5179
5180    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5181        int size = 0;
5182        for (BasePermission perm : mSettings.mPermissions.values()) {
5183            if (perm.uid == tree.uid) {
5184                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5185            }
5186        }
5187        return size;
5188    }
5189
5190    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5191        // We calculate the max size of permissions defined by this uid and throw
5192        // if that plus the size of 'info' would exceed our stated maximum.
5193        if (tree.uid != Process.SYSTEM_UID) {
5194            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5195            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5196                throw new SecurityException("Permission tree size cap exceeded");
5197            }
5198        }
5199    }
5200
5201    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5202        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5203            throw new SecurityException("Instant apps can't add permissions");
5204        }
5205        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5206            throw new SecurityException("Label must be specified in permission");
5207        }
5208        BasePermission tree = checkPermissionTreeLP(info.name);
5209        BasePermission bp = mSettings.mPermissions.get(info.name);
5210        boolean added = bp == null;
5211        boolean changed = true;
5212        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5213        if (added) {
5214            enforcePermissionCapLocked(info, tree);
5215            bp = new BasePermission(info.name, tree.sourcePackage,
5216                    BasePermission.TYPE_DYNAMIC);
5217        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5218            throw new SecurityException(
5219                    "Not allowed to modify non-dynamic permission "
5220                    + info.name);
5221        } else {
5222            if (bp.protectionLevel == fixedLevel
5223                    && bp.perm.owner.equals(tree.perm.owner)
5224                    && bp.uid == tree.uid
5225                    && comparePermissionInfos(bp.perm.info, info)) {
5226                changed = false;
5227            }
5228        }
5229        bp.protectionLevel = fixedLevel;
5230        info = new PermissionInfo(info);
5231        info.protectionLevel = fixedLevel;
5232        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5233        bp.perm.info.packageName = tree.perm.info.packageName;
5234        bp.uid = tree.uid;
5235        if (added) {
5236            mSettings.mPermissions.put(info.name, bp);
5237        }
5238        if (changed) {
5239            if (!async) {
5240                mSettings.writeLPr();
5241            } else {
5242                scheduleWriteSettingsLocked();
5243            }
5244        }
5245        return added;
5246    }
5247
5248    @Override
5249    public boolean addPermission(PermissionInfo info) {
5250        synchronized (mPackages) {
5251            return addPermissionLocked(info, false);
5252        }
5253    }
5254
5255    @Override
5256    public boolean addPermissionAsync(PermissionInfo info) {
5257        synchronized (mPackages) {
5258            return addPermissionLocked(info, true);
5259        }
5260    }
5261
5262    @Override
5263    public void removePermission(String name) {
5264        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5265            throw new SecurityException("Instant applications don't have access to this method");
5266        }
5267        synchronized (mPackages) {
5268            checkPermissionTreeLP(name);
5269            BasePermission bp = mSettings.mPermissions.get(name);
5270            if (bp != null) {
5271                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5272                    throw new SecurityException(
5273                            "Not allowed to modify non-dynamic permission "
5274                            + name);
5275                }
5276                mSettings.mPermissions.remove(name);
5277                mSettings.writeLPr();
5278            }
5279        }
5280    }
5281
5282    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5283            PackageParser.Package pkg, BasePermission bp) {
5284        int index = pkg.requestedPermissions.indexOf(bp.name);
5285        if (index == -1) {
5286            throw new SecurityException("Package " + pkg.packageName
5287                    + " has not requested permission " + bp.name);
5288        }
5289        if (!bp.isRuntime() && !bp.isDevelopment()) {
5290            throw new SecurityException("Permission " + bp.name
5291                    + " is not a changeable permission type");
5292        }
5293    }
5294
5295    @Override
5296    public void grantRuntimePermission(String packageName, String name, final int userId) {
5297        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5298    }
5299
5300    private void grantRuntimePermission(String packageName, String name, final int userId,
5301            boolean overridePolicy) {
5302        if (!sUserManager.exists(userId)) {
5303            Log.e(TAG, "No such user:" + userId);
5304            return;
5305        }
5306        final int callingUid = Binder.getCallingUid();
5307
5308        mContext.enforceCallingOrSelfPermission(
5309                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5310                "grantRuntimePermission");
5311
5312        enforceCrossUserPermission(callingUid, userId,
5313                true /* requireFullPermission */, true /* checkShell */,
5314                "grantRuntimePermission");
5315
5316        final int uid;
5317        final PackageSetting ps;
5318
5319        synchronized (mPackages) {
5320            final PackageParser.Package pkg = mPackages.get(packageName);
5321            if (pkg == null) {
5322                throw new IllegalArgumentException("Unknown package: " + packageName);
5323            }
5324            final BasePermission bp = mSettings.mPermissions.get(name);
5325            if (bp == null) {
5326                throw new IllegalArgumentException("Unknown permission: " + name);
5327            }
5328            ps = (PackageSetting) pkg.mExtras;
5329            if (ps == null
5330                    || filterAppAccessLPr(ps, callingUid, userId)) {
5331                throw new IllegalArgumentException("Unknown package: " + packageName);
5332            }
5333
5334            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5335
5336            // If a permission review is required for legacy apps we represent
5337            // their permissions as always granted runtime ones since we need
5338            // to keep the review required permission flag per user while an
5339            // install permission's state is shared across all users.
5340            if (mPermissionReviewRequired
5341                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5342                    && bp.isRuntime()) {
5343                return;
5344            }
5345
5346            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5347
5348            final PermissionsState permissionsState = ps.getPermissionsState();
5349
5350            final int flags = permissionsState.getPermissionFlags(name, userId);
5351            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5352                throw new SecurityException("Cannot grant system fixed permission "
5353                        + name + " for package " + packageName);
5354            }
5355            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5356                throw new SecurityException("Cannot grant policy fixed permission "
5357                        + name + " for package " + packageName);
5358            }
5359
5360            if (bp.isDevelopment()) {
5361                // Development permissions must be handled specially, since they are not
5362                // normal runtime permissions.  For now they apply to all users.
5363                if (permissionsState.grantInstallPermission(bp) !=
5364                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5365                    scheduleWriteSettingsLocked();
5366                }
5367                return;
5368            }
5369
5370            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5371                throw new SecurityException("Cannot grant non-ephemeral permission"
5372                        + name + " for package " + packageName);
5373            }
5374
5375            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5376                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5377                return;
5378            }
5379
5380            final int result = permissionsState.grantRuntimePermission(bp, userId);
5381            switch (result) {
5382                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5383                    return;
5384                }
5385
5386                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5387                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5388                    mHandler.post(new Runnable() {
5389                        @Override
5390                        public void run() {
5391                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5392                        }
5393                    });
5394                }
5395                break;
5396            }
5397
5398            if (bp.isRuntime()) {
5399                logPermissionGranted(mContext, name, packageName);
5400            }
5401
5402            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5403
5404            // Not critical if that is lost - app has to request again.
5405            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5406        }
5407
5408        // Only need to do this if user is initialized. Otherwise it's a new user
5409        // and there are no processes running as the user yet and there's no need
5410        // to make an expensive call to remount processes for the changed permissions.
5411        if (READ_EXTERNAL_STORAGE.equals(name)
5412                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5413            final long token = Binder.clearCallingIdentity();
5414            try {
5415                if (sUserManager.isInitialized(userId)) {
5416                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5417                            StorageManagerInternal.class);
5418                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5419                }
5420            } finally {
5421                Binder.restoreCallingIdentity(token);
5422            }
5423        }
5424    }
5425
5426    @Override
5427    public void revokeRuntimePermission(String packageName, String name, int userId) {
5428        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5429    }
5430
5431    private void revokeRuntimePermission(String packageName, String name, int userId,
5432            boolean overridePolicy) {
5433        if (!sUserManager.exists(userId)) {
5434            Log.e(TAG, "No such user:" + userId);
5435            return;
5436        }
5437
5438        mContext.enforceCallingOrSelfPermission(
5439                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5440                "revokeRuntimePermission");
5441
5442        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5443                true /* requireFullPermission */, true /* checkShell */,
5444                "revokeRuntimePermission");
5445
5446        final int appId;
5447
5448        synchronized (mPackages) {
5449            final PackageParser.Package pkg = mPackages.get(packageName);
5450            if (pkg == null) {
5451                throw new IllegalArgumentException("Unknown package: " + packageName);
5452            }
5453            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5454            if (ps == null
5455                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5456                throw new IllegalArgumentException("Unknown package: " + packageName);
5457            }
5458            final BasePermission bp = mSettings.mPermissions.get(name);
5459            if (bp == null) {
5460                throw new IllegalArgumentException("Unknown permission: " + name);
5461            }
5462
5463            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5464
5465            // If a permission review is required for legacy apps we represent
5466            // their permissions as always granted runtime ones since we need
5467            // to keep the review required permission flag per user while an
5468            // install permission's state is shared across all users.
5469            if (mPermissionReviewRequired
5470                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5471                    && bp.isRuntime()) {
5472                return;
5473            }
5474
5475            final PermissionsState permissionsState = ps.getPermissionsState();
5476
5477            final int flags = permissionsState.getPermissionFlags(name, userId);
5478            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5479                throw new SecurityException("Cannot revoke system fixed permission "
5480                        + name + " for package " + packageName);
5481            }
5482            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5483                throw new SecurityException("Cannot revoke policy fixed permission "
5484                        + name + " for package " + packageName);
5485            }
5486
5487            if (bp.isDevelopment()) {
5488                // Development permissions must be handled specially, since they are not
5489                // normal runtime permissions.  For now they apply to all users.
5490                if (permissionsState.revokeInstallPermission(bp) !=
5491                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5492                    scheduleWriteSettingsLocked();
5493                }
5494                return;
5495            }
5496
5497            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5498                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5499                return;
5500            }
5501
5502            if (bp.isRuntime()) {
5503                logPermissionRevoked(mContext, name, packageName);
5504            }
5505
5506            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5507
5508            // Critical, after this call app should never have the permission.
5509            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5510
5511            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5512        }
5513
5514        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5515    }
5516
5517    /**
5518     * Get the first event id for the permission.
5519     *
5520     * <p>There are four events for each permission: <ul>
5521     *     <li>Request permission: first id + 0</li>
5522     *     <li>Grant permission: first id + 1</li>
5523     *     <li>Request for permission denied: first id + 2</li>
5524     *     <li>Revoke permission: first id + 3</li>
5525     * </ul></p>
5526     *
5527     * @param name name of the permission
5528     *
5529     * @return The first event id for the permission
5530     */
5531    private static int getBaseEventId(@NonNull String name) {
5532        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5533
5534        if (eventIdIndex == -1) {
5535            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5536                    || Build.IS_USER) {
5537                Log.i(TAG, "Unknown permission " + name);
5538
5539                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5540            } else {
5541                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5542                //
5543                // Also update
5544                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5545                // - metrics_constants.proto
5546                throw new IllegalStateException("Unknown permission " + name);
5547            }
5548        }
5549
5550        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5551    }
5552
5553    /**
5554     * Log that a permission was revoked.
5555     *
5556     * @param context Context of the caller
5557     * @param name name of the permission
5558     * @param packageName package permission if for
5559     */
5560    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5561            @NonNull String packageName) {
5562        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5563    }
5564
5565    /**
5566     * Log that a permission request was granted.
5567     *
5568     * @param context Context of the caller
5569     * @param name name of the permission
5570     * @param packageName package permission if for
5571     */
5572    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5573            @NonNull String packageName) {
5574        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5575    }
5576
5577    @Override
5578    public void resetRuntimePermissions() {
5579        mContext.enforceCallingOrSelfPermission(
5580                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5581                "revokeRuntimePermission");
5582
5583        int callingUid = Binder.getCallingUid();
5584        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5585            mContext.enforceCallingOrSelfPermission(
5586                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5587                    "resetRuntimePermissions");
5588        }
5589
5590        synchronized (mPackages) {
5591            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5592            for (int userId : UserManagerService.getInstance().getUserIds()) {
5593                final int packageCount = mPackages.size();
5594                for (int i = 0; i < packageCount; i++) {
5595                    PackageParser.Package pkg = mPackages.valueAt(i);
5596                    if (!(pkg.mExtras instanceof PackageSetting)) {
5597                        continue;
5598                    }
5599                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5600                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5601                }
5602            }
5603        }
5604    }
5605
5606    @Override
5607    public int getPermissionFlags(String name, String packageName, int userId) {
5608        if (!sUserManager.exists(userId)) {
5609            return 0;
5610        }
5611
5612        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5613
5614        final int callingUid = Binder.getCallingUid();
5615        enforceCrossUserPermission(callingUid, userId,
5616                true /* requireFullPermission */, false /* checkShell */,
5617                "getPermissionFlags");
5618
5619        synchronized (mPackages) {
5620            final PackageParser.Package pkg = mPackages.get(packageName);
5621            if (pkg == null) {
5622                return 0;
5623            }
5624            final BasePermission bp = mSettings.mPermissions.get(name);
5625            if (bp == null) {
5626                return 0;
5627            }
5628            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5629            if (ps == null
5630                    || filterAppAccessLPr(ps, callingUid, userId)) {
5631                return 0;
5632            }
5633            PermissionsState permissionsState = ps.getPermissionsState();
5634            return permissionsState.getPermissionFlags(name, userId);
5635        }
5636    }
5637
5638    @Override
5639    public void updatePermissionFlags(String name, String packageName, int flagMask,
5640            int flagValues, int userId) {
5641        if (!sUserManager.exists(userId)) {
5642            return;
5643        }
5644
5645        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5646
5647        final int callingUid = Binder.getCallingUid();
5648        enforceCrossUserPermission(callingUid, userId,
5649                true /* requireFullPermission */, true /* checkShell */,
5650                "updatePermissionFlags");
5651
5652        // Only the system can change these flags and nothing else.
5653        if (getCallingUid() != Process.SYSTEM_UID) {
5654            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5655            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5656            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5657            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5658            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5659        }
5660
5661        synchronized (mPackages) {
5662            final PackageParser.Package pkg = mPackages.get(packageName);
5663            if (pkg == null) {
5664                throw new IllegalArgumentException("Unknown package: " + packageName);
5665            }
5666            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5667            if (ps == null
5668                    || filterAppAccessLPr(ps, callingUid, userId)) {
5669                throw new IllegalArgumentException("Unknown package: " + packageName);
5670            }
5671
5672            final BasePermission bp = mSettings.mPermissions.get(name);
5673            if (bp == null) {
5674                throw new IllegalArgumentException("Unknown permission: " + name);
5675            }
5676
5677            PermissionsState permissionsState = ps.getPermissionsState();
5678
5679            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5680
5681            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5682                // Install and runtime permissions are stored in different places,
5683                // so figure out what permission changed and persist the change.
5684                if (permissionsState.getInstallPermissionState(name) != null) {
5685                    scheduleWriteSettingsLocked();
5686                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5687                        || hadState) {
5688                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5689                }
5690            }
5691        }
5692    }
5693
5694    /**
5695     * Update the permission flags for all packages and runtime permissions of a user in order
5696     * to allow device or profile owner to remove POLICY_FIXED.
5697     */
5698    @Override
5699    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5700        if (!sUserManager.exists(userId)) {
5701            return;
5702        }
5703
5704        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5705
5706        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5707                true /* requireFullPermission */, true /* checkShell */,
5708                "updatePermissionFlagsForAllApps");
5709
5710        // Only the system can change system fixed flags.
5711        if (getCallingUid() != Process.SYSTEM_UID) {
5712            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5713            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5714        }
5715
5716        synchronized (mPackages) {
5717            boolean changed = false;
5718            final int packageCount = mPackages.size();
5719            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5720                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5721                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5722                if (ps == null) {
5723                    continue;
5724                }
5725                PermissionsState permissionsState = ps.getPermissionsState();
5726                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5727                        userId, flagMask, flagValues);
5728            }
5729            if (changed) {
5730                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5731            }
5732        }
5733    }
5734
5735    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5736        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5737                != PackageManager.PERMISSION_GRANTED
5738            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5739                != PackageManager.PERMISSION_GRANTED) {
5740            throw new SecurityException(message + " requires "
5741                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5742                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5743        }
5744    }
5745
5746    @Override
5747    public boolean shouldShowRequestPermissionRationale(String permissionName,
5748            String packageName, int userId) {
5749        if (UserHandle.getCallingUserId() != userId) {
5750            mContext.enforceCallingPermission(
5751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5752                    "canShowRequestPermissionRationale for user " + userId);
5753        }
5754
5755        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5756        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5757            return false;
5758        }
5759
5760        if (checkPermission(permissionName, packageName, userId)
5761                == PackageManager.PERMISSION_GRANTED) {
5762            return false;
5763        }
5764
5765        final int flags;
5766
5767        final long identity = Binder.clearCallingIdentity();
5768        try {
5769            flags = getPermissionFlags(permissionName,
5770                    packageName, userId);
5771        } finally {
5772            Binder.restoreCallingIdentity(identity);
5773        }
5774
5775        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5776                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5777                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5778
5779        if ((flags & fixedFlags) != 0) {
5780            return false;
5781        }
5782
5783        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5784    }
5785
5786    @Override
5787    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5788        mContext.enforceCallingOrSelfPermission(
5789                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5790                "addOnPermissionsChangeListener");
5791
5792        synchronized (mPackages) {
5793            mOnPermissionChangeListeners.addListenerLocked(listener);
5794        }
5795    }
5796
5797    @Override
5798    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5799        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5800            throw new SecurityException("Instant applications don't have access to this method");
5801        }
5802        synchronized (mPackages) {
5803            mOnPermissionChangeListeners.removeListenerLocked(listener);
5804        }
5805    }
5806
5807    @Override
5808    public boolean isProtectedBroadcast(String actionName) {
5809        // allow instant applications
5810        synchronized (mProtectedBroadcasts) {
5811            if (mProtectedBroadcasts.contains(actionName)) {
5812                return true;
5813            } else if (actionName != null) {
5814                // TODO: remove these terrible hacks
5815                if (actionName.startsWith("android.net.netmon.lingerExpired")
5816                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5817                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5818                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5819                    return true;
5820                }
5821            }
5822        }
5823        return false;
5824    }
5825
5826    @Override
5827    public int checkSignatures(String pkg1, String pkg2) {
5828        synchronized (mPackages) {
5829            final PackageParser.Package p1 = mPackages.get(pkg1);
5830            final PackageParser.Package p2 = mPackages.get(pkg2);
5831            if (p1 == null || p1.mExtras == null
5832                    || p2 == null || p2.mExtras == null) {
5833                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5834            }
5835            final int callingUid = Binder.getCallingUid();
5836            final int callingUserId = UserHandle.getUserId(callingUid);
5837            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5838            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5839            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5840                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5841                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5842            }
5843            return compareSignatures(p1.mSignatures, p2.mSignatures);
5844        }
5845    }
5846
5847    @Override
5848    public int checkUidSignatures(int uid1, int uid2) {
5849        final int callingUid = Binder.getCallingUid();
5850        final int callingUserId = UserHandle.getUserId(callingUid);
5851        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5852        // Map to base uids.
5853        uid1 = UserHandle.getAppId(uid1);
5854        uid2 = UserHandle.getAppId(uid2);
5855        // reader
5856        synchronized (mPackages) {
5857            Signature[] s1;
5858            Signature[] s2;
5859            Object obj = mSettings.getUserIdLPr(uid1);
5860            if (obj != null) {
5861                if (obj instanceof SharedUserSetting) {
5862                    if (isCallerInstantApp) {
5863                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5864                    }
5865                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5866                } else if (obj instanceof PackageSetting) {
5867                    final PackageSetting ps = (PackageSetting) obj;
5868                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5869                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5870                    }
5871                    s1 = ps.signatures.mSignatures;
5872                } else {
5873                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5874                }
5875            } else {
5876                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5877            }
5878            obj = mSettings.getUserIdLPr(uid2);
5879            if (obj != null) {
5880                if (obj instanceof SharedUserSetting) {
5881                    if (isCallerInstantApp) {
5882                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5883                    }
5884                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5885                } else if (obj instanceof PackageSetting) {
5886                    final PackageSetting ps = (PackageSetting) obj;
5887                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5888                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5889                    }
5890                    s2 = ps.signatures.mSignatures;
5891                } else {
5892                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5893                }
5894            } else {
5895                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5896            }
5897            return compareSignatures(s1, s2);
5898        }
5899    }
5900
5901    /**
5902     * This method should typically only be used when granting or revoking
5903     * permissions, since the app may immediately restart after this call.
5904     * <p>
5905     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5906     * guard your work against the app being relaunched.
5907     */
5908    private void killUid(int appId, int userId, String reason) {
5909        final long identity = Binder.clearCallingIdentity();
5910        try {
5911            IActivityManager am = ActivityManager.getService();
5912            if (am != null) {
5913                try {
5914                    am.killUid(appId, userId, reason);
5915                } catch (RemoteException e) {
5916                    /* ignore - same process */
5917                }
5918            }
5919        } finally {
5920            Binder.restoreCallingIdentity(identity);
5921        }
5922    }
5923
5924    /**
5925     * Compares two sets of signatures. Returns:
5926     * <br />
5927     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5928     * <br />
5929     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5930     * <br />
5931     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5932     * <br />
5933     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5934     * <br />
5935     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5936     */
5937    static int compareSignatures(Signature[] s1, Signature[] s2) {
5938        if (s1 == null) {
5939            return s2 == null
5940                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5941                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5942        }
5943
5944        if (s2 == null) {
5945            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5946        }
5947
5948        if (s1.length != s2.length) {
5949            return PackageManager.SIGNATURE_NO_MATCH;
5950        }
5951
5952        // Since both signature sets are of size 1, we can compare without HashSets.
5953        if (s1.length == 1) {
5954            return s1[0].equals(s2[0]) ?
5955                    PackageManager.SIGNATURE_MATCH :
5956                    PackageManager.SIGNATURE_NO_MATCH;
5957        }
5958
5959        ArraySet<Signature> set1 = new ArraySet<Signature>();
5960        for (Signature sig : s1) {
5961            set1.add(sig);
5962        }
5963        ArraySet<Signature> set2 = new ArraySet<Signature>();
5964        for (Signature sig : s2) {
5965            set2.add(sig);
5966        }
5967        // Make sure s2 contains all signatures in s1.
5968        if (set1.equals(set2)) {
5969            return PackageManager.SIGNATURE_MATCH;
5970        }
5971        return PackageManager.SIGNATURE_NO_MATCH;
5972    }
5973
5974    /**
5975     * If the database version for this type of package (internal storage or
5976     * external storage) is less than the version where package signatures
5977     * were updated, return true.
5978     */
5979    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5980        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5981        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5982    }
5983
5984    /**
5985     * Used for backward compatibility to make sure any packages with
5986     * certificate chains get upgraded to the new style. {@code existingSigs}
5987     * will be in the old format (since they were stored on disk from before the
5988     * system upgrade) and {@code scannedSigs} will be in the newer format.
5989     */
5990    private int compareSignaturesCompat(PackageSignatures existingSigs,
5991            PackageParser.Package scannedPkg) {
5992        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5993            return PackageManager.SIGNATURE_NO_MATCH;
5994        }
5995
5996        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5997        for (Signature sig : existingSigs.mSignatures) {
5998            existingSet.add(sig);
5999        }
6000        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6001        for (Signature sig : scannedPkg.mSignatures) {
6002            try {
6003                Signature[] chainSignatures = sig.getChainSignatures();
6004                for (Signature chainSig : chainSignatures) {
6005                    scannedCompatSet.add(chainSig);
6006                }
6007            } catch (CertificateEncodingException e) {
6008                scannedCompatSet.add(sig);
6009            }
6010        }
6011        /*
6012         * Make sure the expanded scanned set contains all signatures in the
6013         * existing one.
6014         */
6015        if (scannedCompatSet.equals(existingSet)) {
6016            // Migrate the old signatures to the new scheme.
6017            existingSigs.assignSignatures(scannedPkg.mSignatures);
6018            // The new KeySets will be re-added later in the scanning process.
6019            synchronized (mPackages) {
6020                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6021            }
6022            return PackageManager.SIGNATURE_MATCH;
6023        }
6024        return PackageManager.SIGNATURE_NO_MATCH;
6025    }
6026
6027    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6028        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6029        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6030    }
6031
6032    private int compareSignaturesRecover(PackageSignatures existingSigs,
6033            PackageParser.Package scannedPkg) {
6034        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6035            return PackageManager.SIGNATURE_NO_MATCH;
6036        }
6037
6038        String msg = null;
6039        try {
6040            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6041                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6042                        + scannedPkg.packageName);
6043                return PackageManager.SIGNATURE_MATCH;
6044            }
6045        } catch (CertificateException e) {
6046            msg = e.getMessage();
6047        }
6048
6049        logCriticalInfo(Log.INFO,
6050                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6051        return PackageManager.SIGNATURE_NO_MATCH;
6052    }
6053
6054    @Override
6055    public List<String> getAllPackages() {
6056        final int callingUid = Binder.getCallingUid();
6057        final int callingUserId = UserHandle.getUserId(callingUid);
6058        synchronized (mPackages) {
6059            if (canViewInstantApps(callingUid, callingUserId)) {
6060                return new ArrayList<String>(mPackages.keySet());
6061            }
6062            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6063            final List<String> result = new ArrayList<>();
6064            if (instantAppPkgName != null) {
6065                // caller is an instant application; filter unexposed applications
6066                for (PackageParser.Package pkg : mPackages.values()) {
6067                    if (!pkg.visibleToInstantApps) {
6068                        continue;
6069                    }
6070                    result.add(pkg.packageName);
6071                }
6072            } else {
6073                // caller is a normal application; filter instant applications
6074                for (PackageParser.Package pkg : mPackages.values()) {
6075                    final PackageSetting ps =
6076                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6077                    if (ps != null
6078                            && ps.getInstantApp(callingUserId)
6079                            && !mInstantAppRegistry.isInstantAccessGranted(
6080                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6081                        continue;
6082                    }
6083                    result.add(pkg.packageName);
6084                }
6085            }
6086            return result;
6087        }
6088    }
6089
6090    @Override
6091    public String[] getPackagesForUid(int uid) {
6092        final int callingUid = Binder.getCallingUid();
6093        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6094        final int userId = UserHandle.getUserId(uid);
6095        uid = UserHandle.getAppId(uid);
6096        // reader
6097        synchronized (mPackages) {
6098            Object obj = mSettings.getUserIdLPr(uid);
6099            if (obj instanceof SharedUserSetting) {
6100                if (isCallerInstantApp) {
6101                    return null;
6102                }
6103                final SharedUserSetting sus = (SharedUserSetting) obj;
6104                final int N = sus.packages.size();
6105                String[] res = new String[N];
6106                final Iterator<PackageSetting> it = sus.packages.iterator();
6107                int i = 0;
6108                while (it.hasNext()) {
6109                    PackageSetting ps = it.next();
6110                    if (ps.getInstalled(userId)) {
6111                        res[i++] = ps.name;
6112                    } else {
6113                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6114                    }
6115                }
6116                return res;
6117            } else if (obj instanceof PackageSetting) {
6118                final PackageSetting ps = (PackageSetting) obj;
6119                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6120                    return new String[]{ps.name};
6121                }
6122            }
6123        }
6124        return null;
6125    }
6126
6127    @Override
6128    public String getNameForUid(int uid) {
6129        final int callingUid = Binder.getCallingUid();
6130        if (getInstantAppPackageName(callingUid) != null) {
6131            return null;
6132        }
6133        synchronized (mPackages) {
6134            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6135            if (obj instanceof SharedUserSetting) {
6136                final SharedUserSetting sus = (SharedUserSetting) obj;
6137                return sus.name + ":" + sus.userId;
6138            } else if (obj instanceof PackageSetting) {
6139                final PackageSetting ps = (PackageSetting) obj;
6140                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6141                    return null;
6142                }
6143                return ps.name;
6144            }
6145        }
6146        return null;
6147    }
6148
6149    @Override
6150    public int getUidForSharedUser(String sharedUserName) {
6151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6152            return -1;
6153        }
6154        if (sharedUserName == null) {
6155            return -1;
6156        }
6157        // reader
6158        synchronized (mPackages) {
6159            SharedUserSetting suid;
6160            try {
6161                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6162                if (suid != null) {
6163                    return suid.userId;
6164                }
6165            } catch (PackageManagerException ignore) {
6166                // can't happen, but, still need to catch it
6167            }
6168            return -1;
6169        }
6170    }
6171
6172    @Override
6173    public int getFlagsForUid(int uid) {
6174        final int callingUid = Binder.getCallingUid();
6175        if (getInstantAppPackageName(callingUid) != null) {
6176            return 0;
6177        }
6178        synchronized (mPackages) {
6179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6180            if (obj instanceof SharedUserSetting) {
6181                final SharedUserSetting sus = (SharedUserSetting) obj;
6182                return sus.pkgFlags;
6183            } else if (obj instanceof PackageSetting) {
6184                final PackageSetting ps = (PackageSetting) obj;
6185                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6186                    return 0;
6187                }
6188                return ps.pkgFlags;
6189            }
6190        }
6191        return 0;
6192    }
6193
6194    @Override
6195    public int getPrivateFlagsForUid(int uid) {
6196        final int callingUid = Binder.getCallingUid();
6197        if (getInstantAppPackageName(callingUid) != null) {
6198            return 0;
6199        }
6200        synchronized (mPackages) {
6201            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6202            if (obj instanceof SharedUserSetting) {
6203                final SharedUserSetting sus = (SharedUserSetting) obj;
6204                return sus.pkgPrivateFlags;
6205            } else if (obj instanceof PackageSetting) {
6206                final PackageSetting ps = (PackageSetting) obj;
6207                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6208                    return 0;
6209                }
6210                return ps.pkgPrivateFlags;
6211            }
6212        }
6213        return 0;
6214    }
6215
6216    @Override
6217    public boolean isUidPrivileged(int uid) {
6218        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6219            return false;
6220        }
6221        uid = UserHandle.getAppId(uid);
6222        // reader
6223        synchronized (mPackages) {
6224            Object obj = mSettings.getUserIdLPr(uid);
6225            if (obj instanceof SharedUserSetting) {
6226                final SharedUserSetting sus = (SharedUserSetting) obj;
6227                final Iterator<PackageSetting> it = sus.packages.iterator();
6228                while (it.hasNext()) {
6229                    if (it.next().isPrivileged()) {
6230                        return true;
6231                    }
6232                }
6233            } else if (obj instanceof PackageSetting) {
6234                final PackageSetting ps = (PackageSetting) obj;
6235                return ps.isPrivileged();
6236            }
6237        }
6238        return false;
6239    }
6240
6241    @Override
6242    public String[] getAppOpPermissionPackages(String permissionName) {
6243        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6244            return null;
6245        }
6246        synchronized (mPackages) {
6247            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6248            if (pkgs == null) {
6249                return null;
6250            }
6251            return pkgs.toArray(new String[pkgs.size()]);
6252        }
6253    }
6254
6255    @Override
6256    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6257            int flags, int userId) {
6258        return resolveIntentInternal(
6259                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6260    }
6261
6262    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6263            int flags, int userId, boolean resolveForStart) {
6264        try {
6265            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6266
6267            if (!sUserManager.exists(userId)) return null;
6268            final int callingUid = Binder.getCallingUid();
6269            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6270            enforceCrossUserPermission(callingUid, userId,
6271                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6272
6273            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6274            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6275                    flags, callingUid, userId, resolveForStart);
6276            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6277
6278            final ResolveInfo bestChoice =
6279                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6280            return bestChoice;
6281        } finally {
6282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6283        }
6284    }
6285
6286    @Override
6287    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6288        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6289            throw new SecurityException(
6290                    "findPersistentPreferredActivity can only be run by the system");
6291        }
6292        if (!sUserManager.exists(userId)) {
6293            return null;
6294        }
6295        final int callingUid = Binder.getCallingUid();
6296        intent = updateIntentForResolve(intent);
6297        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6298        final int flags = updateFlagsForResolve(
6299                0, userId, intent, callingUid, false /*includeInstantApps*/);
6300        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6301                userId);
6302        synchronized (mPackages) {
6303            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6304                    userId);
6305        }
6306    }
6307
6308    @Override
6309    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6310            IntentFilter filter, int match, ComponentName activity) {
6311        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6312            return;
6313        }
6314        final int userId = UserHandle.getCallingUserId();
6315        if (DEBUG_PREFERRED) {
6316            Log.v(TAG, "setLastChosenActivity intent=" + intent
6317                + " resolvedType=" + resolvedType
6318                + " flags=" + flags
6319                + " filter=" + filter
6320                + " match=" + match
6321                + " activity=" + activity);
6322            filter.dump(new PrintStreamPrinter(System.out), "    ");
6323        }
6324        intent.setComponent(null);
6325        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6326                userId);
6327        // Find any earlier preferred or last chosen entries and nuke them
6328        findPreferredActivity(intent, resolvedType,
6329                flags, query, 0, false, true, false, userId);
6330        // Add the new activity as the last chosen for this filter
6331        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6332                "Setting last chosen");
6333    }
6334
6335    @Override
6336    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6337        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6338            return null;
6339        }
6340        final int userId = UserHandle.getCallingUserId();
6341        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6342        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6343                userId);
6344        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6345                false, false, false, userId);
6346    }
6347
6348    /**
6349     * Returns whether or not instant apps have been disabled remotely.
6350     */
6351    private boolean isEphemeralDisabled() {
6352        return mEphemeralAppsDisabled;
6353    }
6354
6355    private boolean isInstantAppAllowed(
6356            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6357            boolean skipPackageCheck) {
6358        if (mInstantAppResolverConnection == null) {
6359            return false;
6360        }
6361        if (mInstantAppInstallerActivity == null) {
6362            return false;
6363        }
6364        if (intent.getComponent() != null) {
6365            return false;
6366        }
6367        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6368            return false;
6369        }
6370        if (!skipPackageCheck && intent.getPackage() != null) {
6371            return false;
6372        }
6373        final boolean isWebUri = hasWebURI(intent);
6374        if (!isWebUri || intent.getData().getHost() == null) {
6375            return false;
6376        }
6377        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6378        // Or if there's already an ephemeral app installed that handles the action
6379        synchronized (mPackages) {
6380            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6381            for (int n = 0; n < count; n++) {
6382                final ResolveInfo info = resolvedActivities.get(n);
6383                final String packageName = info.activityInfo.packageName;
6384                final PackageSetting ps = mSettings.mPackages.get(packageName);
6385                if (ps != null) {
6386                    // only check domain verification status if the app is not a browser
6387                    if (!info.handleAllWebDataURI) {
6388                        // Try to get the status from User settings first
6389                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6390                        final int status = (int) (packedStatus >> 32);
6391                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6392                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6393                            if (DEBUG_EPHEMERAL) {
6394                                Slog.v(TAG, "DENY instant app;"
6395                                    + " pkg: " + packageName + ", status: " + status);
6396                            }
6397                            return false;
6398                        }
6399                    }
6400                    if (ps.getInstantApp(userId)) {
6401                        if (DEBUG_EPHEMERAL) {
6402                            Slog.v(TAG, "DENY instant app installed;"
6403                                    + " pkg: " + packageName);
6404                        }
6405                        return false;
6406                    }
6407                }
6408            }
6409        }
6410        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6411        return true;
6412    }
6413
6414    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6415            Intent origIntent, String resolvedType, String callingPackage,
6416            Bundle verificationBundle, int userId) {
6417        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6418                new InstantAppRequest(responseObj, origIntent, resolvedType,
6419                        callingPackage, userId, verificationBundle));
6420        mHandler.sendMessage(msg);
6421    }
6422
6423    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6424            int flags, List<ResolveInfo> query, int userId) {
6425        if (query != null) {
6426            final int N = query.size();
6427            if (N == 1) {
6428                return query.get(0);
6429            } else if (N > 1) {
6430                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6431                // If there is more than one activity with the same priority,
6432                // then let the user decide between them.
6433                ResolveInfo r0 = query.get(0);
6434                ResolveInfo r1 = query.get(1);
6435                if (DEBUG_INTENT_MATCHING || debug) {
6436                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6437                            + r1.activityInfo.name + "=" + r1.priority);
6438                }
6439                // If the first activity has a higher priority, or a different
6440                // default, then it is always desirable to pick it.
6441                if (r0.priority != r1.priority
6442                        || r0.preferredOrder != r1.preferredOrder
6443                        || r0.isDefault != r1.isDefault) {
6444                    return query.get(0);
6445                }
6446                // If we have saved a preference for a preferred activity for
6447                // this Intent, use that.
6448                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6449                        flags, query, r0.priority, true, false, debug, userId);
6450                if (ri != null) {
6451                    return ri;
6452                }
6453                // If we have an ephemeral app, use it
6454                for (int i = 0; i < N; i++) {
6455                    ri = query.get(i);
6456                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6457                        final String packageName = ri.activityInfo.packageName;
6458                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6459                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6460                        final int status = (int)(packedStatus >> 32);
6461                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6462                            return ri;
6463                        }
6464                    }
6465                }
6466                ri = new ResolveInfo(mResolveInfo);
6467                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6468                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6469                // If all of the options come from the same package, show the application's
6470                // label and icon instead of the generic resolver's.
6471                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6472                // and then throw away the ResolveInfo itself, meaning that the caller loses
6473                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6474                // a fallback for this case; we only set the target package's resources on
6475                // the ResolveInfo, not the ActivityInfo.
6476                final String intentPackage = intent.getPackage();
6477                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6478                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6479                    ri.resolvePackageName = intentPackage;
6480                    if (userNeedsBadging(userId)) {
6481                        ri.noResourceId = true;
6482                    } else {
6483                        ri.icon = appi.icon;
6484                    }
6485                    ri.iconResourceId = appi.icon;
6486                    ri.labelRes = appi.labelRes;
6487                }
6488                ri.activityInfo.applicationInfo = new ApplicationInfo(
6489                        ri.activityInfo.applicationInfo);
6490                if (userId != 0) {
6491                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6492                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6493                }
6494                // Make sure that the resolver is displayable in car mode
6495                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6496                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6497                return ri;
6498            }
6499        }
6500        return null;
6501    }
6502
6503    /**
6504     * Return true if the given list is not empty and all of its contents have
6505     * an activityInfo with the given package name.
6506     */
6507    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6508        if (ArrayUtils.isEmpty(list)) {
6509            return false;
6510        }
6511        for (int i = 0, N = list.size(); i < N; i++) {
6512            final ResolveInfo ri = list.get(i);
6513            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6514            if (ai == null || !packageName.equals(ai.packageName)) {
6515                return false;
6516            }
6517        }
6518        return true;
6519    }
6520
6521    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6522            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6523        final int N = query.size();
6524        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6525                .get(userId);
6526        // Get the list of persistent preferred activities that handle the intent
6527        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6528        List<PersistentPreferredActivity> pprefs = ppir != null
6529                ? ppir.queryIntent(intent, resolvedType,
6530                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6531                        userId)
6532                : null;
6533        if (pprefs != null && pprefs.size() > 0) {
6534            final int M = pprefs.size();
6535            for (int i=0; i<M; i++) {
6536                final PersistentPreferredActivity ppa = pprefs.get(i);
6537                if (DEBUG_PREFERRED || debug) {
6538                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6539                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6540                            + "\n  component=" + ppa.mComponent);
6541                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6542                }
6543                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6544                        flags | MATCH_DISABLED_COMPONENTS, userId);
6545                if (DEBUG_PREFERRED || debug) {
6546                    Slog.v(TAG, "Found persistent preferred activity:");
6547                    if (ai != null) {
6548                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6549                    } else {
6550                        Slog.v(TAG, "  null");
6551                    }
6552                }
6553                if (ai == null) {
6554                    // This previously registered persistent preferred activity
6555                    // component is no longer known. Ignore it and do NOT remove it.
6556                    continue;
6557                }
6558                for (int j=0; j<N; j++) {
6559                    final ResolveInfo ri = query.get(j);
6560                    if (!ri.activityInfo.applicationInfo.packageName
6561                            .equals(ai.applicationInfo.packageName)) {
6562                        continue;
6563                    }
6564                    if (!ri.activityInfo.name.equals(ai.name)) {
6565                        continue;
6566                    }
6567                    //  Found a persistent preference that can handle the intent.
6568                    if (DEBUG_PREFERRED || debug) {
6569                        Slog.v(TAG, "Returning persistent preferred activity: " +
6570                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6571                    }
6572                    return ri;
6573                }
6574            }
6575        }
6576        return null;
6577    }
6578
6579    // TODO: handle preferred activities missing while user has amnesia
6580    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6581            List<ResolveInfo> query, int priority, boolean always,
6582            boolean removeMatches, boolean debug, int userId) {
6583        if (!sUserManager.exists(userId)) return null;
6584        final int callingUid = Binder.getCallingUid();
6585        flags = updateFlagsForResolve(
6586                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6587        intent = updateIntentForResolve(intent);
6588        // writer
6589        synchronized (mPackages) {
6590            // Try to find a matching persistent preferred activity.
6591            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6592                    debug, userId);
6593
6594            // If a persistent preferred activity matched, use it.
6595            if (pri != null) {
6596                return pri;
6597            }
6598
6599            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6600            // Get the list of preferred activities that handle the intent
6601            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6602            List<PreferredActivity> prefs = pir != null
6603                    ? pir.queryIntent(intent, resolvedType,
6604                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6605                            userId)
6606                    : null;
6607            if (prefs != null && prefs.size() > 0) {
6608                boolean changed = false;
6609                try {
6610                    // First figure out how good the original match set is.
6611                    // We will only allow preferred activities that came
6612                    // from the same match quality.
6613                    int match = 0;
6614
6615                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6616
6617                    final int N = query.size();
6618                    for (int j=0; j<N; j++) {
6619                        final ResolveInfo ri = query.get(j);
6620                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6621                                + ": 0x" + Integer.toHexString(match));
6622                        if (ri.match > match) {
6623                            match = ri.match;
6624                        }
6625                    }
6626
6627                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6628                            + Integer.toHexString(match));
6629
6630                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6631                    final int M = prefs.size();
6632                    for (int i=0; i<M; i++) {
6633                        final PreferredActivity pa = prefs.get(i);
6634                        if (DEBUG_PREFERRED || debug) {
6635                            Slog.v(TAG, "Checking PreferredActivity ds="
6636                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6637                                    + "\n  component=" + pa.mPref.mComponent);
6638                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6639                        }
6640                        if (pa.mPref.mMatch != match) {
6641                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6642                                    + Integer.toHexString(pa.mPref.mMatch));
6643                            continue;
6644                        }
6645                        // If it's not an "always" type preferred activity and that's what we're
6646                        // looking for, skip it.
6647                        if (always && !pa.mPref.mAlways) {
6648                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6649                            continue;
6650                        }
6651                        final ActivityInfo ai = getActivityInfo(
6652                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6653                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6654                                userId);
6655                        if (DEBUG_PREFERRED || debug) {
6656                            Slog.v(TAG, "Found preferred activity:");
6657                            if (ai != null) {
6658                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6659                            } else {
6660                                Slog.v(TAG, "  null");
6661                            }
6662                        }
6663                        if (ai == null) {
6664                            // This previously registered preferred activity
6665                            // component is no longer known.  Most likely an update
6666                            // to the app was installed and in the new version this
6667                            // component no longer exists.  Clean it up by removing
6668                            // it from the preferred activities list, and skip it.
6669                            Slog.w(TAG, "Removing dangling preferred activity: "
6670                                    + pa.mPref.mComponent);
6671                            pir.removeFilter(pa);
6672                            changed = true;
6673                            continue;
6674                        }
6675                        for (int j=0; j<N; j++) {
6676                            final ResolveInfo ri = query.get(j);
6677                            if (!ri.activityInfo.applicationInfo.packageName
6678                                    .equals(ai.applicationInfo.packageName)) {
6679                                continue;
6680                            }
6681                            if (!ri.activityInfo.name.equals(ai.name)) {
6682                                continue;
6683                            }
6684
6685                            if (removeMatches) {
6686                                pir.removeFilter(pa);
6687                                changed = true;
6688                                if (DEBUG_PREFERRED) {
6689                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6690                                }
6691                                break;
6692                            }
6693
6694                            // Okay we found a previously set preferred or last chosen app.
6695                            // If the result set is different from when this
6696                            // was created, we need to clear it and re-ask the
6697                            // user their preference, if we're looking for an "always" type entry.
6698                            if (always && !pa.mPref.sameSet(query)) {
6699                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6700                                        + intent + " type " + resolvedType);
6701                                if (DEBUG_PREFERRED) {
6702                                    Slog.v(TAG, "Removing preferred activity since set changed "
6703                                            + pa.mPref.mComponent);
6704                                }
6705                                pir.removeFilter(pa);
6706                                // Re-add the filter as a "last chosen" entry (!always)
6707                                PreferredActivity lastChosen = new PreferredActivity(
6708                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6709                                pir.addFilter(lastChosen);
6710                                changed = true;
6711                                return null;
6712                            }
6713
6714                            // Yay! Either the set matched or we're looking for the last chosen
6715                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6716                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6717                            return ri;
6718                        }
6719                    }
6720                } finally {
6721                    if (changed) {
6722                        if (DEBUG_PREFERRED) {
6723                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6724                        }
6725                        scheduleWritePackageRestrictionsLocked(userId);
6726                    }
6727                }
6728            }
6729        }
6730        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6731        return null;
6732    }
6733
6734    /*
6735     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6736     */
6737    @Override
6738    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6739            int targetUserId) {
6740        mContext.enforceCallingOrSelfPermission(
6741                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6742        List<CrossProfileIntentFilter> matches =
6743                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6744        if (matches != null) {
6745            int size = matches.size();
6746            for (int i = 0; i < size; i++) {
6747                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6748            }
6749        }
6750        if (hasWebURI(intent)) {
6751            // cross-profile app linking works only towards the parent.
6752            final int callingUid = Binder.getCallingUid();
6753            final UserInfo parent = getProfileParent(sourceUserId);
6754            synchronized(mPackages) {
6755                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6756                        false /*includeInstantApps*/);
6757                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6758                        intent, resolvedType, flags, sourceUserId, parent.id);
6759                return xpDomainInfo != null;
6760            }
6761        }
6762        return false;
6763    }
6764
6765    private UserInfo getProfileParent(int userId) {
6766        final long identity = Binder.clearCallingIdentity();
6767        try {
6768            return sUserManager.getProfileParent(userId);
6769        } finally {
6770            Binder.restoreCallingIdentity(identity);
6771        }
6772    }
6773
6774    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6775            String resolvedType, int userId) {
6776        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6777        if (resolver != null) {
6778            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6779        }
6780        return null;
6781    }
6782
6783    @Override
6784    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        try {
6787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6788
6789            return new ParceledListSlice<>(
6790                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6791        } finally {
6792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6793        }
6794    }
6795
6796    /**
6797     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6798     * instant, returns {@code null}.
6799     */
6800    private String getInstantAppPackageName(int callingUid) {
6801        synchronized (mPackages) {
6802            // If the caller is an isolated app use the owner's uid for the lookup.
6803            if (Process.isIsolated(callingUid)) {
6804                callingUid = mIsolatedOwners.get(callingUid);
6805            }
6806            final int appId = UserHandle.getAppId(callingUid);
6807            final Object obj = mSettings.getUserIdLPr(appId);
6808            if (obj instanceof PackageSetting) {
6809                final PackageSetting ps = (PackageSetting) obj;
6810                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6811                return isInstantApp ? ps.pkg.packageName : null;
6812            }
6813        }
6814        return null;
6815    }
6816
6817    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6818            String resolvedType, int flags, int userId) {
6819        return queryIntentActivitiesInternal(
6820                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6821    }
6822
6823    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6824            String resolvedType, int flags, int filterCallingUid, int userId,
6825            boolean resolveForStart) {
6826        if (!sUserManager.exists(userId)) return Collections.emptyList();
6827        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6828        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6829                false /* requireFullPermission */, false /* checkShell */,
6830                "query intent activities");
6831        final String pkgName = intent.getPackage();
6832        ComponentName comp = intent.getComponent();
6833        if (comp == null) {
6834            if (intent.getSelector() != null) {
6835                intent = intent.getSelector();
6836                comp = intent.getComponent();
6837            }
6838        }
6839
6840        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6841                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6842        if (comp != null) {
6843            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6844            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6845            if (ai != null) {
6846                // When specifying an explicit component, we prevent the activity from being
6847                // used when either 1) the calling package is normal and the activity is within
6848                // an ephemeral application or 2) the calling package is ephemeral and the
6849                // activity is not visible to ephemeral applications.
6850                final boolean matchInstantApp =
6851                        (flags & PackageManager.MATCH_INSTANT) != 0;
6852                final boolean matchVisibleToInstantAppOnly =
6853                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6854                final boolean matchExplicitlyVisibleOnly =
6855                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6856                final boolean isCallerInstantApp =
6857                        instantAppPkgName != null;
6858                final boolean isTargetSameInstantApp =
6859                        comp.getPackageName().equals(instantAppPkgName);
6860                final boolean isTargetInstantApp =
6861                        (ai.applicationInfo.privateFlags
6862                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6863                final boolean isTargetVisibleToInstantApp =
6864                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6865                final boolean isTargetExplicitlyVisibleToInstantApp =
6866                        isTargetVisibleToInstantApp
6867                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6868                final boolean isTargetHiddenFromInstantApp =
6869                        !isTargetVisibleToInstantApp
6870                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6871                final boolean blockResolution =
6872                        !isTargetSameInstantApp
6873                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6874                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6875                                        && isTargetHiddenFromInstantApp));
6876                if (!blockResolution) {
6877                    final ResolveInfo ri = new ResolveInfo();
6878                    ri.activityInfo = ai;
6879                    list.add(ri);
6880                }
6881            }
6882            return applyPostResolutionFilter(list, instantAppPkgName);
6883        }
6884
6885        // reader
6886        boolean sortResult = false;
6887        boolean addEphemeral = false;
6888        List<ResolveInfo> result;
6889        final boolean ephemeralDisabled = isEphemeralDisabled();
6890        synchronized (mPackages) {
6891            if (pkgName == null) {
6892                List<CrossProfileIntentFilter> matchingFilters =
6893                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6894                // Check for results that need to skip the current profile.
6895                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6896                        resolvedType, flags, userId);
6897                if (xpResolveInfo != null) {
6898                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6899                    xpResult.add(xpResolveInfo);
6900                    return applyPostResolutionFilter(
6901                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6902                }
6903
6904                // Check for results in the current profile.
6905                result = filterIfNotSystemUser(mActivities.queryIntent(
6906                        intent, resolvedType, flags, userId), userId);
6907                addEphemeral = !ephemeralDisabled
6908                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6909                // Check for cross profile results.
6910                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6911                xpResolveInfo = queryCrossProfileIntents(
6912                        matchingFilters, intent, resolvedType, flags, userId,
6913                        hasNonNegativePriorityResult);
6914                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6915                    boolean isVisibleToUser = filterIfNotSystemUser(
6916                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6917                    if (isVisibleToUser) {
6918                        result.add(xpResolveInfo);
6919                        sortResult = true;
6920                    }
6921                }
6922                if (hasWebURI(intent)) {
6923                    CrossProfileDomainInfo xpDomainInfo = null;
6924                    final UserInfo parent = getProfileParent(userId);
6925                    if (parent != null) {
6926                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6927                                flags, userId, parent.id);
6928                    }
6929                    if (xpDomainInfo != null) {
6930                        if (xpResolveInfo != null) {
6931                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6932                            // in the result.
6933                            result.remove(xpResolveInfo);
6934                        }
6935                        if (result.size() == 0 && !addEphemeral) {
6936                            // No result in current profile, but found candidate in parent user.
6937                            // And we are not going to add emphemeral app, so we can return the
6938                            // result straight away.
6939                            result.add(xpDomainInfo.resolveInfo);
6940                            return applyPostResolutionFilter(result, instantAppPkgName);
6941                        }
6942                    } else if (result.size() <= 1 && !addEphemeral) {
6943                        // No result in parent user and <= 1 result in current profile, and we
6944                        // are not going to add emphemeral app, so we can return the result without
6945                        // further processing.
6946                        return applyPostResolutionFilter(result, instantAppPkgName);
6947                    }
6948                    // We have more than one candidate (combining results from current and parent
6949                    // profile), so we need filtering and sorting.
6950                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6951                            intent, flags, result, xpDomainInfo, userId);
6952                    sortResult = true;
6953                }
6954            } else {
6955                final PackageParser.Package pkg = mPackages.get(pkgName);
6956                result = null;
6957                if (pkg != null) {
6958                    result = filterIfNotSystemUser(
6959                            mActivities.queryIntentForPackage(
6960                                    intent, resolvedType, flags, pkg.activities, userId),
6961                            userId);
6962                }
6963                if (result == null || result.size() == 0) {
6964                    // the caller wants to resolve for a particular package; however, there
6965                    // were no installed results, so, try to find an ephemeral result
6966                    addEphemeral = !ephemeralDisabled
6967                            && isInstantAppAllowed(
6968                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6969                    if (result == null) {
6970                        result = new ArrayList<>();
6971                    }
6972                }
6973            }
6974        }
6975        if (addEphemeral) {
6976            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6977        }
6978        if (sortResult) {
6979            Collections.sort(result, mResolvePrioritySorter);
6980        }
6981        return applyPostResolutionFilter(result, instantAppPkgName);
6982    }
6983
6984    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6985            String resolvedType, int flags, int userId) {
6986        // first, check to see if we've got an instant app already installed
6987        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6988        ResolveInfo localInstantApp = null;
6989        boolean blockResolution = false;
6990        if (!alreadyResolvedLocally) {
6991            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6992                    flags
6993                        | PackageManager.GET_RESOLVED_FILTER
6994                        | PackageManager.MATCH_INSTANT
6995                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6996                    userId);
6997            for (int i = instantApps.size() - 1; i >= 0; --i) {
6998                final ResolveInfo info = instantApps.get(i);
6999                final String packageName = info.activityInfo.packageName;
7000                final PackageSetting ps = mSettings.mPackages.get(packageName);
7001                if (ps.getInstantApp(userId)) {
7002                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7003                    final int status = (int)(packedStatus >> 32);
7004                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7005                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7006                        // there's a local instant application installed, but, the user has
7007                        // chosen to never use it; skip resolution and don't acknowledge
7008                        // an instant application is even available
7009                        if (DEBUG_EPHEMERAL) {
7010                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7011                        }
7012                        blockResolution = true;
7013                        break;
7014                    } else {
7015                        // we have a locally installed instant application; skip resolution
7016                        // but acknowledge there's an instant application available
7017                        if (DEBUG_EPHEMERAL) {
7018                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7019                        }
7020                        localInstantApp = info;
7021                        break;
7022                    }
7023                }
7024            }
7025        }
7026        // no app installed, let's see if one's available
7027        AuxiliaryResolveInfo auxiliaryResponse = null;
7028        if (!blockResolution) {
7029            if (localInstantApp == null) {
7030                // we don't have an instant app locally, resolve externally
7031                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7032                final InstantAppRequest requestObject = new InstantAppRequest(
7033                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7034                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7035                auxiliaryResponse =
7036                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7037                                mContext, mInstantAppResolverConnection, requestObject);
7038                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7039            } else {
7040                // we have an instant application locally, but, we can't admit that since
7041                // callers shouldn't be able to determine prior browsing. create a dummy
7042                // auxiliary response so the downstream code behaves as if there's an
7043                // instant application available externally. when it comes time to start
7044                // the instant application, we'll do the right thing.
7045                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7046                auxiliaryResponse = new AuxiliaryResolveInfo(
7047                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7048            }
7049        }
7050        if (auxiliaryResponse != null) {
7051            if (DEBUG_EPHEMERAL) {
7052                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7053            }
7054            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7055            final PackageSetting ps =
7056                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7057            if (ps != null) {
7058                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7059                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7060                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7061                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7062                // make sure this resolver is the default
7063                ephemeralInstaller.isDefault = true;
7064                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7065                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7066                // add a non-generic filter
7067                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7068                ephemeralInstaller.filter.addDataPath(
7069                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7070                ephemeralInstaller.isInstantAppAvailable = true;
7071                result.add(ephemeralInstaller);
7072            }
7073        }
7074        return result;
7075    }
7076
7077    private static class CrossProfileDomainInfo {
7078        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7079        ResolveInfo resolveInfo;
7080        /* Best domain verification status of the activities found in the other profile */
7081        int bestDomainVerificationStatus;
7082    }
7083
7084    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7085            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7086        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7087                sourceUserId)) {
7088            return null;
7089        }
7090        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7091                resolvedType, flags, parentUserId);
7092
7093        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7094            return null;
7095        }
7096        CrossProfileDomainInfo result = null;
7097        int size = resultTargetUser.size();
7098        for (int i = 0; i < size; i++) {
7099            ResolveInfo riTargetUser = resultTargetUser.get(i);
7100            // Intent filter verification is only for filters that specify a host. So don't return
7101            // those that handle all web uris.
7102            if (riTargetUser.handleAllWebDataURI) {
7103                continue;
7104            }
7105            String packageName = riTargetUser.activityInfo.packageName;
7106            PackageSetting ps = mSettings.mPackages.get(packageName);
7107            if (ps == null) {
7108                continue;
7109            }
7110            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7111            int status = (int)(verificationState >> 32);
7112            if (result == null) {
7113                result = new CrossProfileDomainInfo();
7114                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7115                        sourceUserId, parentUserId);
7116                result.bestDomainVerificationStatus = status;
7117            } else {
7118                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7119                        result.bestDomainVerificationStatus);
7120            }
7121        }
7122        // Don't consider matches with status NEVER across profiles.
7123        if (result != null && result.bestDomainVerificationStatus
7124                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7125            return null;
7126        }
7127        return result;
7128    }
7129
7130    /**
7131     * Verification statuses are ordered from the worse to the best, except for
7132     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7133     */
7134    private int bestDomainVerificationStatus(int status1, int status2) {
7135        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7136            return status2;
7137        }
7138        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7139            return status1;
7140        }
7141        return (int) MathUtils.max(status1, status2);
7142    }
7143
7144    private boolean isUserEnabled(int userId) {
7145        long callingId = Binder.clearCallingIdentity();
7146        try {
7147            UserInfo userInfo = sUserManager.getUserInfo(userId);
7148            return userInfo != null && userInfo.isEnabled();
7149        } finally {
7150            Binder.restoreCallingIdentity(callingId);
7151        }
7152    }
7153
7154    /**
7155     * Filter out activities with systemUserOnly flag set, when current user is not System.
7156     *
7157     * @return filtered list
7158     */
7159    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7160        if (userId == UserHandle.USER_SYSTEM) {
7161            return resolveInfos;
7162        }
7163        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7164            ResolveInfo info = resolveInfos.get(i);
7165            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7166                resolveInfos.remove(i);
7167            }
7168        }
7169        return resolveInfos;
7170    }
7171
7172    /**
7173     * Filters out ephemeral activities.
7174     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7175     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7176     *
7177     * @param resolveInfos The pre-filtered list of resolved activities
7178     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7179     *          is performed.
7180     * @return A filtered list of resolved activities.
7181     */
7182    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7183            String ephemeralPkgName) {
7184        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7185            final ResolveInfo info = resolveInfos.get(i);
7186            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7187            // TODO: When adding on-demand split support for non-instant apps, remove this check
7188            // and always apply post filtering
7189            // allow activities that are defined in the provided package
7190            if (isEphemeralApp) {
7191                if (info.activityInfo.splitName != null
7192                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7193                                info.activityInfo.splitName)) {
7194                    // requested activity is defined in a split that hasn't been installed yet.
7195                    // add the installer to the resolve list
7196                    if (DEBUG_EPHEMERAL) {
7197                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7198                    }
7199                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7200                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7201                            info.activityInfo.packageName, info.activityInfo.splitName,
7202                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7203                    // make sure this resolver is the default
7204                    installerInfo.isDefault = true;
7205                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7206                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7207                    // add a non-generic filter
7208                    installerInfo.filter = new IntentFilter();
7209                    // load resources from the correct package
7210                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7211                    resolveInfos.set(i, installerInfo);
7212                    continue;
7213                }
7214            }
7215            // caller is a full app, don't need to apply any other filtering
7216            if (ephemeralPkgName == null) {
7217                continue;
7218            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7219                // caller is same app; don't need to apply any other filtering
7220                continue;
7221            }
7222            // allow activities that have been explicitly exposed to ephemeral apps
7223            if (!isEphemeralApp
7224                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7225                continue;
7226            }
7227            resolveInfos.remove(i);
7228        }
7229        return resolveInfos;
7230    }
7231
7232    /**
7233     * @param resolveInfos list of resolve infos in descending priority order
7234     * @return if the list contains a resolve info with non-negative priority
7235     */
7236    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7237        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7238    }
7239
7240    private static boolean hasWebURI(Intent intent) {
7241        if (intent.getData() == null) {
7242            return false;
7243        }
7244        final String scheme = intent.getScheme();
7245        if (TextUtils.isEmpty(scheme)) {
7246            return false;
7247        }
7248        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7249    }
7250
7251    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7252            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7253            int userId) {
7254        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7255
7256        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7257            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7258                    candidates.size());
7259        }
7260
7261        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7265        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7266        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7267
7268        synchronized (mPackages) {
7269            final int count = candidates.size();
7270            // First, try to use linked apps. Partition the candidates into four lists:
7271            // one for the final results, one for the "do not use ever", one for "undefined status"
7272            // and finally one for "browser app type".
7273            for (int n=0; n<count; n++) {
7274                ResolveInfo info = candidates.get(n);
7275                String packageName = info.activityInfo.packageName;
7276                PackageSetting ps = mSettings.mPackages.get(packageName);
7277                if (ps != null) {
7278                    // Add to the special match all list (Browser use case)
7279                    if (info.handleAllWebDataURI) {
7280                        matchAllList.add(info);
7281                        continue;
7282                    }
7283                    // Try to get the status from User settings first
7284                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7285                    int status = (int)(packedStatus >> 32);
7286                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7287                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7288                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7289                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7290                                    + " : linkgen=" + linkGeneration);
7291                        }
7292                        // Use link-enabled generation as preferredOrder, i.e.
7293                        // prefer newly-enabled over earlier-enabled.
7294                        info.preferredOrder = linkGeneration;
7295                        alwaysList.add(info);
7296                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7297                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7298                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7299                        }
7300                        neverList.add(info);
7301                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7302                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7303                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7304                        }
7305                        alwaysAskList.add(info);
7306                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7307                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7308                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7309                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7310                        }
7311                        undefinedList.add(info);
7312                    }
7313                }
7314            }
7315
7316            // We'll want to include browser possibilities in a few cases
7317            boolean includeBrowser = false;
7318
7319            // First try to add the "always" resolution(s) for the current user, if any
7320            if (alwaysList.size() > 0) {
7321                result.addAll(alwaysList);
7322            } else {
7323                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7324                result.addAll(undefinedList);
7325                // Maybe add one for the other profile.
7326                if (xpDomainInfo != null && (
7327                        xpDomainInfo.bestDomainVerificationStatus
7328                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7329                    result.add(xpDomainInfo.resolveInfo);
7330                }
7331                includeBrowser = true;
7332            }
7333
7334            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7335            // If there were 'always' entries their preferred order has been set, so we also
7336            // back that off to make the alternatives equivalent
7337            if (alwaysAskList.size() > 0) {
7338                for (ResolveInfo i : result) {
7339                    i.preferredOrder = 0;
7340                }
7341                result.addAll(alwaysAskList);
7342                includeBrowser = true;
7343            }
7344
7345            if (includeBrowser) {
7346                // Also add browsers (all of them or only the default one)
7347                if (DEBUG_DOMAIN_VERIFICATION) {
7348                    Slog.v(TAG, "   ...including browsers in candidate set");
7349                }
7350                if ((matchFlags & MATCH_ALL) != 0) {
7351                    result.addAll(matchAllList);
7352                } else {
7353                    // Browser/generic handling case.  If there's a default browser, go straight
7354                    // to that (but only if there is no other higher-priority match).
7355                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7356                    int maxMatchPrio = 0;
7357                    ResolveInfo defaultBrowserMatch = null;
7358                    final int numCandidates = matchAllList.size();
7359                    for (int n = 0; n < numCandidates; n++) {
7360                        ResolveInfo info = matchAllList.get(n);
7361                        // track the highest overall match priority...
7362                        if (info.priority > maxMatchPrio) {
7363                            maxMatchPrio = info.priority;
7364                        }
7365                        // ...and the highest-priority default browser match
7366                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7367                            if (defaultBrowserMatch == null
7368                                    || (defaultBrowserMatch.priority < info.priority)) {
7369                                if (debug) {
7370                                    Slog.v(TAG, "Considering default browser match " + info);
7371                                }
7372                                defaultBrowserMatch = info;
7373                            }
7374                        }
7375                    }
7376                    if (defaultBrowserMatch != null
7377                            && defaultBrowserMatch.priority >= maxMatchPrio
7378                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7379                    {
7380                        if (debug) {
7381                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7382                        }
7383                        result.add(defaultBrowserMatch);
7384                    } else {
7385                        result.addAll(matchAllList);
7386                    }
7387                }
7388
7389                // If there is nothing selected, add all candidates and remove the ones that the user
7390                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7391                if (result.size() == 0) {
7392                    result.addAll(candidates);
7393                    result.removeAll(neverList);
7394                }
7395            }
7396        }
7397        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7398            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7399                    result.size());
7400            for (ResolveInfo info : result) {
7401                Slog.v(TAG, "  + " + info.activityInfo);
7402            }
7403        }
7404        return result;
7405    }
7406
7407    // Returns a packed value as a long:
7408    //
7409    // high 'int'-sized word: link status: undefined/ask/never/always.
7410    // low 'int'-sized word: relative priority among 'always' results.
7411    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7412        long result = ps.getDomainVerificationStatusForUser(userId);
7413        // if none available, get the master status
7414        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7415            if (ps.getIntentFilterVerificationInfo() != null) {
7416                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7417            }
7418        }
7419        return result;
7420    }
7421
7422    private ResolveInfo querySkipCurrentProfileIntents(
7423            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7424            int flags, int sourceUserId) {
7425        if (matchingFilters != null) {
7426            int size = matchingFilters.size();
7427            for (int i = 0; i < size; i ++) {
7428                CrossProfileIntentFilter filter = matchingFilters.get(i);
7429                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7430                    // Checking if there are activities in the target user that can handle the
7431                    // intent.
7432                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7433                            resolvedType, flags, sourceUserId);
7434                    if (resolveInfo != null) {
7435                        return resolveInfo;
7436                    }
7437                }
7438            }
7439        }
7440        return null;
7441    }
7442
7443    // Return matching ResolveInfo in target user if any.
7444    private ResolveInfo queryCrossProfileIntents(
7445            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7446            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7447        if (matchingFilters != null) {
7448            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7449            // match the same intent. For performance reasons, it is better not to
7450            // run queryIntent twice for the same userId
7451            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7452            int size = matchingFilters.size();
7453            for (int i = 0; i < size; i++) {
7454                CrossProfileIntentFilter filter = matchingFilters.get(i);
7455                int targetUserId = filter.getTargetUserId();
7456                boolean skipCurrentProfile =
7457                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7458                boolean skipCurrentProfileIfNoMatchFound =
7459                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7460                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7461                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7462                    // Checking if there are activities in the target user that can handle the
7463                    // intent.
7464                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7465                            resolvedType, flags, sourceUserId);
7466                    if (resolveInfo != null) return resolveInfo;
7467                    alreadyTriedUserIds.put(targetUserId, true);
7468                }
7469            }
7470        }
7471        return null;
7472    }
7473
7474    /**
7475     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7476     * will forward the intent to the filter's target user.
7477     * Otherwise, returns null.
7478     */
7479    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7480            String resolvedType, int flags, int sourceUserId) {
7481        int targetUserId = filter.getTargetUserId();
7482        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7483                resolvedType, flags, targetUserId);
7484        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7485            // If all the matches in the target profile are suspended, return null.
7486            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7487                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7488                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7489                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7490                            targetUserId);
7491                }
7492            }
7493        }
7494        return null;
7495    }
7496
7497    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7498            int sourceUserId, int targetUserId) {
7499        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7500        long ident = Binder.clearCallingIdentity();
7501        boolean targetIsProfile;
7502        try {
7503            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7504        } finally {
7505            Binder.restoreCallingIdentity(ident);
7506        }
7507        String className;
7508        if (targetIsProfile) {
7509            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7510        } else {
7511            className = FORWARD_INTENT_TO_PARENT;
7512        }
7513        ComponentName forwardingActivityComponentName = new ComponentName(
7514                mAndroidApplication.packageName, className);
7515        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7516                sourceUserId);
7517        if (!targetIsProfile) {
7518            forwardingActivityInfo.showUserIcon = targetUserId;
7519            forwardingResolveInfo.noResourceId = true;
7520        }
7521        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7522        forwardingResolveInfo.priority = 0;
7523        forwardingResolveInfo.preferredOrder = 0;
7524        forwardingResolveInfo.match = 0;
7525        forwardingResolveInfo.isDefault = true;
7526        forwardingResolveInfo.filter = filter;
7527        forwardingResolveInfo.targetUserId = targetUserId;
7528        return forwardingResolveInfo;
7529    }
7530
7531    @Override
7532    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7533            Intent[] specifics, String[] specificTypes, Intent intent,
7534            String resolvedType, int flags, int userId) {
7535        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7536                specificTypes, intent, resolvedType, flags, userId));
7537    }
7538
7539    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7540            Intent[] specifics, String[] specificTypes, Intent intent,
7541            String resolvedType, int flags, int userId) {
7542        if (!sUserManager.exists(userId)) return Collections.emptyList();
7543        final int callingUid = Binder.getCallingUid();
7544        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7545                false /*includeInstantApps*/);
7546        enforceCrossUserPermission(callingUid, userId,
7547                false /*requireFullPermission*/, false /*checkShell*/,
7548                "query intent activity options");
7549        final String resultsAction = intent.getAction();
7550
7551        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7552                | PackageManager.GET_RESOLVED_FILTER, userId);
7553
7554        if (DEBUG_INTENT_MATCHING) {
7555            Log.v(TAG, "Query " + intent + ": " + results);
7556        }
7557
7558        int specificsPos = 0;
7559        int N;
7560
7561        // todo: note that the algorithm used here is O(N^2).  This
7562        // isn't a problem in our current environment, but if we start running
7563        // into situations where we have more than 5 or 10 matches then this
7564        // should probably be changed to something smarter...
7565
7566        // First we go through and resolve each of the specific items
7567        // that were supplied, taking care of removing any corresponding
7568        // duplicate items in the generic resolve list.
7569        if (specifics != null) {
7570            for (int i=0; i<specifics.length; i++) {
7571                final Intent sintent = specifics[i];
7572                if (sintent == null) {
7573                    continue;
7574                }
7575
7576                if (DEBUG_INTENT_MATCHING) {
7577                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7578                }
7579
7580                String action = sintent.getAction();
7581                if (resultsAction != null && resultsAction.equals(action)) {
7582                    // If this action was explicitly requested, then don't
7583                    // remove things that have it.
7584                    action = null;
7585                }
7586
7587                ResolveInfo ri = null;
7588                ActivityInfo ai = null;
7589
7590                ComponentName comp = sintent.getComponent();
7591                if (comp == null) {
7592                    ri = resolveIntent(
7593                        sintent,
7594                        specificTypes != null ? specificTypes[i] : null,
7595                            flags, userId);
7596                    if (ri == null) {
7597                        continue;
7598                    }
7599                    if (ri == mResolveInfo) {
7600                        // ACK!  Must do something better with this.
7601                    }
7602                    ai = ri.activityInfo;
7603                    comp = new ComponentName(ai.applicationInfo.packageName,
7604                            ai.name);
7605                } else {
7606                    ai = getActivityInfo(comp, flags, userId);
7607                    if (ai == null) {
7608                        continue;
7609                    }
7610                }
7611
7612                // Look for any generic query activities that are duplicates
7613                // of this specific one, and remove them from the results.
7614                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7615                N = results.size();
7616                int j;
7617                for (j=specificsPos; j<N; j++) {
7618                    ResolveInfo sri = results.get(j);
7619                    if ((sri.activityInfo.name.equals(comp.getClassName())
7620                            && sri.activityInfo.applicationInfo.packageName.equals(
7621                                    comp.getPackageName()))
7622                        || (action != null && sri.filter.matchAction(action))) {
7623                        results.remove(j);
7624                        if (DEBUG_INTENT_MATCHING) Log.v(
7625                            TAG, "Removing duplicate item from " + j
7626                            + " due to specific " + specificsPos);
7627                        if (ri == null) {
7628                            ri = sri;
7629                        }
7630                        j--;
7631                        N--;
7632                    }
7633                }
7634
7635                // Add this specific item to its proper place.
7636                if (ri == null) {
7637                    ri = new ResolveInfo();
7638                    ri.activityInfo = ai;
7639                }
7640                results.add(specificsPos, ri);
7641                ri.specificIndex = i;
7642                specificsPos++;
7643            }
7644        }
7645
7646        // Now we go through the remaining generic results and remove any
7647        // duplicate actions that are found here.
7648        N = results.size();
7649        for (int i=specificsPos; i<N-1; i++) {
7650            final ResolveInfo rii = results.get(i);
7651            if (rii.filter == null) {
7652                continue;
7653            }
7654
7655            // Iterate over all of the actions of this result's intent
7656            // filter...  typically this should be just one.
7657            final Iterator<String> it = rii.filter.actionsIterator();
7658            if (it == null) {
7659                continue;
7660            }
7661            while (it.hasNext()) {
7662                final String action = it.next();
7663                if (resultsAction != null && resultsAction.equals(action)) {
7664                    // If this action was explicitly requested, then don't
7665                    // remove things that have it.
7666                    continue;
7667                }
7668                for (int j=i+1; j<N; j++) {
7669                    final ResolveInfo rij = results.get(j);
7670                    if (rij.filter != null && rij.filter.hasAction(action)) {
7671                        results.remove(j);
7672                        if (DEBUG_INTENT_MATCHING) Log.v(
7673                            TAG, "Removing duplicate item from " + j
7674                            + " due to action " + action + " at " + i);
7675                        j--;
7676                        N--;
7677                    }
7678                }
7679            }
7680
7681            // If the caller didn't request filter information, drop it now
7682            // so we don't have to marshall/unmarshall it.
7683            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7684                rii.filter = null;
7685            }
7686        }
7687
7688        // Filter out the caller activity if so requested.
7689        if (caller != null) {
7690            N = results.size();
7691            for (int i=0; i<N; i++) {
7692                ActivityInfo ainfo = results.get(i).activityInfo;
7693                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7694                        && caller.getClassName().equals(ainfo.name)) {
7695                    results.remove(i);
7696                    break;
7697                }
7698            }
7699        }
7700
7701        // If the caller didn't request filter information,
7702        // drop them now so we don't have to
7703        // marshall/unmarshall it.
7704        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7705            N = results.size();
7706            for (int i=0; i<N; i++) {
7707                results.get(i).filter = null;
7708            }
7709        }
7710
7711        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7712        return results;
7713    }
7714
7715    @Override
7716    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7717            String resolvedType, int flags, int userId) {
7718        return new ParceledListSlice<>(
7719                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7720    }
7721
7722    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7723            String resolvedType, int flags, int userId) {
7724        if (!sUserManager.exists(userId)) return Collections.emptyList();
7725        final int callingUid = Binder.getCallingUid();
7726        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7727        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7728                false /*includeInstantApps*/);
7729        ComponentName comp = intent.getComponent();
7730        if (comp == null) {
7731            if (intent.getSelector() != null) {
7732                intent = intent.getSelector();
7733                comp = intent.getComponent();
7734            }
7735        }
7736        if (comp != null) {
7737            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7738            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7739            if (ai != null) {
7740                // When specifying an explicit component, we prevent the activity from being
7741                // used when either 1) the calling package is normal and the activity is within
7742                // an instant application or 2) the calling package is ephemeral and the
7743                // activity is not visible to instant applications.
7744                final boolean matchInstantApp =
7745                        (flags & PackageManager.MATCH_INSTANT) != 0;
7746                final boolean matchVisibleToInstantAppOnly =
7747                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7748                final boolean matchExplicitlyVisibleOnly =
7749                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7750                final boolean isCallerInstantApp =
7751                        instantAppPkgName != null;
7752                final boolean isTargetSameInstantApp =
7753                        comp.getPackageName().equals(instantAppPkgName);
7754                final boolean isTargetInstantApp =
7755                        (ai.applicationInfo.privateFlags
7756                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7757                final boolean isTargetVisibleToInstantApp =
7758                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7759                final boolean isTargetExplicitlyVisibleToInstantApp =
7760                        isTargetVisibleToInstantApp
7761                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7762                final boolean isTargetHiddenFromInstantApp =
7763                        !isTargetVisibleToInstantApp
7764                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7765                final boolean blockResolution =
7766                        !isTargetSameInstantApp
7767                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7768                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7769                                        && isTargetHiddenFromInstantApp));
7770                if (!blockResolution) {
7771                    ResolveInfo ri = new ResolveInfo();
7772                    ri.activityInfo = ai;
7773                    list.add(ri);
7774                }
7775            }
7776            return applyPostResolutionFilter(list, instantAppPkgName);
7777        }
7778
7779        // reader
7780        synchronized (mPackages) {
7781            String pkgName = intent.getPackage();
7782            if (pkgName == null) {
7783                final List<ResolveInfo> result =
7784                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7785                return applyPostResolutionFilter(result, instantAppPkgName);
7786            }
7787            final PackageParser.Package pkg = mPackages.get(pkgName);
7788            if (pkg != null) {
7789                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7790                        intent, resolvedType, flags, pkg.receivers, userId);
7791                return applyPostResolutionFilter(result, instantAppPkgName);
7792            }
7793            return Collections.emptyList();
7794        }
7795    }
7796
7797    @Override
7798    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7799        final int callingUid = Binder.getCallingUid();
7800        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7801    }
7802
7803    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7804            int userId, int callingUid) {
7805        if (!sUserManager.exists(userId)) return null;
7806        flags = updateFlagsForResolve(
7807                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7808        List<ResolveInfo> query = queryIntentServicesInternal(
7809                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7810        if (query != null) {
7811            if (query.size() >= 1) {
7812                // If there is more than one service with the same priority,
7813                // just arbitrarily pick the first one.
7814                return query.get(0);
7815            }
7816        }
7817        return null;
7818    }
7819
7820    @Override
7821    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7822            String resolvedType, int flags, int userId) {
7823        final int callingUid = Binder.getCallingUid();
7824        return new ParceledListSlice<>(queryIntentServicesInternal(
7825                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7826    }
7827
7828    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7829            String resolvedType, int flags, int userId, int callingUid,
7830            boolean includeInstantApps) {
7831        if (!sUserManager.exists(userId)) return Collections.emptyList();
7832        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7833        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7834        ComponentName comp = intent.getComponent();
7835        if (comp == null) {
7836            if (intent.getSelector() != null) {
7837                intent = intent.getSelector();
7838                comp = intent.getComponent();
7839            }
7840        }
7841        if (comp != null) {
7842            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7843            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7844            if (si != null) {
7845                // When specifying an explicit component, we prevent the service from being
7846                // used when either 1) the service is in an instant application and the
7847                // caller is not the same instant application or 2) the calling package is
7848                // ephemeral and the activity is not visible to ephemeral applications.
7849                final boolean matchInstantApp =
7850                        (flags & PackageManager.MATCH_INSTANT) != 0;
7851                final boolean matchVisibleToInstantAppOnly =
7852                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7853                final boolean isCallerInstantApp =
7854                        instantAppPkgName != null;
7855                final boolean isTargetSameInstantApp =
7856                        comp.getPackageName().equals(instantAppPkgName);
7857                final boolean isTargetInstantApp =
7858                        (si.applicationInfo.privateFlags
7859                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7860                final boolean isTargetHiddenFromInstantApp =
7861                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7862                final boolean blockResolution =
7863                        !isTargetSameInstantApp
7864                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7865                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7866                                        && isTargetHiddenFromInstantApp));
7867                if (!blockResolution) {
7868                    final ResolveInfo ri = new ResolveInfo();
7869                    ri.serviceInfo = si;
7870                    list.add(ri);
7871                }
7872            }
7873            return list;
7874        }
7875
7876        // reader
7877        synchronized (mPackages) {
7878            String pkgName = intent.getPackage();
7879            if (pkgName == null) {
7880                return applyPostServiceResolutionFilter(
7881                        mServices.queryIntent(intent, resolvedType, flags, userId),
7882                        instantAppPkgName);
7883            }
7884            final PackageParser.Package pkg = mPackages.get(pkgName);
7885            if (pkg != null) {
7886                return applyPostServiceResolutionFilter(
7887                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7888                                userId),
7889                        instantAppPkgName);
7890            }
7891            return Collections.emptyList();
7892        }
7893    }
7894
7895    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7896            String instantAppPkgName) {
7897        // TODO: When adding on-demand split support for non-instant apps, remove this check
7898        // and always apply post filtering
7899        if (instantAppPkgName == null) {
7900            return resolveInfos;
7901        }
7902        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7903            final ResolveInfo info = resolveInfos.get(i);
7904            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7905            // allow services that are defined in the provided package
7906            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7907                if (info.serviceInfo.splitName != null
7908                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7909                                info.serviceInfo.splitName)) {
7910                    // requested service is defined in a split that hasn't been installed yet.
7911                    // add the installer to the resolve list
7912                    if (DEBUG_EPHEMERAL) {
7913                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7914                    }
7915                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7916                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7917                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7918                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7919                    // make sure this resolver is the default
7920                    installerInfo.isDefault = true;
7921                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7922                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7923                    // add a non-generic filter
7924                    installerInfo.filter = new IntentFilter();
7925                    // load resources from the correct package
7926                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7927                    resolveInfos.set(i, installerInfo);
7928                }
7929                continue;
7930            }
7931            // allow services that have been explicitly exposed to ephemeral apps
7932            if (!isEphemeralApp
7933                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7934                continue;
7935            }
7936            resolveInfos.remove(i);
7937        }
7938        return resolveInfos;
7939    }
7940
7941    @Override
7942    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7943            String resolvedType, int flags, int userId) {
7944        return new ParceledListSlice<>(
7945                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7946    }
7947
7948    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7949            Intent intent, String resolvedType, int flags, int userId) {
7950        if (!sUserManager.exists(userId)) return Collections.emptyList();
7951        final int callingUid = Binder.getCallingUid();
7952        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7953        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7954                false /*includeInstantApps*/);
7955        ComponentName comp = intent.getComponent();
7956        if (comp == null) {
7957            if (intent.getSelector() != null) {
7958                intent = intent.getSelector();
7959                comp = intent.getComponent();
7960            }
7961        }
7962        if (comp != null) {
7963            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7964            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7965            if (pi != null) {
7966                // When specifying an explicit component, we prevent the provider from being
7967                // used when either 1) the provider is in an instant application and the
7968                // caller is not the same instant application or 2) the calling package is an
7969                // instant application and the provider is not visible to instant applications.
7970                final boolean matchInstantApp =
7971                        (flags & PackageManager.MATCH_INSTANT) != 0;
7972                final boolean matchVisibleToInstantAppOnly =
7973                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7974                final boolean isCallerInstantApp =
7975                        instantAppPkgName != null;
7976                final boolean isTargetSameInstantApp =
7977                        comp.getPackageName().equals(instantAppPkgName);
7978                final boolean isTargetInstantApp =
7979                        (pi.applicationInfo.privateFlags
7980                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7981                final boolean isTargetHiddenFromInstantApp =
7982                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7983                final boolean blockResolution =
7984                        !isTargetSameInstantApp
7985                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7986                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7987                                        && isTargetHiddenFromInstantApp));
7988                if (!blockResolution) {
7989                    final ResolveInfo ri = new ResolveInfo();
7990                    ri.providerInfo = pi;
7991                    list.add(ri);
7992                }
7993            }
7994            return list;
7995        }
7996
7997        // reader
7998        synchronized (mPackages) {
7999            String pkgName = intent.getPackage();
8000            if (pkgName == null) {
8001                return applyPostContentProviderResolutionFilter(
8002                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8003                        instantAppPkgName);
8004            }
8005            final PackageParser.Package pkg = mPackages.get(pkgName);
8006            if (pkg != null) {
8007                return applyPostContentProviderResolutionFilter(
8008                        mProviders.queryIntentForPackage(
8009                        intent, resolvedType, flags, pkg.providers, userId),
8010                        instantAppPkgName);
8011            }
8012            return Collections.emptyList();
8013        }
8014    }
8015
8016    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8017            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8018        // TODO: When adding on-demand split support for non-instant applications, remove
8019        // this check and always apply post filtering
8020        if (instantAppPkgName == null) {
8021            return resolveInfos;
8022        }
8023        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8024            final ResolveInfo info = resolveInfos.get(i);
8025            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8026            // allow providers that are defined in the provided package
8027            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8028                if (info.providerInfo.splitName != null
8029                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8030                                info.providerInfo.splitName)) {
8031                    // requested provider is defined in a split that hasn't been installed yet.
8032                    // add the installer to the resolve list
8033                    if (DEBUG_EPHEMERAL) {
8034                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8035                    }
8036                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8037                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8038                            info.providerInfo.packageName, info.providerInfo.splitName,
8039                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8040                    // make sure this resolver is the default
8041                    installerInfo.isDefault = true;
8042                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8043                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8044                    // add a non-generic filter
8045                    installerInfo.filter = new IntentFilter();
8046                    // load resources from the correct package
8047                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8048                    resolveInfos.set(i, installerInfo);
8049                }
8050                continue;
8051            }
8052            // allow providers that have been explicitly exposed to instant applications
8053            if (!isEphemeralApp
8054                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8055                continue;
8056            }
8057            resolveInfos.remove(i);
8058        }
8059        return resolveInfos;
8060    }
8061
8062    @Override
8063    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8064        final int callingUid = Binder.getCallingUid();
8065        if (getInstantAppPackageName(callingUid) != null) {
8066            return ParceledListSlice.emptyList();
8067        }
8068        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8069        flags = updateFlagsForPackage(flags, userId, null);
8070        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8071        enforceCrossUserPermission(callingUid, userId,
8072                true /* requireFullPermission */, false /* checkShell */,
8073                "get installed packages");
8074
8075        // writer
8076        synchronized (mPackages) {
8077            ArrayList<PackageInfo> list;
8078            if (listUninstalled) {
8079                list = new ArrayList<>(mSettings.mPackages.size());
8080                for (PackageSetting ps : mSettings.mPackages.values()) {
8081                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8082                        continue;
8083                    }
8084                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8085                        return null;
8086                    }
8087                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8088                    if (pi != null) {
8089                        list.add(pi);
8090                    }
8091                }
8092            } else {
8093                list = new ArrayList<>(mPackages.size());
8094                for (PackageParser.Package p : mPackages.values()) {
8095                    final PackageSetting ps = (PackageSetting) p.mExtras;
8096                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8097                        continue;
8098                    }
8099                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8100                        return null;
8101                    }
8102                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8103                            p.mExtras, flags, userId);
8104                    if (pi != null) {
8105                        list.add(pi);
8106                    }
8107                }
8108            }
8109
8110            return new ParceledListSlice<>(list);
8111        }
8112    }
8113
8114    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8115            String[] permissions, boolean[] tmp, int flags, int userId) {
8116        int numMatch = 0;
8117        final PermissionsState permissionsState = ps.getPermissionsState();
8118        for (int i=0; i<permissions.length; i++) {
8119            final String permission = permissions[i];
8120            if (permissionsState.hasPermission(permission, userId)) {
8121                tmp[i] = true;
8122                numMatch++;
8123            } else {
8124                tmp[i] = false;
8125            }
8126        }
8127        if (numMatch == 0) {
8128            return;
8129        }
8130        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8131
8132        // The above might return null in cases of uninstalled apps or install-state
8133        // skew across users/profiles.
8134        if (pi != null) {
8135            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8136                if (numMatch == permissions.length) {
8137                    pi.requestedPermissions = permissions;
8138                } else {
8139                    pi.requestedPermissions = new String[numMatch];
8140                    numMatch = 0;
8141                    for (int i=0; i<permissions.length; i++) {
8142                        if (tmp[i]) {
8143                            pi.requestedPermissions[numMatch] = permissions[i];
8144                            numMatch++;
8145                        }
8146                    }
8147                }
8148            }
8149            list.add(pi);
8150        }
8151    }
8152
8153    @Override
8154    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8155            String[] permissions, int flags, int userId) {
8156        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8157        flags = updateFlagsForPackage(flags, userId, permissions);
8158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8159                true /* requireFullPermission */, false /* checkShell */,
8160                "get packages holding permissions");
8161        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8162
8163        // writer
8164        synchronized (mPackages) {
8165            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8166            boolean[] tmpBools = new boolean[permissions.length];
8167            if (listUninstalled) {
8168                for (PackageSetting ps : mSettings.mPackages.values()) {
8169                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8170                            userId);
8171                }
8172            } else {
8173                for (PackageParser.Package pkg : mPackages.values()) {
8174                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8175                    if (ps != null) {
8176                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8177                                userId);
8178                    }
8179                }
8180            }
8181
8182            return new ParceledListSlice<PackageInfo>(list);
8183        }
8184    }
8185
8186    @Override
8187    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8188        final int callingUid = Binder.getCallingUid();
8189        if (getInstantAppPackageName(callingUid) != null) {
8190            return ParceledListSlice.emptyList();
8191        }
8192        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8193        flags = updateFlagsForApplication(flags, userId, null);
8194        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8195
8196        // writer
8197        synchronized (mPackages) {
8198            ArrayList<ApplicationInfo> list;
8199            if (listUninstalled) {
8200                list = new ArrayList<>(mSettings.mPackages.size());
8201                for (PackageSetting ps : mSettings.mPackages.values()) {
8202                    ApplicationInfo ai;
8203                    int effectiveFlags = flags;
8204                    if (ps.isSystem()) {
8205                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8206                    }
8207                    if (ps.pkg != null) {
8208                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8209                            continue;
8210                        }
8211                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8212                            return null;
8213                        }
8214                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8215                                ps.readUserState(userId), userId);
8216                        if (ai != null) {
8217                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8218                        }
8219                    } else {
8220                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8221                        // and already converts to externally visible package name
8222                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8223                                callingUid, effectiveFlags, userId);
8224                    }
8225                    if (ai != null) {
8226                        list.add(ai);
8227                    }
8228                }
8229            } else {
8230                list = new ArrayList<>(mPackages.size());
8231                for (PackageParser.Package p : mPackages.values()) {
8232                    if (p.mExtras != null) {
8233                        PackageSetting ps = (PackageSetting) p.mExtras;
8234                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8235                            continue;
8236                        }
8237                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8238                            return null;
8239                        }
8240                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8241                                ps.readUserState(userId), userId);
8242                        if (ai != null) {
8243                            ai.packageName = resolveExternalPackageNameLPr(p);
8244                            list.add(ai);
8245                        }
8246                    }
8247                }
8248            }
8249
8250            return new ParceledListSlice<>(list);
8251        }
8252    }
8253
8254    @Override
8255    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8256        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8257            return null;
8258        }
8259        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8260                "getEphemeralApplications");
8261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8262                true /* requireFullPermission */, false /* checkShell */,
8263                "getEphemeralApplications");
8264        synchronized (mPackages) {
8265            List<InstantAppInfo> instantApps = mInstantAppRegistry
8266                    .getInstantAppsLPr(userId);
8267            if (instantApps != null) {
8268                return new ParceledListSlice<>(instantApps);
8269            }
8270        }
8271        return null;
8272    }
8273
8274    @Override
8275    public boolean isInstantApp(String packageName, int userId) {
8276        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8277                true /* requireFullPermission */, false /* checkShell */,
8278                "isInstantApp");
8279        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8280            return false;
8281        }
8282
8283        synchronized (mPackages) {
8284            int callingUid = Binder.getCallingUid();
8285            if (Process.isIsolated(callingUid)) {
8286                callingUid = mIsolatedOwners.get(callingUid);
8287            }
8288            final PackageSetting ps = mSettings.mPackages.get(packageName);
8289            PackageParser.Package pkg = mPackages.get(packageName);
8290            final boolean returnAllowed =
8291                    ps != null
8292                    && (isCallerSameApp(packageName, callingUid)
8293                            || canViewInstantApps(callingUid, userId)
8294                            || mInstantAppRegistry.isInstantAccessGranted(
8295                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8296            if (returnAllowed) {
8297                return ps.getInstantApp(userId);
8298            }
8299        }
8300        return false;
8301    }
8302
8303    @Override
8304    public byte[] getInstantAppCookie(String packageName, int userId) {
8305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306            return null;
8307        }
8308
8309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8310                true /* requireFullPermission */, false /* checkShell */,
8311                "getInstantAppCookie");
8312        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8313            return null;
8314        }
8315        synchronized (mPackages) {
8316            return mInstantAppRegistry.getInstantAppCookieLPw(
8317                    packageName, userId);
8318        }
8319    }
8320
8321    @Override
8322    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8323        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8324            return true;
8325        }
8326
8327        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8328                true /* requireFullPermission */, true /* checkShell */,
8329                "setInstantAppCookie");
8330        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8331            return false;
8332        }
8333        synchronized (mPackages) {
8334            return mInstantAppRegistry.setInstantAppCookieLPw(
8335                    packageName, cookie, userId);
8336        }
8337    }
8338
8339    @Override
8340    public Bitmap getInstantAppIcon(String packageName, int userId) {
8341        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8342            return null;
8343        }
8344
8345        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8346                "getInstantAppIcon");
8347
8348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8349                true /* requireFullPermission */, false /* checkShell */,
8350                "getInstantAppIcon");
8351
8352        synchronized (mPackages) {
8353            return mInstantAppRegistry.getInstantAppIconLPw(
8354                    packageName, userId);
8355        }
8356    }
8357
8358    private boolean isCallerSameApp(String packageName, int uid) {
8359        PackageParser.Package pkg = mPackages.get(packageName);
8360        return pkg != null
8361                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8362    }
8363
8364    @Override
8365    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8366        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8367            return ParceledListSlice.emptyList();
8368        }
8369        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8370    }
8371
8372    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8373        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8374
8375        // reader
8376        synchronized (mPackages) {
8377            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8378            final int userId = UserHandle.getCallingUserId();
8379            while (i.hasNext()) {
8380                final PackageParser.Package p = i.next();
8381                if (p.applicationInfo == null) continue;
8382
8383                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8384                        && !p.applicationInfo.isDirectBootAware();
8385                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8386                        && p.applicationInfo.isDirectBootAware();
8387
8388                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8389                        && (!mSafeMode || isSystemApp(p))
8390                        && (matchesUnaware || matchesAware)) {
8391                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8392                    if (ps != null) {
8393                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8394                                ps.readUserState(userId), userId);
8395                        if (ai != null) {
8396                            finalList.add(ai);
8397                        }
8398                    }
8399                }
8400            }
8401        }
8402
8403        return finalList;
8404    }
8405
8406    @Override
8407    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8408        if (!sUserManager.exists(userId)) return null;
8409        flags = updateFlagsForComponent(flags, userId, name);
8410        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8411        // reader
8412        synchronized (mPackages) {
8413            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8414            PackageSetting ps = provider != null
8415                    ? mSettings.mPackages.get(provider.owner.packageName)
8416                    : null;
8417            if (ps != null) {
8418                final boolean isInstantApp = ps.getInstantApp(userId);
8419                // normal application; filter out instant application provider
8420                if (instantAppPkgName == null && isInstantApp) {
8421                    return null;
8422                }
8423                // instant application; filter out other instant applications
8424                if (instantAppPkgName != null
8425                        && isInstantApp
8426                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8427                    return null;
8428                }
8429                // instant application; filter out non-exposed provider
8430                if (instantAppPkgName != null
8431                        && !isInstantApp
8432                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8433                    return null;
8434                }
8435                // provider not enabled
8436                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8437                    return null;
8438                }
8439                return PackageParser.generateProviderInfo(
8440                        provider, flags, ps.readUserState(userId), userId);
8441            }
8442            return null;
8443        }
8444    }
8445
8446    /**
8447     * @deprecated
8448     */
8449    @Deprecated
8450    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8451        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8452            return;
8453        }
8454        // reader
8455        synchronized (mPackages) {
8456            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8457                    .entrySet().iterator();
8458            final int userId = UserHandle.getCallingUserId();
8459            while (i.hasNext()) {
8460                Map.Entry<String, PackageParser.Provider> entry = i.next();
8461                PackageParser.Provider p = entry.getValue();
8462                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8463
8464                if (ps != null && p.syncable
8465                        && (!mSafeMode || (p.info.applicationInfo.flags
8466                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8467                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8468                            ps.readUserState(userId), userId);
8469                    if (info != null) {
8470                        outNames.add(entry.getKey());
8471                        outInfo.add(info);
8472                    }
8473                }
8474            }
8475        }
8476    }
8477
8478    @Override
8479    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8480            int uid, int flags, String metaDataKey) {
8481        final int callingUid = Binder.getCallingUid();
8482        final int userId = processName != null ? UserHandle.getUserId(uid)
8483                : UserHandle.getCallingUserId();
8484        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8485        flags = updateFlagsForComponent(flags, userId, processName);
8486        ArrayList<ProviderInfo> finalList = null;
8487        // reader
8488        synchronized (mPackages) {
8489            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8490            while (i.hasNext()) {
8491                final PackageParser.Provider p = i.next();
8492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8493                if (ps != null && p.info.authority != null
8494                        && (processName == null
8495                                || (p.info.processName.equals(processName)
8496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8497                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8498
8499                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8500                    // parameter.
8501                    if (metaDataKey != null
8502                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8503                        continue;
8504                    }
8505                    final ComponentName component =
8506                            new ComponentName(p.info.packageName, p.info.name);
8507                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8508                        continue;
8509                    }
8510                    if (finalList == null) {
8511                        finalList = new ArrayList<ProviderInfo>(3);
8512                    }
8513                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8514                            ps.readUserState(userId), userId);
8515                    if (info != null) {
8516                        finalList.add(info);
8517                    }
8518                }
8519            }
8520        }
8521
8522        if (finalList != null) {
8523            Collections.sort(finalList, mProviderInitOrderSorter);
8524            return new ParceledListSlice<ProviderInfo>(finalList);
8525        }
8526
8527        return ParceledListSlice.emptyList();
8528    }
8529
8530    @Override
8531    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8532        // reader
8533        synchronized (mPackages) {
8534            final int callingUid = Binder.getCallingUid();
8535            final int callingUserId = UserHandle.getUserId(callingUid);
8536            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8537            if (ps == null) return null;
8538            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8539                return null;
8540            }
8541            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8542            return PackageParser.generateInstrumentationInfo(i, flags);
8543        }
8544    }
8545
8546    @Override
8547    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8548            String targetPackage, int flags) {
8549        final int callingUid = Binder.getCallingUid();
8550        final int callingUserId = UserHandle.getUserId(callingUid);
8551        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8552        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8553            return ParceledListSlice.emptyList();
8554        }
8555        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8556    }
8557
8558    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8559            int flags) {
8560        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8561
8562        // reader
8563        synchronized (mPackages) {
8564            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8565            while (i.hasNext()) {
8566                final PackageParser.Instrumentation p = i.next();
8567                if (targetPackage == null
8568                        || targetPackage.equals(p.info.targetPackage)) {
8569                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8570                            flags);
8571                    if (ii != null) {
8572                        finalList.add(ii);
8573                    }
8574                }
8575            }
8576        }
8577
8578        return finalList;
8579    }
8580
8581    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8583        try {
8584            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8585        } finally {
8586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8587        }
8588    }
8589
8590    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8591        final File[] files = dir.listFiles();
8592        if (ArrayUtils.isEmpty(files)) {
8593            Log.d(TAG, "No files in app dir " + dir);
8594            return;
8595        }
8596
8597        if (DEBUG_PACKAGE_SCANNING) {
8598            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8599                    + " flags=0x" + Integer.toHexString(parseFlags));
8600        }
8601        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8602                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8603                mParallelPackageParserCallback);
8604
8605        // Submit files for parsing in parallel
8606        int fileCount = 0;
8607        for (File file : files) {
8608            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8609                    && !PackageInstallerService.isStageName(file.getName());
8610            if (!isPackage) {
8611                // Ignore entries which are not packages
8612                continue;
8613            }
8614            parallelPackageParser.submit(file, parseFlags);
8615            fileCount++;
8616        }
8617
8618        // Process results one by one
8619        for (; fileCount > 0; fileCount--) {
8620            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8621            Throwable throwable = parseResult.throwable;
8622            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8623
8624            if (throwable == null) {
8625                // Static shared libraries have synthetic package names
8626                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8627                    renameStaticSharedLibraryPackage(parseResult.pkg);
8628                }
8629                try {
8630                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8631                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8632                                currentTime, null);
8633                    }
8634                } catch (PackageManagerException e) {
8635                    errorCode = e.error;
8636                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8637                }
8638            } else if (throwable instanceof PackageParser.PackageParserException) {
8639                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8640                        throwable;
8641                errorCode = e.error;
8642                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8643            } else {
8644                throw new IllegalStateException("Unexpected exception occurred while parsing "
8645                        + parseResult.scanFile, throwable);
8646            }
8647
8648            // Delete invalid userdata apps
8649            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8650                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8651                logCriticalInfo(Log.WARN,
8652                        "Deleting invalid package at " + parseResult.scanFile);
8653                removeCodePathLI(parseResult.scanFile);
8654            }
8655        }
8656        parallelPackageParser.close();
8657    }
8658
8659    private static File getSettingsProblemFile() {
8660        File dataDir = Environment.getDataDirectory();
8661        File systemDir = new File(dataDir, "system");
8662        File fname = new File(systemDir, "uiderrors.txt");
8663        return fname;
8664    }
8665
8666    static void reportSettingsProblem(int priority, String msg) {
8667        logCriticalInfo(priority, msg);
8668    }
8669
8670    public static void logCriticalInfo(int priority, String msg) {
8671        Slog.println(priority, TAG, msg);
8672        EventLogTags.writePmCriticalInfo(msg);
8673        try {
8674            File fname = getSettingsProblemFile();
8675            FileOutputStream out = new FileOutputStream(fname, true);
8676            PrintWriter pw = new FastPrintWriter(out);
8677            SimpleDateFormat formatter = new SimpleDateFormat();
8678            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8679            pw.println(dateString + ": " + msg);
8680            pw.close();
8681            FileUtils.setPermissions(
8682                    fname.toString(),
8683                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8684                    -1, -1);
8685        } catch (java.io.IOException e) {
8686        }
8687    }
8688
8689    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8690        if (srcFile.isDirectory()) {
8691            final File baseFile = new File(pkg.baseCodePath);
8692            long maxModifiedTime = baseFile.lastModified();
8693            if (pkg.splitCodePaths != null) {
8694                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8695                    final File splitFile = new File(pkg.splitCodePaths[i]);
8696                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8697                }
8698            }
8699            return maxModifiedTime;
8700        }
8701        return srcFile.lastModified();
8702    }
8703
8704    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8705            final int policyFlags) throws PackageManagerException {
8706        // When upgrading from pre-N MR1, verify the package time stamp using the package
8707        // directory and not the APK file.
8708        final long lastModifiedTime = mIsPreNMR1Upgrade
8709                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8710        if (ps != null
8711                && ps.codePath.equals(srcFile)
8712                && ps.timeStamp == lastModifiedTime
8713                && !isCompatSignatureUpdateNeeded(pkg)
8714                && !isRecoverSignatureUpdateNeeded(pkg)) {
8715            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8716            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8717            ArraySet<PublicKey> signingKs;
8718            synchronized (mPackages) {
8719                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8720            }
8721            if (ps.signatures.mSignatures != null
8722                    && ps.signatures.mSignatures.length != 0
8723                    && signingKs != null) {
8724                // Optimization: reuse the existing cached certificates
8725                // if the package appears to be unchanged.
8726                pkg.mSignatures = ps.signatures.mSignatures;
8727                pkg.mSigningKeys = signingKs;
8728                return;
8729            }
8730
8731            Slog.w(TAG, "PackageSetting for " + ps.name
8732                    + " is missing signatures.  Collecting certs again to recover them.");
8733        } else {
8734            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8735        }
8736
8737        try {
8738            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8739            PackageParser.collectCertificates(pkg, policyFlags);
8740        } catch (PackageParserException e) {
8741            throw PackageManagerException.from(e);
8742        } finally {
8743            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8744        }
8745    }
8746
8747    /**
8748     *  Traces a package scan.
8749     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8750     */
8751    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8752            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8753        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8754        try {
8755            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8756        } finally {
8757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8758        }
8759    }
8760
8761    /**
8762     *  Scans a package and returns the newly parsed package.
8763     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8764     */
8765    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8766            long currentTime, UserHandle user) throws PackageManagerException {
8767        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8768        PackageParser pp = new PackageParser();
8769        pp.setSeparateProcesses(mSeparateProcesses);
8770        pp.setOnlyCoreApps(mOnlyCore);
8771        pp.setDisplayMetrics(mMetrics);
8772        pp.setCallback(mPackageParserCallback);
8773
8774        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8775            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8776        }
8777
8778        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8779        final PackageParser.Package pkg;
8780        try {
8781            pkg = pp.parsePackage(scanFile, parseFlags);
8782        } catch (PackageParserException e) {
8783            throw PackageManagerException.from(e);
8784        } finally {
8785            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8786        }
8787
8788        // Static shared libraries have synthetic package names
8789        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8790            renameStaticSharedLibraryPackage(pkg);
8791        }
8792
8793        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8794    }
8795
8796    /**
8797     *  Scans a package and returns the newly parsed package.
8798     *  @throws PackageManagerException on a parse error.
8799     */
8800    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8801            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8802            throws PackageManagerException {
8803        // If the package has children and this is the first dive in the function
8804        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8805        // packages (parent and children) would be successfully scanned before the
8806        // actual scan since scanning mutates internal state and we want to atomically
8807        // install the package and its children.
8808        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8809            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8810                scanFlags |= SCAN_CHECK_ONLY;
8811            }
8812        } else {
8813            scanFlags &= ~SCAN_CHECK_ONLY;
8814        }
8815
8816        // Scan the parent
8817        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8818                scanFlags, currentTime, user);
8819
8820        // Scan the children
8821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8822        for (int i = 0; i < childCount; i++) {
8823            PackageParser.Package childPackage = pkg.childPackages.get(i);
8824            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8825                    currentTime, user);
8826        }
8827
8828
8829        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8830            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8831        }
8832
8833        return scannedPkg;
8834    }
8835
8836    /**
8837     *  Scans a package and returns the newly parsed package.
8838     *  @throws PackageManagerException on a parse error.
8839     */
8840    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8841            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8842            throws PackageManagerException {
8843        PackageSetting ps = null;
8844        PackageSetting updatedPkg;
8845        // reader
8846        synchronized (mPackages) {
8847            // Look to see if we already know about this package.
8848            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8849            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8850                // This package has been renamed to its original name.  Let's
8851                // use that.
8852                ps = mSettings.getPackageLPr(oldName);
8853            }
8854            // If there was no original package, see one for the real package name.
8855            if (ps == null) {
8856                ps = mSettings.getPackageLPr(pkg.packageName);
8857            }
8858            // Check to see if this package could be hiding/updating a system
8859            // package.  Must look for it either under the original or real
8860            // package name depending on our state.
8861            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8862            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8863
8864            // If this is a package we don't know about on the system partition, we
8865            // may need to remove disabled child packages on the system partition
8866            // or may need to not add child packages if the parent apk is updated
8867            // on the data partition and no longer defines this child package.
8868            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8869                // If this is a parent package for an updated system app and this system
8870                // app got an OTA update which no longer defines some of the child packages
8871                // we have to prune them from the disabled system packages.
8872                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8873                if (disabledPs != null) {
8874                    final int scannedChildCount = (pkg.childPackages != null)
8875                            ? pkg.childPackages.size() : 0;
8876                    final int disabledChildCount = disabledPs.childPackageNames != null
8877                            ? disabledPs.childPackageNames.size() : 0;
8878                    for (int i = 0; i < disabledChildCount; i++) {
8879                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8880                        boolean disabledPackageAvailable = false;
8881                        for (int j = 0; j < scannedChildCount; j++) {
8882                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8883                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8884                                disabledPackageAvailable = true;
8885                                break;
8886                            }
8887                         }
8888                         if (!disabledPackageAvailable) {
8889                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8890                         }
8891                    }
8892                }
8893            }
8894        }
8895
8896        boolean updatedPkgBetter = false;
8897        // First check if this is a system package that may involve an update
8898        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8899            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8900            // it needs to drop FLAG_PRIVILEGED.
8901            if (locationIsPrivileged(scanFile)) {
8902                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8903            } else {
8904                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8905            }
8906
8907            if (ps != null && !ps.codePath.equals(scanFile)) {
8908                // The path has changed from what was last scanned...  check the
8909                // version of the new path against what we have stored to determine
8910                // what to do.
8911                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8912                if (pkg.mVersionCode <= ps.versionCode) {
8913                    // The system package has been updated and the code path does not match
8914                    // Ignore entry. Skip it.
8915                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8916                            + " ignored: updated version " + ps.versionCode
8917                            + " better than this " + pkg.mVersionCode);
8918                    if (!updatedPkg.codePath.equals(scanFile)) {
8919                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8920                                + ps.name + " changing from " + updatedPkg.codePathString
8921                                + " to " + scanFile);
8922                        updatedPkg.codePath = scanFile;
8923                        updatedPkg.codePathString = scanFile.toString();
8924                        updatedPkg.resourcePath = scanFile;
8925                        updatedPkg.resourcePathString = scanFile.toString();
8926                    }
8927                    updatedPkg.pkg = pkg;
8928                    updatedPkg.versionCode = pkg.mVersionCode;
8929
8930                    // Update the disabled system child packages to point to the package too.
8931                    final int childCount = updatedPkg.childPackageNames != null
8932                            ? updatedPkg.childPackageNames.size() : 0;
8933                    for (int i = 0; i < childCount; i++) {
8934                        String childPackageName = updatedPkg.childPackageNames.get(i);
8935                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8936                                childPackageName);
8937                        if (updatedChildPkg != null) {
8938                            updatedChildPkg.pkg = pkg;
8939                            updatedChildPkg.versionCode = pkg.mVersionCode;
8940                        }
8941                    }
8942
8943                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8944                            + scanFile + " ignored: updated version " + ps.versionCode
8945                            + " better than this " + pkg.mVersionCode);
8946                } else {
8947                    // The current app on the system partition is better than
8948                    // what we have updated to on the data partition; switch
8949                    // back to the system partition version.
8950                    // At this point, its safely assumed that package installation for
8951                    // apps in system partition will go through. If not there won't be a working
8952                    // version of the app
8953                    // writer
8954                    synchronized (mPackages) {
8955                        // Just remove the loaded entries from package lists.
8956                        mPackages.remove(ps.name);
8957                    }
8958
8959                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8960                            + " reverting from " + ps.codePathString
8961                            + ": new version " + pkg.mVersionCode
8962                            + " better than installed " + ps.versionCode);
8963
8964                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8965                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8966                    synchronized (mInstallLock) {
8967                        args.cleanUpResourcesLI();
8968                    }
8969                    synchronized (mPackages) {
8970                        mSettings.enableSystemPackageLPw(ps.name);
8971                    }
8972                    updatedPkgBetter = true;
8973                }
8974            }
8975        }
8976
8977        if (updatedPkg != null) {
8978            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8979            // initially
8980            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8981
8982            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8983            // flag set initially
8984            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8985                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8986            }
8987        }
8988
8989        // Verify certificates against what was last scanned
8990        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8991
8992        /*
8993         * A new system app appeared, but we already had a non-system one of the
8994         * same name installed earlier.
8995         */
8996        boolean shouldHideSystemApp = false;
8997        if (updatedPkg == null && ps != null
8998                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8999            /*
9000             * Check to make sure the signatures match first. If they don't,
9001             * wipe the installed application and its data.
9002             */
9003            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9004                    != PackageManager.SIGNATURE_MATCH) {
9005                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9006                        + " signatures don't match existing userdata copy; removing");
9007                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9008                        "scanPackageInternalLI")) {
9009                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9010                }
9011                ps = null;
9012            } else {
9013                /*
9014                 * If the newly-added system app is an older version than the
9015                 * already installed version, hide it. It will be scanned later
9016                 * and re-added like an update.
9017                 */
9018                if (pkg.mVersionCode <= ps.versionCode) {
9019                    shouldHideSystemApp = true;
9020                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9021                            + " but new version " + pkg.mVersionCode + " better than installed "
9022                            + ps.versionCode + "; hiding system");
9023                } else {
9024                    /*
9025                     * The newly found system app is a newer version that the
9026                     * one previously installed. Simply remove the
9027                     * already-installed application and replace it with our own
9028                     * while keeping the application data.
9029                     */
9030                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9031                            + " reverting from " + ps.codePathString + ": new version "
9032                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9033                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9034                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9035                    synchronized (mInstallLock) {
9036                        args.cleanUpResourcesLI();
9037                    }
9038                }
9039            }
9040        }
9041
9042        // The apk is forward locked (not public) if its code and resources
9043        // are kept in different files. (except for app in either system or
9044        // vendor path).
9045        // TODO grab this value from PackageSettings
9046        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9047            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9048                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9049            }
9050        }
9051
9052        // TODO: extend to support forward-locked splits
9053        String resourcePath = null;
9054        String baseResourcePath = null;
9055        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9056            if (ps != null && ps.resourcePathString != null) {
9057                resourcePath = ps.resourcePathString;
9058                baseResourcePath = ps.resourcePathString;
9059            } else {
9060                // Should not happen at all. Just log an error.
9061                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9062            }
9063        } else {
9064            resourcePath = pkg.codePath;
9065            baseResourcePath = pkg.baseCodePath;
9066        }
9067
9068        // Set application objects path explicitly.
9069        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9070        pkg.setApplicationInfoCodePath(pkg.codePath);
9071        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9072        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9073        pkg.setApplicationInfoResourcePath(resourcePath);
9074        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9075        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9076
9077        final int userId = ((user == null) ? 0 : user.getIdentifier());
9078        if (ps != null && ps.getInstantApp(userId)) {
9079            scanFlags |= SCAN_AS_INSTANT_APP;
9080        }
9081
9082        // Note that we invoke the following method only if we are about to unpack an application
9083        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9084                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9085
9086        /*
9087         * If the system app should be overridden by a previously installed
9088         * data, hide the system app now and let the /data/app scan pick it up
9089         * again.
9090         */
9091        if (shouldHideSystemApp) {
9092            synchronized (mPackages) {
9093                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9094            }
9095        }
9096
9097        return scannedPkg;
9098    }
9099
9100    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9101        // Derive the new package synthetic package name
9102        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9103                + pkg.staticSharedLibVersion);
9104    }
9105
9106    private static String fixProcessName(String defProcessName,
9107            String processName) {
9108        if (processName == null) {
9109            return defProcessName;
9110        }
9111        return processName;
9112    }
9113
9114    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9115            throws PackageManagerException {
9116        if (pkgSetting.signatures.mSignatures != null) {
9117            // Already existing package. Make sure signatures match
9118            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9119                    == PackageManager.SIGNATURE_MATCH;
9120            if (!match) {
9121                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9122                        == PackageManager.SIGNATURE_MATCH;
9123            }
9124            if (!match) {
9125                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9126                        == PackageManager.SIGNATURE_MATCH;
9127            }
9128            if (!match) {
9129                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9130                        + pkg.packageName + " signatures do not match the "
9131                        + "previously installed version; ignoring!");
9132            }
9133        }
9134
9135        // Check for shared user signatures
9136        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9137            // Already existing package. Make sure signatures match
9138            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9139                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9140            if (!match) {
9141                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9142                        == PackageManager.SIGNATURE_MATCH;
9143            }
9144            if (!match) {
9145                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9146                        == PackageManager.SIGNATURE_MATCH;
9147            }
9148            if (!match) {
9149                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9150                        "Package " + pkg.packageName
9151                        + " has no signatures that match those in shared user "
9152                        + pkgSetting.sharedUser.name + "; ignoring!");
9153            }
9154        }
9155    }
9156
9157    /**
9158     * Enforces that only the system UID or root's UID can call a method exposed
9159     * via Binder.
9160     *
9161     * @param message used as message if SecurityException is thrown
9162     * @throws SecurityException if the caller is not system or root
9163     */
9164    private static final void enforceSystemOrRoot(String message) {
9165        final int uid = Binder.getCallingUid();
9166        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9167            throw new SecurityException(message);
9168        }
9169    }
9170
9171    @Override
9172    public void performFstrimIfNeeded() {
9173        enforceSystemOrRoot("Only the system can request fstrim");
9174
9175        // Before everything else, see whether we need to fstrim.
9176        try {
9177            IStorageManager sm = PackageHelper.getStorageManager();
9178            if (sm != null) {
9179                boolean doTrim = false;
9180                final long interval = android.provider.Settings.Global.getLong(
9181                        mContext.getContentResolver(),
9182                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9183                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9184                if (interval > 0) {
9185                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9186                    if (timeSinceLast > interval) {
9187                        doTrim = true;
9188                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9189                                + "; running immediately");
9190                    }
9191                }
9192                if (doTrim) {
9193                    final boolean dexOptDialogShown;
9194                    synchronized (mPackages) {
9195                        dexOptDialogShown = mDexOptDialogShown;
9196                    }
9197                    if (!isFirstBoot() && dexOptDialogShown) {
9198                        try {
9199                            ActivityManager.getService().showBootMessage(
9200                                    mContext.getResources().getString(
9201                                            R.string.android_upgrading_fstrim), true);
9202                        } catch (RemoteException e) {
9203                        }
9204                    }
9205                    sm.runMaintenance();
9206                }
9207            } else {
9208                Slog.e(TAG, "storageManager service unavailable!");
9209            }
9210        } catch (RemoteException e) {
9211            // Can't happen; StorageManagerService is local
9212        }
9213    }
9214
9215    @Override
9216    public void updatePackagesIfNeeded() {
9217        enforceSystemOrRoot("Only the system can request package update");
9218
9219        // We need to re-extract after an OTA.
9220        boolean causeUpgrade = isUpgrade();
9221
9222        // First boot or factory reset.
9223        // Note: we also handle devices that are upgrading to N right now as if it is their
9224        //       first boot, as they do not have profile data.
9225        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9226
9227        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9228        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9229
9230        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9231            return;
9232        }
9233
9234        List<PackageParser.Package> pkgs;
9235        synchronized (mPackages) {
9236            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9237        }
9238
9239        final long startTime = System.nanoTime();
9240        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9241                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9242                    false /* bootComplete */);
9243
9244        final int elapsedTimeSeconds =
9245                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9246
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9248        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9249        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9250        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9251        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9252    }
9253
9254    /*
9255     * Return the prebuilt profile path given a package base code path.
9256     */
9257    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9258        return pkg.baseCodePath + ".prof";
9259    }
9260
9261    /**
9262     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9263     * containing statistics about the invocation. The array consists of three elements,
9264     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9265     * and {@code numberOfPackagesFailed}.
9266     */
9267    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9268            String compilerFilter, boolean bootComplete) {
9269
9270        int numberOfPackagesVisited = 0;
9271        int numberOfPackagesOptimized = 0;
9272        int numberOfPackagesSkipped = 0;
9273        int numberOfPackagesFailed = 0;
9274        final int numberOfPackagesToDexopt = pkgs.size();
9275
9276        for (PackageParser.Package pkg : pkgs) {
9277            numberOfPackagesVisited++;
9278
9279            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9280                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9281                // that are already compiled.
9282                File profileFile = new File(getPrebuildProfilePath(pkg));
9283                // Copy profile if it exists.
9284                if (profileFile.exists()) {
9285                    try {
9286                        // We could also do this lazily before calling dexopt in
9287                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9288                        // is that we don't have a good way to say "do this only once".
9289                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9290                                pkg.applicationInfo.uid, pkg.packageName)) {
9291                            Log.e(TAG, "Installer failed to copy system profile!");
9292                        }
9293                    } catch (Exception e) {
9294                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9295                                e);
9296                    }
9297                }
9298            }
9299
9300            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9301                if (DEBUG_DEXOPT) {
9302                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9303                }
9304                numberOfPackagesSkipped++;
9305                continue;
9306            }
9307
9308            if (DEBUG_DEXOPT) {
9309                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9310                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9311            }
9312
9313            if (showDialog) {
9314                try {
9315                    ActivityManager.getService().showBootMessage(
9316                            mContext.getResources().getString(R.string.android_upgrading_apk,
9317                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9318                } catch (RemoteException e) {
9319                }
9320                synchronized (mPackages) {
9321                    mDexOptDialogShown = true;
9322                }
9323            }
9324
9325            // If the OTA updates a system app which was previously preopted to a non-preopted state
9326            // the app might end up being verified at runtime. That's because by default the apps
9327            // are verify-profile but for preopted apps there's no profile.
9328            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9329            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9330            // filter (by default 'quicken').
9331            // Note that at this stage unused apps are already filtered.
9332            if (isSystemApp(pkg) &&
9333                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9334                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9335                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9336            }
9337
9338            // checkProfiles is false to avoid merging profiles during boot which
9339            // might interfere with background compilation (b/28612421).
9340            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9341            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9342            // trade-off worth doing to save boot time work.
9343            int primaryDexOptStaus = performDexOptTraced(pkg.packageName,
9344                    false /* checkProfiles */,
9345                    compilerFilter,
9346                    false /* force */,
9347                    bootComplete);
9348
9349            boolean secondaryDexOptStatus = true;
9350            if (pkg.isSystemApp()) {
9351                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9352                // too much boot after an OTA.
9353                secondaryDexOptStatus = mDexManager.dexoptSecondaryDex(pkg.packageName,
9354                        compilerFilter,
9355                        false /* force */,
9356                        true /* compileOnlySharedDex */);
9357            }
9358
9359            if (secondaryDexOptStatus) {
9360                switch (primaryDexOptStaus) {
9361                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9362                        numberOfPackagesOptimized++;
9363                        break;
9364                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9365                        numberOfPackagesSkipped++;
9366                        break;
9367                    case PackageDexOptimizer.DEX_OPT_FAILED:
9368                        numberOfPackagesFailed++;
9369                        break;
9370                    default:
9371                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9372                        break;
9373                }
9374            } else {
9375                numberOfPackagesFailed++;
9376            }
9377        }
9378
9379        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9380                numberOfPackagesFailed };
9381    }
9382
9383    @Override
9384    public void notifyPackageUse(String packageName, int reason) {
9385        synchronized (mPackages) {
9386            final int callingUid = Binder.getCallingUid();
9387            final int callingUserId = UserHandle.getUserId(callingUid);
9388            if (getInstantAppPackageName(callingUid) != null) {
9389                if (!isCallerSameApp(packageName, callingUid)) {
9390                    return;
9391                }
9392            } else {
9393                if (isInstantApp(packageName, callingUserId)) {
9394                    return;
9395                }
9396            }
9397            final PackageParser.Package p = mPackages.get(packageName);
9398            if (p == null) {
9399                return;
9400            }
9401            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9402        }
9403    }
9404
9405    @Override
9406    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9407        int userId = UserHandle.getCallingUserId();
9408        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9409        if (ai == null) {
9410            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9411                + loadingPackageName + ", user=" + userId);
9412            return;
9413        }
9414        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9415    }
9416
9417    @Override
9418    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9419            IDexModuleRegisterCallback callback) {
9420        int userId = UserHandle.getCallingUserId();
9421        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9422        DexManager.RegisterDexModuleResult result;
9423        if (ai == null) {
9424            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9425                     " calling user. package=" + packageName + ", user=" + userId);
9426            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9427        } else {
9428            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9429        }
9430
9431        if (callback != null) {
9432            mHandler.post(() -> {
9433                try {
9434                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9435                } catch (RemoteException e) {
9436                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9437                }
9438            });
9439        }
9440    }
9441
9442    @Override
9443    public boolean performDexOpt(String packageName,
9444            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9445        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9446            return false;
9447        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9448            return false;
9449        }
9450        int dexoptStatus = performDexOptWithStatus(
9451              packageName, checkProfiles, compileReason, force, bootComplete);
9452        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9453    }
9454
9455    /**
9456     * Perform dexopt on the given package and return one of following result:
9457     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9458     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9459     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9460     */
9461    /* package */ int performDexOptWithStatus(String packageName,
9462            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9463        return performDexOptTraced(packageName, checkProfiles,
9464                getCompilerFilterForReason(compileReason), force, bootComplete);
9465    }
9466
9467    @Override
9468    public boolean performDexOptMode(String packageName,
9469            boolean checkProfiles, String targetCompilerFilter, boolean force,
9470            boolean bootComplete) {
9471        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9472            return false;
9473        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9474            return false;
9475        }
9476        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9477                targetCompilerFilter, force, bootComplete);
9478        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9479    }
9480
9481    private int performDexOptTraced(String packageName,
9482                boolean checkProfiles, String targetCompilerFilter, boolean force,
9483                boolean bootComplete) {
9484        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9485        try {
9486            return performDexOptInternal(packageName, checkProfiles,
9487                    targetCompilerFilter, force, bootComplete);
9488        } finally {
9489            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9490        }
9491    }
9492
9493    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9494    // if the package can now be considered up to date for the given filter.
9495    private int performDexOptInternal(String packageName,
9496                boolean checkProfiles, String targetCompilerFilter, boolean force,
9497                boolean bootComplete) {
9498        PackageParser.Package p;
9499        synchronized (mPackages) {
9500            p = mPackages.get(packageName);
9501            if (p == null) {
9502                // Package could not be found. Report failure.
9503                return PackageDexOptimizer.DEX_OPT_FAILED;
9504            }
9505            mPackageUsage.maybeWriteAsync(mPackages);
9506            mCompilerStats.maybeWriteAsync();
9507        }
9508        long callingId = Binder.clearCallingIdentity();
9509        try {
9510            synchronized (mInstallLock) {
9511                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9512                        targetCompilerFilter, force, bootComplete);
9513            }
9514        } finally {
9515            Binder.restoreCallingIdentity(callingId);
9516        }
9517    }
9518
9519    public ArraySet<String> getOptimizablePackages() {
9520        ArraySet<String> pkgs = new ArraySet<String>();
9521        synchronized (mPackages) {
9522            for (PackageParser.Package p : mPackages.values()) {
9523                if (PackageDexOptimizer.canOptimizePackage(p)) {
9524                    pkgs.add(p.packageName);
9525                }
9526            }
9527        }
9528        return pkgs;
9529    }
9530
9531    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9532            boolean checkProfiles, String targetCompilerFilter,
9533            boolean force, boolean bootComplete) {
9534        // Select the dex optimizer based on the force parameter.
9535        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9536        //       allocate an object here.
9537        PackageDexOptimizer pdo = force
9538                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9539                : mPackageDexOptimizer;
9540
9541        // Dexopt all dependencies first. Note: we ignore the return value and march on
9542        // on errors.
9543        // Note that we are going to call performDexOpt on those libraries as many times as
9544        // they are referenced in packages. When we do a batch of performDexOpt (for example
9545        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9546        // and the first package that uses the library will dexopt it. The
9547        // others will see that the compiled code for the library is up to date.
9548        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9549        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9550        if (!deps.isEmpty()) {
9551            for (PackageParser.Package depPackage : deps) {
9552                // TODO: Analyze and investigate if we (should) profile libraries.
9553                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9554                        false /* checkProfiles */,
9555                        targetCompilerFilter,
9556                        getOrCreateCompilerPackageStats(depPackage),
9557                        true /* isUsedByOtherApps */,
9558                        bootComplete);
9559            }
9560        }
9561        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9562                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9563                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9564    }
9565
9566    // Performs dexopt on the used secondary dex files belonging to the given package.
9567    // Returns true if all dex files were process successfully (which could mean either dexopt or
9568    // skip). Returns false if any of the files caused errors.
9569    @Override
9570    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9571            boolean force) {
9572        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9573            return false;
9574        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9575            return false;
9576        }
9577        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force,
9578                /* compileOnlySharedDex*/ false);
9579    }
9580
9581    public boolean performDexOptSecondary(String packageName, int compileReason,
9582            boolean force) {
9583        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9584    }
9585
9586    /**
9587     * Reconcile the information we have about the secondary dex files belonging to
9588     * {@code packagName} and the actual dex files. For all dex files that were
9589     * deleted, update the internal records and delete the generated oat files.
9590     */
9591    @Override
9592    public void reconcileSecondaryDexFiles(String packageName) {
9593        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9594            return;
9595        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9596            return;
9597        }
9598        mDexManager.reconcileSecondaryDexFiles(packageName);
9599    }
9600
9601    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9602    // a reference there.
9603    /*package*/ DexManager getDexManager() {
9604        return mDexManager;
9605    }
9606
9607    /**
9608     * Execute the background dexopt job immediately.
9609     */
9610    @Override
9611    public boolean runBackgroundDexoptJob() {
9612        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9613            return false;
9614        }
9615        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9616    }
9617
9618    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9619        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9620                || p.usesStaticLibraries != null) {
9621            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9622            Set<String> collectedNames = new HashSet<>();
9623            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9624
9625            retValue.remove(p);
9626
9627            return retValue;
9628        } else {
9629            return Collections.emptyList();
9630        }
9631    }
9632
9633    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9634            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9635        if (!collectedNames.contains(p.packageName)) {
9636            collectedNames.add(p.packageName);
9637            collected.add(p);
9638
9639            if (p.usesLibraries != null) {
9640                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9641                        null, collected, collectedNames);
9642            }
9643            if (p.usesOptionalLibraries != null) {
9644                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9645                        null, collected, collectedNames);
9646            }
9647            if (p.usesStaticLibraries != null) {
9648                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9649                        p.usesStaticLibrariesVersions, collected, collectedNames);
9650            }
9651        }
9652    }
9653
9654    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9655            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9656        final int libNameCount = libs.size();
9657        for (int i = 0; i < libNameCount; i++) {
9658            String libName = libs.get(i);
9659            int version = (versions != null && versions.length == libNameCount)
9660                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9661            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9662            if (libPkg != null) {
9663                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9664            }
9665        }
9666    }
9667
9668    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9669        synchronized (mPackages) {
9670            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9671            if (libEntry != null) {
9672                return mPackages.get(libEntry.apk);
9673            }
9674            return null;
9675        }
9676    }
9677
9678    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9679        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9680        if (versionedLib == null) {
9681            return null;
9682        }
9683        return versionedLib.get(version);
9684    }
9685
9686    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9687        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9688                pkg.staticSharedLibName);
9689        if (versionedLib == null) {
9690            return null;
9691        }
9692        int previousLibVersion = -1;
9693        final int versionCount = versionedLib.size();
9694        for (int i = 0; i < versionCount; i++) {
9695            final int libVersion = versionedLib.keyAt(i);
9696            if (libVersion < pkg.staticSharedLibVersion) {
9697                previousLibVersion = Math.max(previousLibVersion, libVersion);
9698            }
9699        }
9700        if (previousLibVersion >= 0) {
9701            return versionedLib.get(previousLibVersion);
9702        }
9703        return null;
9704    }
9705
9706    public void shutdown() {
9707        mPackageUsage.writeNow(mPackages);
9708        mCompilerStats.writeNow();
9709    }
9710
9711    @Override
9712    public void dumpProfiles(String packageName) {
9713        PackageParser.Package pkg;
9714        synchronized (mPackages) {
9715            pkg = mPackages.get(packageName);
9716            if (pkg == null) {
9717                throw new IllegalArgumentException("Unknown package: " + packageName);
9718            }
9719        }
9720        /* Only the shell, root, or the app user should be able to dump profiles. */
9721        int callingUid = Binder.getCallingUid();
9722        if (callingUid != Process.SHELL_UID &&
9723            callingUid != Process.ROOT_UID &&
9724            callingUid != pkg.applicationInfo.uid) {
9725            throw new SecurityException("dumpProfiles");
9726        }
9727
9728        synchronized (mInstallLock) {
9729            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9730            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9731            try {
9732                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9733                String codePaths = TextUtils.join(";", allCodePaths);
9734                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9735            } catch (InstallerException e) {
9736                Slog.w(TAG, "Failed to dump profiles", e);
9737            }
9738            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9739        }
9740    }
9741
9742    @Override
9743    public void forceDexOpt(String packageName) {
9744        enforceSystemOrRoot("forceDexOpt");
9745
9746        PackageParser.Package pkg;
9747        synchronized (mPackages) {
9748            pkg = mPackages.get(packageName);
9749            if (pkg == null) {
9750                throw new IllegalArgumentException("Unknown package: " + packageName);
9751            }
9752        }
9753
9754        synchronized (mInstallLock) {
9755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9756
9757            // Whoever is calling forceDexOpt wants a compiled package.
9758            // Don't use profiles since that may cause compilation to be skipped.
9759            final int res = performDexOptInternalWithDependenciesLI(pkg,
9760                    false /* checkProfiles */, getDefaultCompilerFilter(),
9761                    true /* force */,
9762                    true /* bootComplete */);
9763
9764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9765            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9766                throw new IllegalStateException("Failed to dexopt: " + res);
9767            }
9768        }
9769    }
9770
9771    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9772        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9773            Slog.w(TAG, "Unable to update from " + oldPkg.name
9774                    + " to " + newPkg.packageName
9775                    + ": old package not in system partition");
9776            return false;
9777        } else if (mPackages.get(oldPkg.name) != null) {
9778            Slog.w(TAG, "Unable to update from " + oldPkg.name
9779                    + " to " + newPkg.packageName
9780                    + ": old package still exists");
9781            return false;
9782        }
9783        return true;
9784    }
9785
9786    void removeCodePathLI(File codePath) {
9787        if (codePath.isDirectory()) {
9788            try {
9789                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9790            } catch (InstallerException e) {
9791                Slog.w(TAG, "Failed to remove code path", e);
9792            }
9793        } else {
9794            codePath.delete();
9795        }
9796    }
9797
9798    private int[] resolveUserIds(int userId) {
9799        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9800    }
9801
9802    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9803        if (pkg == null) {
9804            Slog.wtf(TAG, "Package was null!", new Throwable());
9805            return;
9806        }
9807        clearAppDataLeafLIF(pkg, userId, flags);
9808        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9809        for (int i = 0; i < childCount; i++) {
9810            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9811        }
9812    }
9813
9814    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9815        final PackageSetting ps;
9816        synchronized (mPackages) {
9817            ps = mSettings.mPackages.get(pkg.packageName);
9818        }
9819        for (int realUserId : resolveUserIds(userId)) {
9820            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9821            try {
9822                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9823                        ceDataInode);
9824            } catch (InstallerException e) {
9825                Slog.w(TAG, String.valueOf(e));
9826            }
9827        }
9828    }
9829
9830    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9831        if (pkg == null) {
9832            Slog.wtf(TAG, "Package was null!", new Throwable());
9833            return;
9834        }
9835        destroyAppDataLeafLIF(pkg, userId, flags);
9836        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9837        for (int i = 0; i < childCount; i++) {
9838            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9839        }
9840    }
9841
9842    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9843        final PackageSetting ps;
9844        synchronized (mPackages) {
9845            ps = mSettings.mPackages.get(pkg.packageName);
9846        }
9847        for (int realUserId : resolveUserIds(userId)) {
9848            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9849            try {
9850                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9851                        ceDataInode);
9852            } catch (InstallerException e) {
9853                Slog.w(TAG, String.valueOf(e));
9854            }
9855            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9856        }
9857    }
9858
9859    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9860        if (pkg == null) {
9861            Slog.wtf(TAG, "Package was null!", new Throwable());
9862            return;
9863        }
9864        destroyAppProfilesLeafLIF(pkg);
9865        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9866        for (int i = 0; i < childCount; i++) {
9867            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9868        }
9869    }
9870
9871    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9872        try {
9873            mInstaller.destroyAppProfiles(pkg.packageName);
9874        } catch (InstallerException e) {
9875            Slog.w(TAG, String.valueOf(e));
9876        }
9877    }
9878
9879    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9880        if (pkg == null) {
9881            Slog.wtf(TAG, "Package was null!", new Throwable());
9882            return;
9883        }
9884        clearAppProfilesLeafLIF(pkg);
9885        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9886        for (int i = 0; i < childCount; i++) {
9887            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9888        }
9889    }
9890
9891    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9892        try {
9893            mInstaller.clearAppProfiles(pkg.packageName);
9894        } catch (InstallerException e) {
9895            Slog.w(TAG, String.valueOf(e));
9896        }
9897    }
9898
9899    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9900            long lastUpdateTime) {
9901        // Set parent install/update time
9902        PackageSetting ps = (PackageSetting) pkg.mExtras;
9903        if (ps != null) {
9904            ps.firstInstallTime = firstInstallTime;
9905            ps.lastUpdateTime = lastUpdateTime;
9906        }
9907        // Set children install/update time
9908        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9909        for (int i = 0; i < childCount; i++) {
9910            PackageParser.Package childPkg = pkg.childPackages.get(i);
9911            ps = (PackageSetting) childPkg.mExtras;
9912            if (ps != null) {
9913                ps.firstInstallTime = firstInstallTime;
9914                ps.lastUpdateTime = lastUpdateTime;
9915            }
9916        }
9917    }
9918
9919    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9920            PackageParser.Package changingLib) {
9921        if (file.path != null) {
9922            usesLibraryFiles.add(file.path);
9923            return;
9924        }
9925        PackageParser.Package p = mPackages.get(file.apk);
9926        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9927            // If we are doing this while in the middle of updating a library apk,
9928            // then we need to make sure to use that new apk for determining the
9929            // dependencies here.  (We haven't yet finished committing the new apk
9930            // to the package manager state.)
9931            if (p == null || p.packageName.equals(changingLib.packageName)) {
9932                p = changingLib;
9933            }
9934        }
9935        if (p != null) {
9936            usesLibraryFiles.addAll(p.getAllCodePaths());
9937            if (p.usesLibraryFiles != null) {
9938                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9939            }
9940        }
9941    }
9942
9943    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9944            PackageParser.Package changingLib) throws PackageManagerException {
9945        if (pkg == null) {
9946            return;
9947        }
9948        ArraySet<String> usesLibraryFiles = null;
9949        if (pkg.usesLibraries != null) {
9950            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9951                    null, null, pkg.packageName, changingLib, true, null);
9952        }
9953        if (pkg.usesStaticLibraries != null) {
9954            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9955                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9956                    pkg.packageName, changingLib, true, usesLibraryFiles);
9957        }
9958        if (pkg.usesOptionalLibraries != null) {
9959            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9960                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9961        }
9962        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9963            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9964        } else {
9965            pkg.usesLibraryFiles = null;
9966        }
9967    }
9968
9969    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9970            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9971            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9972            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9973            throws PackageManagerException {
9974        final int libCount = requestedLibraries.size();
9975        for (int i = 0; i < libCount; i++) {
9976            final String libName = requestedLibraries.get(i);
9977            final int libVersion = requiredVersions != null ? requiredVersions[i]
9978                    : SharedLibraryInfo.VERSION_UNDEFINED;
9979            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9980            if (libEntry == null) {
9981                if (required) {
9982                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9983                            "Package " + packageName + " requires unavailable shared library "
9984                                    + libName + "; failing!");
9985                } else if (DEBUG_SHARED_LIBRARIES) {
9986                    Slog.i(TAG, "Package " + packageName
9987                            + " desires unavailable shared library "
9988                            + libName + "; ignoring!");
9989                }
9990            } else {
9991                if (requiredVersions != null && requiredCertDigests != null) {
9992                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9993                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9994                            "Package " + packageName + " requires unavailable static shared"
9995                                    + " library " + libName + " version "
9996                                    + libEntry.info.getVersion() + "; failing!");
9997                    }
9998
9999                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10000                    if (libPkg == null) {
10001                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10002                                "Package " + packageName + " requires unavailable static shared"
10003                                        + " library; failing!");
10004                    }
10005
10006                    String expectedCertDigest = requiredCertDigests[i];
10007                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10008                                libPkg.mSignatures[0]);
10009                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10010                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10011                                "Package " + packageName + " requires differently signed" +
10012                                        " static shared library; failing!");
10013                    }
10014                }
10015
10016                if (outUsedLibraries == null) {
10017                    outUsedLibraries = new ArraySet<>();
10018                }
10019                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10020            }
10021        }
10022        return outUsedLibraries;
10023    }
10024
10025    private static boolean hasString(List<String> list, List<String> which) {
10026        if (list == null) {
10027            return false;
10028        }
10029        for (int i=list.size()-1; i>=0; i--) {
10030            for (int j=which.size()-1; j>=0; j--) {
10031                if (which.get(j).equals(list.get(i))) {
10032                    return true;
10033                }
10034            }
10035        }
10036        return false;
10037    }
10038
10039    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10040            PackageParser.Package changingPkg) {
10041        ArrayList<PackageParser.Package> res = null;
10042        for (PackageParser.Package pkg : mPackages.values()) {
10043            if (changingPkg != null
10044                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10045                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10046                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10047                            changingPkg.staticSharedLibName)) {
10048                return null;
10049            }
10050            if (res == null) {
10051                res = new ArrayList<>();
10052            }
10053            res.add(pkg);
10054            try {
10055                updateSharedLibrariesLPr(pkg, changingPkg);
10056            } catch (PackageManagerException e) {
10057                // If a system app update or an app and a required lib missing we
10058                // delete the package and for updated system apps keep the data as
10059                // it is better for the user to reinstall than to be in an limbo
10060                // state. Also libs disappearing under an app should never happen
10061                // - just in case.
10062                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10063                    final int flags = pkg.isUpdatedSystemApp()
10064                            ? PackageManager.DELETE_KEEP_DATA : 0;
10065                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10066                            flags , null, true, null);
10067                }
10068                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10069            }
10070        }
10071        return res;
10072    }
10073
10074    /**
10075     * Derive the value of the {@code cpuAbiOverride} based on the provided
10076     * value and an optional stored value from the package settings.
10077     */
10078    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10079        String cpuAbiOverride = null;
10080
10081        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10082            cpuAbiOverride = null;
10083        } else if (abiOverride != null) {
10084            cpuAbiOverride = abiOverride;
10085        } else if (settings != null) {
10086            cpuAbiOverride = settings.cpuAbiOverrideString;
10087        }
10088
10089        return cpuAbiOverride;
10090    }
10091
10092    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10093            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10094                    throws PackageManagerException {
10095        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10096        // If the package has children and this is the first dive in the function
10097        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10098        // whether all packages (parent and children) would be successfully scanned
10099        // before the actual scan since scanning mutates internal state and we want
10100        // to atomically install the package and its children.
10101        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10102            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10103                scanFlags |= SCAN_CHECK_ONLY;
10104            }
10105        } else {
10106            scanFlags &= ~SCAN_CHECK_ONLY;
10107        }
10108
10109        final PackageParser.Package scannedPkg;
10110        try {
10111            // Scan the parent
10112            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10113            // Scan the children
10114            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10115            for (int i = 0; i < childCount; i++) {
10116                PackageParser.Package childPkg = pkg.childPackages.get(i);
10117                scanPackageLI(childPkg, policyFlags,
10118                        scanFlags, currentTime, user);
10119            }
10120        } finally {
10121            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10122        }
10123
10124        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10125            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10126        }
10127
10128        return scannedPkg;
10129    }
10130
10131    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10132            int scanFlags, long currentTime, @Nullable UserHandle user)
10133                    throws PackageManagerException {
10134        boolean success = false;
10135        try {
10136            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10137                    currentTime, user);
10138            success = true;
10139            return res;
10140        } finally {
10141            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10142                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10143                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10144                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10145                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10146            }
10147        }
10148    }
10149
10150    /**
10151     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10152     */
10153    private static boolean apkHasCode(String fileName) {
10154        StrictJarFile jarFile = null;
10155        try {
10156            jarFile = new StrictJarFile(fileName,
10157                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10158            return jarFile.findEntry("classes.dex") != null;
10159        } catch (IOException ignore) {
10160        } finally {
10161            try {
10162                if (jarFile != null) {
10163                    jarFile.close();
10164                }
10165            } catch (IOException ignore) {}
10166        }
10167        return false;
10168    }
10169
10170    /**
10171     * Enforces code policy for the package. This ensures that if an APK has
10172     * declared hasCode="true" in its manifest that the APK actually contains
10173     * code.
10174     *
10175     * @throws PackageManagerException If bytecode could not be found when it should exist
10176     */
10177    private static void assertCodePolicy(PackageParser.Package pkg)
10178            throws PackageManagerException {
10179        final boolean shouldHaveCode =
10180                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10181        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10182            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10183                    "Package " + pkg.baseCodePath + " code is missing");
10184        }
10185
10186        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10187            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10188                final boolean splitShouldHaveCode =
10189                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10190                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10191                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10192                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10193                }
10194            }
10195        }
10196    }
10197
10198    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10199            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10200                    throws PackageManagerException {
10201        if (DEBUG_PACKAGE_SCANNING) {
10202            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10203                Log.d(TAG, "Scanning package " + pkg.packageName);
10204        }
10205
10206        applyPolicy(pkg, policyFlags);
10207
10208        assertPackageIsValid(pkg, policyFlags, scanFlags);
10209
10210        // Initialize package source and resource directories
10211        final File scanFile = new File(pkg.codePath);
10212        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10213        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10214
10215        SharedUserSetting suid = null;
10216        PackageSetting pkgSetting = null;
10217
10218        // Getting the package setting may have a side-effect, so if we
10219        // are only checking if scan would succeed, stash a copy of the
10220        // old setting to restore at the end.
10221        PackageSetting nonMutatedPs = null;
10222
10223        // We keep references to the derived CPU Abis from settings in oder to reuse
10224        // them in the case where we're not upgrading or booting for the first time.
10225        String primaryCpuAbiFromSettings = null;
10226        String secondaryCpuAbiFromSettings = null;
10227
10228        // writer
10229        synchronized (mPackages) {
10230            if (pkg.mSharedUserId != null) {
10231                // SIDE EFFECTS; may potentially allocate a new shared user
10232                suid = mSettings.getSharedUserLPw(
10233                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10234                if (DEBUG_PACKAGE_SCANNING) {
10235                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10236                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10237                                + "): packages=" + suid.packages);
10238                }
10239            }
10240
10241            // Check if we are renaming from an original package name.
10242            PackageSetting origPackage = null;
10243            String realName = null;
10244            if (pkg.mOriginalPackages != null) {
10245                // This package may need to be renamed to a previously
10246                // installed name.  Let's check on that...
10247                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10248                if (pkg.mOriginalPackages.contains(renamed)) {
10249                    // This package had originally been installed as the
10250                    // original name, and we have already taken care of
10251                    // transitioning to the new one.  Just update the new
10252                    // one to continue using the old name.
10253                    realName = pkg.mRealPackage;
10254                    if (!pkg.packageName.equals(renamed)) {
10255                        // Callers into this function may have already taken
10256                        // care of renaming the package; only do it here if
10257                        // it is not already done.
10258                        pkg.setPackageName(renamed);
10259                    }
10260                } else {
10261                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10262                        if ((origPackage = mSettings.getPackageLPr(
10263                                pkg.mOriginalPackages.get(i))) != null) {
10264                            // We do have the package already installed under its
10265                            // original name...  should we use it?
10266                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10267                                // New package is not compatible with original.
10268                                origPackage = null;
10269                                continue;
10270                            } else if (origPackage.sharedUser != null) {
10271                                // Make sure uid is compatible between packages.
10272                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10273                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10274                                            + " to " + pkg.packageName + ": old uid "
10275                                            + origPackage.sharedUser.name
10276                                            + " differs from " + pkg.mSharedUserId);
10277                                    origPackage = null;
10278                                    continue;
10279                                }
10280                                // TODO: Add case when shared user id is added [b/28144775]
10281                            } else {
10282                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10283                                        + pkg.packageName + " to old name " + origPackage.name);
10284                            }
10285                            break;
10286                        }
10287                    }
10288                }
10289            }
10290
10291            if (mTransferedPackages.contains(pkg.packageName)) {
10292                Slog.w(TAG, "Package " + pkg.packageName
10293                        + " was transferred to another, but its .apk remains");
10294            }
10295
10296            // See comments in nonMutatedPs declaration
10297            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10298                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10299                if (foundPs != null) {
10300                    nonMutatedPs = new PackageSetting(foundPs);
10301                }
10302            }
10303
10304            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10305                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10306                if (foundPs != null) {
10307                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10308                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10309                }
10310            }
10311
10312            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10313            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10314                PackageManagerService.reportSettingsProblem(Log.WARN,
10315                        "Package " + pkg.packageName + " shared user changed from "
10316                                + (pkgSetting.sharedUser != null
10317                                        ? pkgSetting.sharedUser.name : "<nothing>")
10318                                + " to "
10319                                + (suid != null ? suid.name : "<nothing>")
10320                                + "; replacing with new");
10321                pkgSetting = null;
10322            }
10323            final PackageSetting oldPkgSetting =
10324                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10325            final PackageSetting disabledPkgSetting =
10326                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10327
10328            String[] usesStaticLibraries = null;
10329            if (pkg.usesStaticLibraries != null) {
10330                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10331                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10332            }
10333
10334            if (pkgSetting == null) {
10335                final String parentPackageName = (pkg.parentPackage != null)
10336                        ? pkg.parentPackage.packageName : null;
10337                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10338                // REMOVE SharedUserSetting from method; update in a separate call
10339                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10340                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10341                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10342                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10343                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10344                        true /*allowInstall*/, instantApp, parentPackageName,
10345                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10346                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10347                // SIDE EFFECTS; updates system state; move elsewhere
10348                if (origPackage != null) {
10349                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10350                }
10351                mSettings.addUserToSettingLPw(pkgSetting);
10352            } else {
10353                // REMOVE SharedUserSetting from method; update in a separate call.
10354                //
10355                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10356                // secondaryCpuAbi are not known at this point so we always update them
10357                // to null here, only to reset them at a later point.
10358                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10359                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10360                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10361                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10362                        UserManagerService.getInstance(), usesStaticLibraries,
10363                        pkg.usesStaticLibrariesVersions);
10364            }
10365            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10366            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10367
10368            // SIDE EFFECTS; modifies system state; move elsewhere
10369            if (pkgSetting.origPackage != null) {
10370                // If we are first transitioning from an original package,
10371                // fix up the new package's name now.  We need to do this after
10372                // looking up the package under its new name, so getPackageLP
10373                // can take care of fiddling things correctly.
10374                pkg.setPackageName(origPackage.name);
10375
10376                // File a report about this.
10377                String msg = "New package " + pkgSetting.realName
10378                        + " renamed to replace old package " + pkgSetting.name;
10379                reportSettingsProblem(Log.WARN, msg);
10380
10381                // Make a note of it.
10382                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10383                    mTransferedPackages.add(origPackage.name);
10384                }
10385
10386                // No longer need to retain this.
10387                pkgSetting.origPackage = null;
10388            }
10389
10390            // SIDE EFFECTS; modifies system state; move elsewhere
10391            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10392                // Make a note of it.
10393                mTransferedPackages.add(pkg.packageName);
10394            }
10395
10396            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10397                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10398            }
10399
10400            if ((scanFlags & SCAN_BOOTING) == 0
10401                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10402                // Check all shared libraries and map to their actual file path.
10403                // We only do this here for apps not on a system dir, because those
10404                // are the only ones that can fail an install due to this.  We
10405                // will take care of the system apps by updating all of their
10406                // library paths after the scan is done. Also during the initial
10407                // scan don't update any libs as we do this wholesale after all
10408                // apps are scanned to avoid dependency based scanning.
10409                updateSharedLibrariesLPr(pkg, null);
10410            }
10411
10412            if (mFoundPolicyFile) {
10413                SELinuxMMAC.assignSeInfoValue(pkg);
10414            }
10415            pkg.applicationInfo.uid = pkgSetting.appId;
10416            pkg.mExtras = pkgSetting;
10417
10418
10419            // Static shared libs have same package with different versions where
10420            // we internally use a synthetic package name to allow multiple versions
10421            // of the same package, therefore we need to compare signatures against
10422            // the package setting for the latest library version.
10423            PackageSetting signatureCheckPs = pkgSetting;
10424            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10425                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10426                if (libraryEntry != null) {
10427                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10428                }
10429            }
10430
10431            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10432                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10433                    // We just determined the app is signed correctly, so bring
10434                    // over the latest parsed certs.
10435                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10436                } else {
10437                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10438                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10439                                "Package " + pkg.packageName + " upgrade keys do not match the "
10440                                + "previously installed version");
10441                    } else {
10442                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10443                        String msg = "System package " + pkg.packageName
10444                                + " signature changed; retaining data.";
10445                        reportSettingsProblem(Log.WARN, msg);
10446                    }
10447                }
10448            } else {
10449                try {
10450                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10451                    verifySignaturesLP(signatureCheckPs, pkg);
10452                    // We just determined the app is signed correctly, so bring
10453                    // over the latest parsed certs.
10454                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10455                } catch (PackageManagerException e) {
10456                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10457                        throw e;
10458                    }
10459                    // The signature has changed, but this package is in the system
10460                    // image...  let's recover!
10461                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10462                    // However...  if this package is part of a shared user, but it
10463                    // doesn't match the signature of the shared user, let's fail.
10464                    // What this means is that you can't change the signatures
10465                    // associated with an overall shared user, which doesn't seem all
10466                    // that unreasonable.
10467                    if (signatureCheckPs.sharedUser != null) {
10468                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10469                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10470                            throw new PackageManagerException(
10471                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10472                                    "Signature mismatch for shared user: "
10473                                            + pkgSetting.sharedUser);
10474                        }
10475                    }
10476                    // File a report about this.
10477                    String msg = "System package " + pkg.packageName
10478                            + " signature changed; retaining data.";
10479                    reportSettingsProblem(Log.WARN, msg);
10480                }
10481            }
10482
10483            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10484                // This package wants to adopt ownership of permissions from
10485                // another package.
10486                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10487                    final String origName = pkg.mAdoptPermissions.get(i);
10488                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10489                    if (orig != null) {
10490                        if (verifyPackageUpdateLPr(orig, pkg)) {
10491                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10492                                    + pkg.packageName);
10493                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10494                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10495                        }
10496                    }
10497                }
10498            }
10499        }
10500
10501        pkg.applicationInfo.processName = fixProcessName(
10502                pkg.applicationInfo.packageName,
10503                pkg.applicationInfo.processName);
10504
10505        if (pkg != mPlatformPackage) {
10506            // Get all of our default paths setup
10507            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10508        }
10509
10510        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10511
10512        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10513            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10514                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10515                final boolean extractNativeLibs = !pkg.isLibrary();
10516                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10517                        mAppLib32InstallDir);
10518                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10519
10520                // Some system apps still use directory structure for native libraries
10521                // in which case we might end up not detecting abi solely based on apk
10522                // structure. Try to detect abi based on directory structure.
10523                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10524                        pkg.applicationInfo.primaryCpuAbi == null) {
10525                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10526                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10527                }
10528            } else {
10529                // This is not a first boot or an upgrade, don't bother deriving the
10530                // ABI during the scan. Instead, trust the value that was stored in the
10531                // package setting.
10532                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10533                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10534
10535                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10536
10537                if (DEBUG_ABI_SELECTION) {
10538                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10539                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10540                        pkg.applicationInfo.secondaryCpuAbi);
10541                }
10542            }
10543        } else {
10544            if ((scanFlags & SCAN_MOVE) != 0) {
10545                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10546                // but we already have this packages package info in the PackageSetting. We just
10547                // use that and derive the native library path based on the new codepath.
10548                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10549                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10550            }
10551
10552            // Set native library paths again. For moves, the path will be updated based on the
10553            // ABIs we've determined above. For non-moves, the path will be updated based on the
10554            // ABIs we determined during compilation, but the path will depend on the final
10555            // package path (after the rename away from the stage path).
10556            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10557        }
10558
10559        // This is a special case for the "system" package, where the ABI is
10560        // dictated by the zygote configuration (and init.rc). We should keep track
10561        // of this ABI so that we can deal with "normal" applications that run under
10562        // the same UID correctly.
10563        if (mPlatformPackage == pkg) {
10564            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10565                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10566        }
10567
10568        // If there's a mismatch between the abi-override in the package setting
10569        // and the abiOverride specified for the install. Warn about this because we
10570        // would've already compiled the app without taking the package setting into
10571        // account.
10572        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10573            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10574                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10575                        " for package " + pkg.packageName);
10576            }
10577        }
10578
10579        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10580        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10581        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10582
10583        // Copy the derived override back to the parsed package, so that we can
10584        // update the package settings accordingly.
10585        pkg.cpuAbiOverride = cpuAbiOverride;
10586
10587        if (DEBUG_ABI_SELECTION) {
10588            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10589                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10590                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10591        }
10592
10593        // Push the derived path down into PackageSettings so we know what to
10594        // clean up at uninstall time.
10595        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10596
10597        if (DEBUG_ABI_SELECTION) {
10598            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10599                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10600                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10601        }
10602
10603        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10604        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10605            // We don't do this here during boot because we can do it all
10606            // at once after scanning all existing packages.
10607            //
10608            // We also do this *before* we perform dexopt on this package, so that
10609            // we can avoid redundant dexopts, and also to make sure we've got the
10610            // code and package path correct.
10611            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10612        }
10613
10614        if (mFactoryTest && pkg.requestedPermissions.contains(
10615                android.Manifest.permission.FACTORY_TEST)) {
10616            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10617        }
10618
10619        if (isSystemApp(pkg)) {
10620            pkgSetting.isOrphaned = true;
10621        }
10622
10623        // Take care of first install / last update times.
10624        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10625        if (currentTime != 0) {
10626            if (pkgSetting.firstInstallTime == 0) {
10627                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10628            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10629                pkgSetting.lastUpdateTime = currentTime;
10630            }
10631        } else if (pkgSetting.firstInstallTime == 0) {
10632            // We need *something*.  Take time time stamp of the file.
10633            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10634        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10635            if (scanFileTime != pkgSetting.timeStamp) {
10636                // A package on the system image has changed; consider this
10637                // to be an update.
10638                pkgSetting.lastUpdateTime = scanFileTime;
10639            }
10640        }
10641        pkgSetting.setTimeStamp(scanFileTime);
10642
10643        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10644            if (nonMutatedPs != null) {
10645                synchronized (mPackages) {
10646                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10647                }
10648            }
10649        } else {
10650            final int userId = user == null ? 0 : user.getIdentifier();
10651            // Modify state for the given package setting
10652            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10653                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10654            if (pkgSetting.getInstantApp(userId)) {
10655                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10656            }
10657        }
10658        return pkg;
10659    }
10660
10661    /**
10662     * Applies policy to the parsed package based upon the given policy flags.
10663     * Ensures the package is in a good state.
10664     * <p>
10665     * Implementation detail: This method must NOT have any side effect. It would
10666     * ideally be static, but, it requires locks to read system state.
10667     */
10668    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10669        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10670            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10671            if (pkg.applicationInfo.isDirectBootAware()) {
10672                // we're direct boot aware; set for all components
10673                for (PackageParser.Service s : pkg.services) {
10674                    s.info.encryptionAware = s.info.directBootAware = true;
10675                }
10676                for (PackageParser.Provider p : pkg.providers) {
10677                    p.info.encryptionAware = p.info.directBootAware = true;
10678                }
10679                for (PackageParser.Activity a : pkg.activities) {
10680                    a.info.encryptionAware = a.info.directBootAware = true;
10681                }
10682                for (PackageParser.Activity r : pkg.receivers) {
10683                    r.info.encryptionAware = r.info.directBootAware = true;
10684                }
10685            }
10686        } else {
10687            // Only allow system apps to be flagged as core apps.
10688            pkg.coreApp = false;
10689            // clear flags not applicable to regular apps
10690            pkg.applicationInfo.privateFlags &=
10691                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10692            pkg.applicationInfo.privateFlags &=
10693                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10694        }
10695        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10696
10697        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10698            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10699        }
10700
10701        if (!isSystemApp(pkg)) {
10702            // Only system apps can use these features.
10703            pkg.mOriginalPackages = null;
10704            pkg.mRealPackage = null;
10705            pkg.mAdoptPermissions = null;
10706        }
10707    }
10708
10709    /**
10710     * Asserts the parsed package is valid according to the given policy. If the
10711     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10712     * <p>
10713     * Implementation detail: This method must NOT have any side effects. It would
10714     * ideally be static, but, it requires locks to read system state.
10715     *
10716     * @throws PackageManagerException If the package fails any of the validation checks
10717     */
10718    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10719            throws PackageManagerException {
10720        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10721            assertCodePolicy(pkg);
10722        }
10723
10724        if (pkg.applicationInfo.getCodePath() == null ||
10725                pkg.applicationInfo.getResourcePath() == null) {
10726            // Bail out. The resource and code paths haven't been set.
10727            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10728                    "Code and resource paths haven't been set correctly");
10729        }
10730
10731        // Make sure we're not adding any bogus keyset info
10732        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10733        ksms.assertScannedPackageValid(pkg);
10734
10735        synchronized (mPackages) {
10736            // The special "android" package can only be defined once
10737            if (pkg.packageName.equals("android")) {
10738                if (mAndroidApplication != null) {
10739                    Slog.w(TAG, "*************************************************");
10740                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10741                    Slog.w(TAG, " codePath=" + pkg.codePath);
10742                    Slog.w(TAG, "*************************************************");
10743                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10744                            "Core android package being redefined.  Skipping.");
10745                }
10746            }
10747
10748            // A package name must be unique; don't allow duplicates
10749            if (mPackages.containsKey(pkg.packageName)) {
10750                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10751                        "Application package " + pkg.packageName
10752                        + " already installed.  Skipping duplicate.");
10753            }
10754
10755            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10756                // Static libs have a synthetic package name containing the version
10757                // but we still want the base name to be unique.
10758                if (mPackages.containsKey(pkg.manifestPackageName)) {
10759                    throw new PackageManagerException(
10760                            "Duplicate static shared lib provider package");
10761                }
10762
10763                // Static shared libraries should have at least O target SDK
10764                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10765                    throw new PackageManagerException(
10766                            "Packages declaring static-shared libs must target O SDK or higher");
10767                }
10768
10769                // Package declaring static a shared lib cannot be instant apps
10770                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10771                    throw new PackageManagerException(
10772                            "Packages declaring static-shared libs cannot be instant apps");
10773                }
10774
10775                // Package declaring static a shared lib cannot be renamed since the package
10776                // name is synthetic and apps can't code around package manager internals.
10777                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10778                    throw new PackageManagerException(
10779                            "Packages declaring static-shared libs cannot be renamed");
10780                }
10781
10782                // Package declaring static a shared lib cannot declare child packages
10783                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10784                    throw new PackageManagerException(
10785                            "Packages declaring static-shared libs cannot have child packages");
10786                }
10787
10788                // Package declaring static a shared lib cannot declare dynamic libs
10789                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10790                    throw new PackageManagerException(
10791                            "Packages declaring static-shared libs cannot declare dynamic libs");
10792                }
10793
10794                // Package declaring static a shared lib cannot declare shared users
10795                if (pkg.mSharedUserId != null) {
10796                    throw new PackageManagerException(
10797                            "Packages declaring static-shared libs cannot declare shared users");
10798                }
10799
10800                // Static shared libs cannot declare activities
10801                if (!pkg.activities.isEmpty()) {
10802                    throw new PackageManagerException(
10803                            "Static shared libs cannot declare activities");
10804                }
10805
10806                // Static shared libs cannot declare services
10807                if (!pkg.services.isEmpty()) {
10808                    throw new PackageManagerException(
10809                            "Static shared libs cannot declare services");
10810                }
10811
10812                // Static shared libs cannot declare providers
10813                if (!pkg.providers.isEmpty()) {
10814                    throw new PackageManagerException(
10815                            "Static shared libs cannot declare content providers");
10816                }
10817
10818                // Static shared libs cannot declare receivers
10819                if (!pkg.receivers.isEmpty()) {
10820                    throw new PackageManagerException(
10821                            "Static shared libs cannot declare broadcast receivers");
10822                }
10823
10824                // Static shared libs cannot declare permission groups
10825                if (!pkg.permissionGroups.isEmpty()) {
10826                    throw new PackageManagerException(
10827                            "Static shared libs cannot declare permission groups");
10828                }
10829
10830                // Static shared libs cannot declare permissions
10831                if (!pkg.permissions.isEmpty()) {
10832                    throw new PackageManagerException(
10833                            "Static shared libs cannot declare permissions");
10834                }
10835
10836                // Static shared libs cannot declare protected broadcasts
10837                if (pkg.protectedBroadcasts != null) {
10838                    throw new PackageManagerException(
10839                            "Static shared libs cannot declare protected broadcasts");
10840                }
10841
10842                // Static shared libs cannot be overlay targets
10843                if (pkg.mOverlayTarget != null) {
10844                    throw new PackageManagerException(
10845                            "Static shared libs cannot be overlay targets");
10846                }
10847
10848                // The version codes must be ordered as lib versions
10849                int minVersionCode = Integer.MIN_VALUE;
10850                int maxVersionCode = Integer.MAX_VALUE;
10851
10852                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10853                        pkg.staticSharedLibName);
10854                if (versionedLib != null) {
10855                    final int versionCount = versionedLib.size();
10856                    for (int i = 0; i < versionCount; i++) {
10857                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10858                        final int libVersionCode = libInfo.getDeclaringPackage()
10859                                .getVersionCode();
10860                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10861                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10862                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10863                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10864                        } else {
10865                            minVersionCode = maxVersionCode = libVersionCode;
10866                            break;
10867                        }
10868                    }
10869                }
10870                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10871                    throw new PackageManagerException("Static shared"
10872                            + " lib version codes must be ordered as lib versions");
10873                }
10874            }
10875
10876            // Only privileged apps and updated privileged apps can add child packages.
10877            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10878                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10879                    throw new PackageManagerException("Only privileged apps can add child "
10880                            + "packages. Ignoring package " + pkg.packageName);
10881                }
10882                final int childCount = pkg.childPackages.size();
10883                for (int i = 0; i < childCount; i++) {
10884                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10885                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10886                            childPkg.packageName)) {
10887                        throw new PackageManagerException("Can't override child of "
10888                                + "another disabled app. Ignoring package " + pkg.packageName);
10889                    }
10890                }
10891            }
10892
10893            // If we're only installing presumed-existing packages, require that the
10894            // scanned APK is both already known and at the path previously established
10895            // for it.  Previously unknown packages we pick up normally, but if we have an
10896            // a priori expectation about this package's install presence, enforce it.
10897            // With a singular exception for new system packages. When an OTA contains
10898            // a new system package, we allow the codepath to change from a system location
10899            // to the user-installed location. If we don't allow this change, any newer,
10900            // user-installed version of the application will be ignored.
10901            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10902                if (mExpectingBetter.containsKey(pkg.packageName)) {
10903                    logCriticalInfo(Log.WARN,
10904                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10905                } else {
10906                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10907                    if (known != null) {
10908                        if (DEBUG_PACKAGE_SCANNING) {
10909                            Log.d(TAG, "Examining " + pkg.codePath
10910                                    + " and requiring known paths " + known.codePathString
10911                                    + " & " + known.resourcePathString);
10912                        }
10913                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10914                                || !pkg.applicationInfo.getResourcePath().equals(
10915                                        known.resourcePathString)) {
10916                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10917                                    "Application package " + pkg.packageName
10918                                    + " found at " + pkg.applicationInfo.getCodePath()
10919                                    + " but expected at " + known.codePathString
10920                                    + "; ignoring.");
10921                        }
10922                    }
10923                }
10924            }
10925
10926            // Verify that this new package doesn't have any content providers
10927            // that conflict with existing packages.  Only do this if the
10928            // package isn't already installed, since we don't want to break
10929            // things that are installed.
10930            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10931                final int N = pkg.providers.size();
10932                int i;
10933                for (i=0; i<N; i++) {
10934                    PackageParser.Provider p = pkg.providers.get(i);
10935                    if (p.info.authority != null) {
10936                        String names[] = p.info.authority.split(";");
10937                        for (int j = 0; j < names.length; j++) {
10938                            if (mProvidersByAuthority.containsKey(names[j])) {
10939                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10940                                final String otherPackageName =
10941                                        ((other != null && other.getComponentName() != null) ?
10942                                                other.getComponentName().getPackageName() : "?");
10943                                throw new PackageManagerException(
10944                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10945                                        "Can't install because provider name " + names[j]
10946                                                + " (in package " + pkg.applicationInfo.packageName
10947                                                + ") is already used by " + otherPackageName);
10948                            }
10949                        }
10950                    }
10951                }
10952            }
10953        }
10954    }
10955
10956    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10957            int type, String declaringPackageName, int declaringVersionCode) {
10958        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10959        if (versionedLib == null) {
10960            versionedLib = new SparseArray<>();
10961            mSharedLibraries.put(name, versionedLib);
10962            if (type == SharedLibraryInfo.TYPE_STATIC) {
10963                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10964            }
10965        } else if (versionedLib.indexOfKey(version) >= 0) {
10966            return false;
10967        }
10968        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10969                version, type, declaringPackageName, declaringVersionCode);
10970        versionedLib.put(version, libEntry);
10971        return true;
10972    }
10973
10974    private boolean removeSharedLibraryLPw(String name, int version) {
10975        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10976        if (versionedLib == null) {
10977            return false;
10978        }
10979        final int libIdx = versionedLib.indexOfKey(version);
10980        if (libIdx < 0) {
10981            return false;
10982        }
10983        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10984        versionedLib.remove(version);
10985        if (versionedLib.size() <= 0) {
10986            mSharedLibraries.remove(name);
10987            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10988                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10989                        .getPackageName());
10990            }
10991        }
10992        return true;
10993    }
10994
10995    /**
10996     * Adds a scanned package to the system. When this method is finished, the package will
10997     * be available for query, resolution, etc...
10998     */
10999    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11000            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11001        final String pkgName = pkg.packageName;
11002        if (mCustomResolverComponentName != null &&
11003                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11004            setUpCustomResolverActivity(pkg);
11005        }
11006
11007        if (pkg.packageName.equals("android")) {
11008            synchronized (mPackages) {
11009                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11010                    // Set up information for our fall-back user intent resolution activity.
11011                    mPlatformPackage = pkg;
11012                    pkg.mVersionCode = mSdkVersion;
11013                    mAndroidApplication = pkg.applicationInfo;
11014                    if (!mResolverReplaced) {
11015                        mResolveActivity.applicationInfo = mAndroidApplication;
11016                        mResolveActivity.name = ResolverActivity.class.getName();
11017                        mResolveActivity.packageName = mAndroidApplication.packageName;
11018                        mResolveActivity.processName = "system:ui";
11019                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11020                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11021                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11022                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11023                        mResolveActivity.exported = true;
11024                        mResolveActivity.enabled = true;
11025                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11026                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11027                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11028                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11029                                | ActivityInfo.CONFIG_ORIENTATION
11030                                | ActivityInfo.CONFIG_KEYBOARD
11031                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11032                        mResolveInfo.activityInfo = mResolveActivity;
11033                        mResolveInfo.priority = 0;
11034                        mResolveInfo.preferredOrder = 0;
11035                        mResolveInfo.match = 0;
11036                        mResolveComponentName = new ComponentName(
11037                                mAndroidApplication.packageName, mResolveActivity.name);
11038                    }
11039                }
11040            }
11041        }
11042
11043        ArrayList<PackageParser.Package> clientLibPkgs = null;
11044        // writer
11045        synchronized (mPackages) {
11046            boolean hasStaticSharedLibs = false;
11047
11048            // Any app can add new static shared libraries
11049            if (pkg.staticSharedLibName != null) {
11050                // Static shared libs don't allow renaming as they have synthetic package
11051                // names to allow install of multiple versions, so use name from manifest.
11052                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11053                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11054                        pkg.manifestPackageName, pkg.mVersionCode)) {
11055                    hasStaticSharedLibs = true;
11056                } else {
11057                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11058                                + pkg.staticSharedLibName + " already exists; skipping");
11059                }
11060                // Static shared libs cannot be updated once installed since they
11061                // use synthetic package name which includes the version code, so
11062                // not need to update other packages's shared lib dependencies.
11063            }
11064
11065            if (!hasStaticSharedLibs
11066                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11067                // Only system apps can add new dynamic shared libraries.
11068                if (pkg.libraryNames != null) {
11069                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11070                        String name = pkg.libraryNames.get(i);
11071                        boolean allowed = false;
11072                        if (pkg.isUpdatedSystemApp()) {
11073                            // New library entries can only be added through the
11074                            // system image.  This is important to get rid of a lot
11075                            // of nasty edge cases: for example if we allowed a non-
11076                            // system update of the app to add a library, then uninstalling
11077                            // the update would make the library go away, and assumptions
11078                            // we made such as through app install filtering would now
11079                            // have allowed apps on the device which aren't compatible
11080                            // with it.  Better to just have the restriction here, be
11081                            // conservative, and create many fewer cases that can negatively
11082                            // impact the user experience.
11083                            final PackageSetting sysPs = mSettings
11084                                    .getDisabledSystemPkgLPr(pkg.packageName);
11085                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11086                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11087                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11088                                        allowed = true;
11089                                        break;
11090                                    }
11091                                }
11092                            }
11093                        } else {
11094                            allowed = true;
11095                        }
11096                        if (allowed) {
11097                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11098                                    SharedLibraryInfo.VERSION_UNDEFINED,
11099                                    SharedLibraryInfo.TYPE_DYNAMIC,
11100                                    pkg.packageName, pkg.mVersionCode)) {
11101                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11102                                        + name + " already exists; skipping");
11103                            }
11104                        } else {
11105                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11106                                    + name + " that is not declared on system image; skipping");
11107                        }
11108                    }
11109
11110                    if ((scanFlags & SCAN_BOOTING) == 0) {
11111                        // If we are not booting, we need to update any applications
11112                        // that are clients of our shared library.  If we are booting,
11113                        // this will all be done once the scan is complete.
11114                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11115                    }
11116                }
11117            }
11118        }
11119
11120        if ((scanFlags & SCAN_BOOTING) != 0) {
11121            // No apps can run during boot scan, so they don't need to be frozen
11122        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11123            // Caller asked to not kill app, so it's probably not frozen
11124        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11125            // Caller asked us to ignore frozen check for some reason; they
11126            // probably didn't know the package name
11127        } else {
11128            // We're doing major surgery on this package, so it better be frozen
11129            // right now to keep it from launching
11130            checkPackageFrozen(pkgName);
11131        }
11132
11133        // Also need to kill any apps that are dependent on the library.
11134        if (clientLibPkgs != null) {
11135            for (int i=0; i<clientLibPkgs.size(); i++) {
11136                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11137                killApplication(clientPkg.applicationInfo.packageName,
11138                        clientPkg.applicationInfo.uid, "update lib");
11139            }
11140        }
11141
11142        // writer
11143        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11144
11145        synchronized (mPackages) {
11146            // We don't expect installation to fail beyond this point
11147
11148            // Add the new setting to mSettings
11149            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11150            // Add the new setting to mPackages
11151            mPackages.put(pkg.applicationInfo.packageName, pkg);
11152            // Make sure we don't accidentally delete its data.
11153            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11154            while (iter.hasNext()) {
11155                PackageCleanItem item = iter.next();
11156                if (pkgName.equals(item.packageName)) {
11157                    iter.remove();
11158                }
11159            }
11160
11161            // Add the package's KeySets to the global KeySetManagerService
11162            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11163            ksms.addScannedPackageLPw(pkg);
11164
11165            int N = pkg.providers.size();
11166            StringBuilder r = null;
11167            int i;
11168            for (i=0; i<N; i++) {
11169                PackageParser.Provider p = pkg.providers.get(i);
11170                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11171                        p.info.processName);
11172                mProviders.addProvider(p);
11173                p.syncable = p.info.isSyncable;
11174                if (p.info.authority != null) {
11175                    String names[] = p.info.authority.split(";");
11176                    p.info.authority = null;
11177                    for (int j = 0; j < names.length; j++) {
11178                        if (j == 1 && p.syncable) {
11179                            // We only want the first authority for a provider to possibly be
11180                            // syncable, so if we already added this provider using a different
11181                            // authority clear the syncable flag. We copy the provider before
11182                            // changing it because the mProviders object contains a reference
11183                            // to a provider that we don't want to change.
11184                            // Only do this for the second authority since the resulting provider
11185                            // object can be the same for all future authorities for this provider.
11186                            p = new PackageParser.Provider(p);
11187                            p.syncable = false;
11188                        }
11189                        if (!mProvidersByAuthority.containsKey(names[j])) {
11190                            mProvidersByAuthority.put(names[j], p);
11191                            if (p.info.authority == null) {
11192                                p.info.authority = names[j];
11193                            } else {
11194                                p.info.authority = p.info.authority + ";" + names[j];
11195                            }
11196                            if (DEBUG_PACKAGE_SCANNING) {
11197                                if (chatty)
11198                                    Log.d(TAG, "Registered content provider: " + names[j]
11199                                            + ", className = " + p.info.name + ", isSyncable = "
11200                                            + p.info.isSyncable);
11201                            }
11202                        } else {
11203                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11204                            Slog.w(TAG, "Skipping provider name " + names[j] +
11205                                    " (in package " + pkg.applicationInfo.packageName +
11206                                    "): name already used by "
11207                                    + ((other != null && other.getComponentName() != null)
11208                                            ? other.getComponentName().getPackageName() : "?"));
11209                        }
11210                    }
11211                }
11212                if (chatty) {
11213                    if (r == null) {
11214                        r = new StringBuilder(256);
11215                    } else {
11216                        r.append(' ');
11217                    }
11218                    r.append(p.info.name);
11219                }
11220            }
11221            if (r != null) {
11222                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11223            }
11224
11225            N = pkg.services.size();
11226            r = null;
11227            for (i=0; i<N; i++) {
11228                PackageParser.Service s = pkg.services.get(i);
11229                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11230                        s.info.processName);
11231                mServices.addService(s);
11232                if (chatty) {
11233                    if (r == null) {
11234                        r = new StringBuilder(256);
11235                    } else {
11236                        r.append(' ');
11237                    }
11238                    r.append(s.info.name);
11239                }
11240            }
11241            if (r != null) {
11242                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11243            }
11244
11245            N = pkg.receivers.size();
11246            r = null;
11247            for (i=0; i<N; i++) {
11248                PackageParser.Activity a = pkg.receivers.get(i);
11249                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11250                        a.info.processName);
11251                mReceivers.addActivity(a, "receiver");
11252                if (chatty) {
11253                    if (r == null) {
11254                        r = new StringBuilder(256);
11255                    } else {
11256                        r.append(' ');
11257                    }
11258                    r.append(a.info.name);
11259                }
11260            }
11261            if (r != null) {
11262                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11263            }
11264
11265            N = pkg.activities.size();
11266            r = null;
11267            for (i=0; i<N; i++) {
11268                PackageParser.Activity a = pkg.activities.get(i);
11269                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11270                        a.info.processName);
11271                mActivities.addActivity(a, "activity");
11272                if (chatty) {
11273                    if (r == null) {
11274                        r = new StringBuilder(256);
11275                    } else {
11276                        r.append(' ');
11277                    }
11278                    r.append(a.info.name);
11279                }
11280            }
11281            if (r != null) {
11282                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11283            }
11284
11285            N = pkg.permissionGroups.size();
11286            r = null;
11287            for (i=0; i<N; i++) {
11288                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11289                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11290                final String curPackageName = cur == null ? null : cur.info.packageName;
11291                // Dont allow ephemeral apps to define new permission groups.
11292                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11293                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11294                            + pg.info.packageName
11295                            + " ignored: instant apps cannot define new permission groups.");
11296                    continue;
11297                }
11298                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11299                if (cur == null || isPackageUpdate) {
11300                    mPermissionGroups.put(pg.info.name, pg);
11301                    if (chatty) {
11302                        if (r == null) {
11303                            r = new StringBuilder(256);
11304                        } else {
11305                            r.append(' ');
11306                        }
11307                        if (isPackageUpdate) {
11308                            r.append("UPD:");
11309                        }
11310                        r.append(pg.info.name);
11311                    }
11312                } else {
11313                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11314                            + pg.info.packageName + " ignored: original from "
11315                            + cur.info.packageName);
11316                    if (chatty) {
11317                        if (r == null) {
11318                            r = new StringBuilder(256);
11319                        } else {
11320                            r.append(' ');
11321                        }
11322                        r.append("DUP:");
11323                        r.append(pg.info.name);
11324                    }
11325                }
11326            }
11327            if (r != null) {
11328                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11329            }
11330
11331            N = pkg.permissions.size();
11332            r = null;
11333            for (i=0; i<N; i++) {
11334                PackageParser.Permission p = pkg.permissions.get(i);
11335
11336                // Dont allow ephemeral apps to define new permissions.
11337                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11338                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11339                            + p.info.packageName
11340                            + " ignored: instant apps cannot define new permissions.");
11341                    continue;
11342                }
11343
11344                // Assume by default that we did not install this permission into the system.
11345                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11346
11347                // Now that permission groups have a special meaning, we ignore permission
11348                // groups for legacy apps to prevent unexpected behavior. In particular,
11349                // permissions for one app being granted to someone just because they happen
11350                // to be in a group defined by another app (before this had no implications).
11351                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11352                    p.group = mPermissionGroups.get(p.info.group);
11353                    // Warn for a permission in an unknown group.
11354                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11355                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11356                                + p.info.packageName + " in an unknown group " + p.info.group);
11357                    }
11358                }
11359
11360                ArrayMap<String, BasePermission> permissionMap =
11361                        p.tree ? mSettings.mPermissionTrees
11362                                : mSettings.mPermissions;
11363                BasePermission bp = permissionMap.get(p.info.name);
11364
11365                // Allow system apps to redefine non-system permissions
11366                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11367                    final boolean currentOwnerIsSystem = (bp.perm != null
11368                            && isSystemApp(bp.perm.owner));
11369                    if (isSystemApp(p.owner)) {
11370                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11371                            // It's a built-in permission and no owner, take ownership now
11372                            bp.packageSetting = pkgSetting;
11373                            bp.perm = p;
11374                            bp.uid = pkg.applicationInfo.uid;
11375                            bp.sourcePackage = p.info.packageName;
11376                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11377                        } else if (!currentOwnerIsSystem) {
11378                            String msg = "New decl " + p.owner + " of permission  "
11379                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11380                            reportSettingsProblem(Log.WARN, msg);
11381                            bp = null;
11382                        }
11383                    }
11384                }
11385
11386                if (bp == null) {
11387                    bp = new BasePermission(p.info.name, p.info.packageName,
11388                            BasePermission.TYPE_NORMAL);
11389                    permissionMap.put(p.info.name, bp);
11390                }
11391
11392                if (bp.perm == null) {
11393                    if (bp.sourcePackage == null
11394                            || bp.sourcePackage.equals(p.info.packageName)) {
11395                        BasePermission tree = findPermissionTreeLP(p.info.name);
11396                        if (tree == null
11397                                || tree.sourcePackage.equals(p.info.packageName)) {
11398                            bp.packageSetting = pkgSetting;
11399                            bp.perm = p;
11400                            bp.uid = pkg.applicationInfo.uid;
11401                            bp.sourcePackage = p.info.packageName;
11402                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11403                            if (chatty) {
11404                                if (r == null) {
11405                                    r = new StringBuilder(256);
11406                                } else {
11407                                    r.append(' ');
11408                                }
11409                                r.append(p.info.name);
11410                            }
11411                        } else {
11412                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11413                                    + p.info.packageName + " ignored: base tree "
11414                                    + tree.name + " is from package "
11415                                    + tree.sourcePackage);
11416                        }
11417                    } else {
11418                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11419                                + p.info.packageName + " ignored: original from "
11420                                + bp.sourcePackage);
11421                    }
11422                } else if (chatty) {
11423                    if (r == null) {
11424                        r = new StringBuilder(256);
11425                    } else {
11426                        r.append(' ');
11427                    }
11428                    r.append("DUP:");
11429                    r.append(p.info.name);
11430                }
11431                if (bp.perm == p) {
11432                    bp.protectionLevel = p.info.protectionLevel;
11433                }
11434            }
11435
11436            if (r != null) {
11437                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11438            }
11439
11440            N = pkg.instrumentation.size();
11441            r = null;
11442            for (i=0; i<N; i++) {
11443                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11444                a.info.packageName = pkg.applicationInfo.packageName;
11445                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11446                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11447                a.info.splitNames = pkg.splitNames;
11448                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11449                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11450                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11451                a.info.dataDir = pkg.applicationInfo.dataDir;
11452                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11453                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11454                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11455                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11456                mInstrumentation.put(a.getComponentName(), a);
11457                if (chatty) {
11458                    if (r == null) {
11459                        r = new StringBuilder(256);
11460                    } else {
11461                        r.append(' ');
11462                    }
11463                    r.append(a.info.name);
11464                }
11465            }
11466            if (r != null) {
11467                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11468            }
11469
11470            if (pkg.protectedBroadcasts != null) {
11471                N = pkg.protectedBroadcasts.size();
11472                synchronized (mProtectedBroadcasts) {
11473                    for (i = 0; i < N; i++) {
11474                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11475                    }
11476                }
11477            }
11478        }
11479
11480        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11481    }
11482
11483    /**
11484     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11485     * is derived purely on the basis of the contents of {@code scanFile} and
11486     * {@code cpuAbiOverride}.
11487     *
11488     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11489     */
11490    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11491                                 String cpuAbiOverride, boolean extractLibs,
11492                                 File appLib32InstallDir)
11493            throws PackageManagerException {
11494        // Give ourselves some initial paths; we'll come back for another
11495        // pass once we've determined ABI below.
11496        setNativeLibraryPaths(pkg, appLib32InstallDir);
11497
11498        // We would never need to extract libs for forward-locked and external packages,
11499        // since the container service will do it for us. We shouldn't attempt to
11500        // extract libs from system app when it was not updated.
11501        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11502                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11503            extractLibs = false;
11504        }
11505
11506        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11507        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11508
11509        NativeLibraryHelper.Handle handle = null;
11510        try {
11511            handle = NativeLibraryHelper.Handle.create(pkg);
11512            // TODO(multiArch): This can be null for apps that didn't go through the
11513            // usual installation process. We can calculate it again, like we
11514            // do during install time.
11515            //
11516            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11517            // unnecessary.
11518            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11519
11520            // Null out the abis so that they can be recalculated.
11521            pkg.applicationInfo.primaryCpuAbi = null;
11522            pkg.applicationInfo.secondaryCpuAbi = null;
11523            if (isMultiArch(pkg.applicationInfo)) {
11524                // Warn if we've set an abiOverride for multi-lib packages..
11525                // By definition, we need to copy both 32 and 64 bit libraries for
11526                // such packages.
11527                if (pkg.cpuAbiOverride != null
11528                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11529                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11530                }
11531
11532                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11533                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11534                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11535                    if (extractLibs) {
11536                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11537                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11538                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11539                                useIsaSpecificSubdirs);
11540                    } else {
11541                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11542                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11543                    }
11544                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11545                }
11546
11547                // Shared library native code should be in the APK zip aligned
11548                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11549                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11550                            "Shared library native lib extraction not supported");
11551                }
11552
11553                maybeThrowExceptionForMultiArchCopy(
11554                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11555
11556                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11557                    if (extractLibs) {
11558                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11559                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11560                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11561                                useIsaSpecificSubdirs);
11562                    } else {
11563                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11564                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11565                    }
11566                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11567                }
11568
11569                maybeThrowExceptionForMultiArchCopy(
11570                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11571
11572                if (abi64 >= 0) {
11573                    // Shared library native libs should be in the APK zip aligned
11574                    if (extractLibs && pkg.isLibrary()) {
11575                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11576                                "Shared library native lib extraction not supported");
11577                    }
11578                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11579                }
11580
11581                if (abi32 >= 0) {
11582                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11583                    if (abi64 >= 0) {
11584                        if (pkg.use32bitAbi) {
11585                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11586                            pkg.applicationInfo.primaryCpuAbi = abi;
11587                        } else {
11588                            pkg.applicationInfo.secondaryCpuAbi = abi;
11589                        }
11590                    } else {
11591                        pkg.applicationInfo.primaryCpuAbi = abi;
11592                    }
11593                }
11594            } else {
11595                String[] abiList = (cpuAbiOverride != null) ?
11596                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11597
11598                // Enable gross and lame hacks for apps that are built with old
11599                // SDK tools. We must scan their APKs for renderscript bitcode and
11600                // not launch them if it's present. Don't bother checking on devices
11601                // that don't have 64 bit support.
11602                boolean needsRenderScriptOverride = false;
11603                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11604                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11605                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11606                    needsRenderScriptOverride = true;
11607                }
11608
11609                final int copyRet;
11610                if (extractLibs) {
11611                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11612                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11613                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11614                } else {
11615                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11616                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11617                }
11618                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11619
11620                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11621                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11622                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11623                }
11624
11625                if (copyRet >= 0) {
11626                    // Shared libraries that have native libs must be multi-architecture
11627                    if (pkg.isLibrary()) {
11628                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11629                                "Shared library with native libs must be multiarch");
11630                    }
11631                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11632                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11633                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11634                } else if (needsRenderScriptOverride) {
11635                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11636                }
11637            }
11638        } catch (IOException ioe) {
11639            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11640        } finally {
11641            IoUtils.closeQuietly(handle);
11642        }
11643
11644        // Now that we've calculated the ABIs and determined if it's an internal app,
11645        // we will go ahead and populate the nativeLibraryPath.
11646        setNativeLibraryPaths(pkg, appLib32InstallDir);
11647    }
11648
11649    /**
11650     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11651     * i.e, so that all packages can be run inside a single process if required.
11652     *
11653     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11654     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11655     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11656     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11657     * updating a package that belongs to a shared user.
11658     *
11659     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11660     * adds unnecessary complexity.
11661     */
11662    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11663            PackageParser.Package scannedPackage) {
11664        String requiredInstructionSet = null;
11665        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11666            requiredInstructionSet = VMRuntime.getInstructionSet(
11667                     scannedPackage.applicationInfo.primaryCpuAbi);
11668        }
11669
11670        PackageSetting requirer = null;
11671        for (PackageSetting ps : packagesForUser) {
11672            // If packagesForUser contains scannedPackage, we skip it. This will happen
11673            // when scannedPackage is an update of an existing package. Without this check,
11674            // we will never be able to change the ABI of any package belonging to a shared
11675            // user, even if it's compatible with other packages.
11676            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11677                if (ps.primaryCpuAbiString == null) {
11678                    continue;
11679                }
11680
11681                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11682                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11683                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11684                    // this but there's not much we can do.
11685                    String errorMessage = "Instruction set mismatch, "
11686                            + ((requirer == null) ? "[caller]" : requirer)
11687                            + " requires " + requiredInstructionSet + " whereas " + ps
11688                            + " requires " + instructionSet;
11689                    Slog.w(TAG, errorMessage);
11690                }
11691
11692                if (requiredInstructionSet == null) {
11693                    requiredInstructionSet = instructionSet;
11694                    requirer = ps;
11695                }
11696            }
11697        }
11698
11699        if (requiredInstructionSet != null) {
11700            String adjustedAbi;
11701            if (requirer != null) {
11702                // requirer != null implies that either scannedPackage was null or that scannedPackage
11703                // did not require an ABI, in which case we have to adjust scannedPackage to match
11704                // the ABI of the set (which is the same as requirer's ABI)
11705                adjustedAbi = requirer.primaryCpuAbiString;
11706                if (scannedPackage != null) {
11707                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11708                }
11709            } else {
11710                // requirer == null implies that we're updating all ABIs in the set to
11711                // match scannedPackage.
11712                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11713            }
11714
11715            for (PackageSetting ps : packagesForUser) {
11716                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11717                    if (ps.primaryCpuAbiString != null) {
11718                        continue;
11719                    }
11720
11721                    ps.primaryCpuAbiString = adjustedAbi;
11722                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11723                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11724                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11725                        if (DEBUG_ABI_SELECTION) {
11726                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11727                                    + " (requirer="
11728                                    + (requirer != null ? requirer.pkg : "null")
11729                                    + ", scannedPackage="
11730                                    + (scannedPackage != null ? scannedPackage : "null")
11731                                    + ")");
11732                        }
11733                        try {
11734                            mInstaller.rmdex(ps.codePathString,
11735                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11736                        } catch (InstallerException ignored) {
11737                        }
11738                    }
11739                }
11740            }
11741        }
11742    }
11743
11744    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11745        synchronized (mPackages) {
11746            mResolverReplaced = true;
11747            // Set up information for custom user intent resolution activity.
11748            mResolveActivity.applicationInfo = pkg.applicationInfo;
11749            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11750            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11751            mResolveActivity.processName = pkg.applicationInfo.packageName;
11752            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11753            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11754                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11755            mResolveActivity.theme = 0;
11756            mResolveActivity.exported = true;
11757            mResolveActivity.enabled = true;
11758            mResolveInfo.activityInfo = mResolveActivity;
11759            mResolveInfo.priority = 0;
11760            mResolveInfo.preferredOrder = 0;
11761            mResolveInfo.match = 0;
11762            mResolveComponentName = mCustomResolverComponentName;
11763            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11764                    mResolveComponentName);
11765        }
11766    }
11767
11768    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11769        if (installerActivity == null) {
11770            if (DEBUG_EPHEMERAL) {
11771                Slog.d(TAG, "Clear ephemeral installer activity");
11772            }
11773            mInstantAppInstallerActivity = null;
11774            return;
11775        }
11776
11777        if (DEBUG_EPHEMERAL) {
11778            Slog.d(TAG, "Set ephemeral installer activity: "
11779                    + installerActivity.getComponentName());
11780        }
11781        // Set up information for ephemeral installer activity
11782        mInstantAppInstallerActivity = installerActivity;
11783        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11784                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11785        mInstantAppInstallerActivity.exported = true;
11786        mInstantAppInstallerActivity.enabled = true;
11787        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11788        mInstantAppInstallerInfo.priority = 0;
11789        mInstantAppInstallerInfo.preferredOrder = 1;
11790        mInstantAppInstallerInfo.isDefault = true;
11791        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11792                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11793    }
11794
11795    private static String calculateBundledApkRoot(final String codePathString) {
11796        final File codePath = new File(codePathString);
11797        final File codeRoot;
11798        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11799            codeRoot = Environment.getRootDirectory();
11800        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11801            codeRoot = Environment.getOemDirectory();
11802        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11803            codeRoot = Environment.getVendorDirectory();
11804        } else {
11805            // Unrecognized code path; take its top real segment as the apk root:
11806            // e.g. /something/app/blah.apk => /something
11807            try {
11808                File f = codePath.getCanonicalFile();
11809                File parent = f.getParentFile();    // non-null because codePath is a file
11810                File tmp;
11811                while ((tmp = parent.getParentFile()) != null) {
11812                    f = parent;
11813                    parent = tmp;
11814                }
11815                codeRoot = f;
11816                Slog.w(TAG, "Unrecognized code path "
11817                        + codePath + " - using " + codeRoot);
11818            } catch (IOException e) {
11819                // Can't canonicalize the code path -- shenanigans?
11820                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11821                return Environment.getRootDirectory().getPath();
11822            }
11823        }
11824        return codeRoot.getPath();
11825    }
11826
11827    /**
11828     * Derive and set the location of native libraries for the given package,
11829     * which varies depending on where and how the package was installed.
11830     */
11831    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11832        final ApplicationInfo info = pkg.applicationInfo;
11833        final String codePath = pkg.codePath;
11834        final File codeFile = new File(codePath);
11835        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11836        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11837
11838        info.nativeLibraryRootDir = null;
11839        info.nativeLibraryRootRequiresIsa = false;
11840        info.nativeLibraryDir = null;
11841        info.secondaryNativeLibraryDir = null;
11842
11843        if (isApkFile(codeFile)) {
11844            // Monolithic install
11845            if (bundledApp) {
11846                // If "/system/lib64/apkname" exists, assume that is the per-package
11847                // native library directory to use; otherwise use "/system/lib/apkname".
11848                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11849                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11850                        getPrimaryInstructionSet(info));
11851
11852                // This is a bundled system app so choose the path based on the ABI.
11853                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11854                // is just the default path.
11855                final String apkName = deriveCodePathName(codePath);
11856                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11857                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11858                        apkName).getAbsolutePath();
11859
11860                if (info.secondaryCpuAbi != null) {
11861                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11862                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11863                            secondaryLibDir, apkName).getAbsolutePath();
11864                }
11865            } else if (asecApp) {
11866                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11867                        .getAbsolutePath();
11868            } else {
11869                final String apkName = deriveCodePathName(codePath);
11870                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11871                        .getAbsolutePath();
11872            }
11873
11874            info.nativeLibraryRootRequiresIsa = false;
11875            info.nativeLibraryDir = info.nativeLibraryRootDir;
11876        } else {
11877            // Cluster install
11878            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11879            info.nativeLibraryRootRequiresIsa = true;
11880
11881            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11882                    getPrimaryInstructionSet(info)).getAbsolutePath();
11883
11884            if (info.secondaryCpuAbi != null) {
11885                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11886                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11887            }
11888        }
11889    }
11890
11891    /**
11892     * Calculate the abis and roots for a bundled app. These can uniquely
11893     * be determined from the contents of the system partition, i.e whether
11894     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11895     * of this information, and instead assume that the system was built
11896     * sensibly.
11897     */
11898    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11899                                           PackageSetting pkgSetting) {
11900        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11901
11902        // If "/system/lib64/apkname" exists, assume that is the per-package
11903        // native library directory to use; otherwise use "/system/lib/apkname".
11904        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11905        setBundledAppAbi(pkg, apkRoot, apkName);
11906        // pkgSetting might be null during rescan following uninstall of updates
11907        // to a bundled app, so accommodate that possibility.  The settings in
11908        // that case will be established later from the parsed package.
11909        //
11910        // If the settings aren't null, sync them up with what we've just derived.
11911        // note that apkRoot isn't stored in the package settings.
11912        if (pkgSetting != null) {
11913            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11914            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11915        }
11916    }
11917
11918    /**
11919     * Deduces the ABI of a bundled app and sets the relevant fields on the
11920     * parsed pkg object.
11921     *
11922     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11923     *        under which system libraries are installed.
11924     * @param apkName the name of the installed package.
11925     */
11926    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11927        final File codeFile = new File(pkg.codePath);
11928
11929        final boolean has64BitLibs;
11930        final boolean has32BitLibs;
11931        if (isApkFile(codeFile)) {
11932            // Monolithic install
11933            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11934            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11935        } else {
11936            // Cluster install
11937            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11938            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11939                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11940                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11941                has64BitLibs = (new File(rootDir, isa)).exists();
11942            } else {
11943                has64BitLibs = false;
11944            }
11945            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11946                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11947                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11948                has32BitLibs = (new File(rootDir, isa)).exists();
11949            } else {
11950                has32BitLibs = false;
11951            }
11952        }
11953
11954        if (has64BitLibs && !has32BitLibs) {
11955            // The package has 64 bit libs, but not 32 bit libs. Its primary
11956            // ABI should be 64 bit. We can safely assume here that the bundled
11957            // native libraries correspond to the most preferred ABI in the list.
11958
11959            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11960            pkg.applicationInfo.secondaryCpuAbi = null;
11961        } else if (has32BitLibs && !has64BitLibs) {
11962            // The package has 32 bit libs but not 64 bit libs. Its primary
11963            // ABI should be 32 bit.
11964
11965            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11966            pkg.applicationInfo.secondaryCpuAbi = null;
11967        } else if (has32BitLibs && has64BitLibs) {
11968            // The application has both 64 and 32 bit bundled libraries. We check
11969            // here that the app declares multiArch support, and warn if it doesn't.
11970            //
11971            // We will be lenient here and record both ABIs. The primary will be the
11972            // ABI that's higher on the list, i.e, a device that's configured to prefer
11973            // 64 bit apps will see a 64 bit primary ABI,
11974
11975            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11976                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11977            }
11978
11979            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11980                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11981                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11982            } else {
11983                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11984                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11985            }
11986        } else {
11987            pkg.applicationInfo.primaryCpuAbi = null;
11988            pkg.applicationInfo.secondaryCpuAbi = null;
11989        }
11990    }
11991
11992    private void killApplication(String pkgName, int appId, String reason) {
11993        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11994    }
11995
11996    private void killApplication(String pkgName, int appId, int userId, String reason) {
11997        // Request the ActivityManager to kill the process(only for existing packages)
11998        // so that we do not end up in a confused state while the user is still using the older
11999        // version of the application while the new one gets installed.
12000        final long token = Binder.clearCallingIdentity();
12001        try {
12002            IActivityManager am = ActivityManager.getService();
12003            if (am != null) {
12004                try {
12005                    am.killApplication(pkgName, appId, userId, reason);
12006                } catch (RemoteException e) {
12007                }
12008            }
12009        } finally {
12010            Binder.restoreCallingIdentity(token);
12011        }
12012    }
12013
12014    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12015        // Remove the parent package setting
12016        PackageSetting ps = (PackageSetting) pkg.mExtras;
12017        if (ps != null) {
12018            removePackageLI(ps, chatty);
12019        }
12020        // Remove the child package setting
12021        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12022        for (int i = 0; i < childCount; i++) {
12023            PackageParser.Package childPkg = pkg.childPackages.get(i);
12024            ps = (PackageSetting) childPkg.mExtras;
12025            if (ps != null) {
12026                removePackageLI(ps, chatty);
12027            }
12028        }
12029    }
12030
12031    void removePackageLI(PackageSetting ps, boolean chatty) {
12032        if (DEBUG_INSTALL) {
12033            if (chatty)
12034                Log.d(TAG, "Removing package " + ps.name);
12035        }
12036
12037        // writer
12038        synchronized (mPackages) {
12039            mPackages.remove(ps.name);
12040            final PackageParser.Package pkg = ps.pkg;
12041            if (pkg != null) {
12042                cleanPackageDataStructuresLILPw(pkg, chatty);
12043            }
12044        }
12045    }
12046
12047    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12048        if (DEBUG_INSTALL) {
12049            if (chatty)
12050                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12051        }
12052
12053        // writer
12054        synchronized (mPackages) {
12055            // Remove the parent package
12056            mPackages.remove(pkg.applicationInfo.packageName);
12057            cleanPackageDataStructuresLILPw(pkg, chatty);
12058
12059            // Remove the child packages
12060            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12061            for (int i = 0; i < childCount; i++) {
12062                PackageParser.Package childPkg = pkg.childPackages.get(i);
12063                mPackages.remove(childPkg.applicationInfo.packageName);
12064                cleanPackageDataStructuresLILPw(childPkg, chatty);
12065            }
12066        }
12067    }
12068
12069    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12070        int N = pkg.providers.size();
12071        StringBuilder r = null;
12072        int i;
12073        for (i=0; i<N; i++) {
12074            PackageParser.Provider p = pkg.providers.get(i);
12075            mProviders.removeProvider(p);
12076            if (p.info.authority == null) {
12077
12078                /* There was another ContentProvider with this authority when
12079                 * this app was installed so this authority is null,
12080                 * Ignore it as we don't have to unregister the provider.
12081                 */
12082                continue;
12083            }
12084            String names[] = p.info.authority.split(";");
12085            for (int j = 0; j < names.length; j++) {
12086                if (mProvidersByAuthority.get(names[j]) == p) {
12087                    mProvidersByAuthority.remove(names[j]);
12088                    if (DEBUG_REMOVE) {
12089                        if (chatty)
12090                            Log.d(TAG, "Unregistered content provider: " + names[j]
12091                                    + ", className = " + p.info.name + ", isSyncable = "
12092                                    + p.info.isSyncable);
12093                    }
12094                }
12095            }
12096            if (DEBUG_REMOVE && chatty) {
12097                if (r == null) {
12098                    r = new StringBuilder(256);
12099                } else {
12100                    r.append(' ');
12101                }
12102                r.append(p.info.name);
12103            }
12104        }
12105        if (r != null) {
12106            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12107        }
12108
12109        N = pkg.services.size();
12110        r = null;
12111        for (i=0; i<N; i++) {
12112            PackageParser.Service s = pkg.services.get(i);
12113            mServices.removeService(s);
12114            if (chatty) {
12115                if (r == null) {
12116                    r = new StringBuilder(256);
12117                } else {
12118                    r.append(' ');
12119                }
12120                r.append(s.info.name);
12121            }
12122        }
12123        if (r != null) {
12124            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12125        }
12126
12127        N = pkg.receivers.size();
12128        r = null;
12129        for (i=0; i<N; i++) {
12130            PackageParser.Activity a = pkg.receivers.get(i);
12131            mReceivers.removeActivity(a, "receiver");
12132            if (DEBUG_REMOVE && chatty) {
12133                if (r == null) {
12134                    r = new StringBuilder(256);
12135                } else {
12136                    r.append(' ');
12137                }
12138                r.append(a.info.name);
12139            }
12140        }
12141        if (r != null) {
12142            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12143        }
12144
12145        N = pkg.activities.size();
12146        r = null;
12147        for (i=0; i<N; i++) {
12148            PackageParser.Activity a = pkg.activities.get(i);
12149            mActivities.removeActivity(a, "activity");
12150            if (DEBUG_REMOVE && chatty) {
12151                if (r == null) {
12152                    r = new StringBuilder(256);
12153                } else {
12154                    r.append(' ');
12155                }
12156                r.append(a.info.name);
12157            }
12158        }
12159        if (r != null) {
12160            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12161        }
12162
12163        N = pkg.permissions.size();
12164        r = null;
12165        for (i=0; i<N; i++) {
12166            PackageParser.Permission p = pkg.permissions.get(i);
12167            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12168            if (bp == null) {
12169                bp = mSettings.mPermissionTrees.get(p.info.name);
12170            }
12171            if (bp != null && bp.perm == p) {
12172                bp.perm = null;
12173                if (DEBUG_REMOVE && chatty) {
12174                    if (r == null) {
12175                        r = new StringBuilder(256);
12176                    } else {
12177                        r.append(' ');
12178                    }
12179                    r.append(p.info.name);
12180                }
12181            }
12182            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12183                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12184                if (appOpPkgs != null) {
12185                    appOpPkgs.remove(pkg.packageName);
12186                }
12187            }
12188        }
12189        if (r != null) {
12190            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12191        }
12192
12193        N = pkg.requestedPermissions.size();
12194        r = null;
12195        for (i=0; i<N; i++) {
12196            String perm = pkg.requestedPermissions.get(i);
12197            BasePermission bp = mSettings.mPermissions.get(perm);
12198            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12199                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12200                if (appOpPkgs != null) {
12201                    appOpPkgs.remove(pkg.packageName);
12202                    if (appOpPkgs.isEmpty()) {
12203                        mAppOpPermissionPackages.remove(perm);
12204                    }
12205                }
12206            }
12207        }
12208        if (r != null) {
12209            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12210        }
12211
12212        N = pkg.instrumentation.size();
12213        r = null;
12214        for (i=0; i<N; i++) {
12215            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12216            mInstrumentation.remove(a.getComponentName());
12217            if (DEBUG_REMOVE && chatty) {
12218                if (r == null) {
12219                    r = new StringBuilder(256);
12220                } else {
12221                    r.append(' ');
12222                }
12223                r.append(a.info.name);
12224            }
12225        }
12226        if (r != null) {
12227            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12228        }
12229
12230        r = null;
12231        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12232            // Only system apps can hold shared libraries.
12233            if (pkg.libraryNames != null) {
12234                for (i = 0; i < pkg.libraryNames.size(); i++) {
12235                    String name = pkg.libraryNames.get(i);
12236                    if (removeSharedLibraryLPw(name, 0)) {
12237                        if (DEBUG_REMOVE && chatty) {
12238                            if (r == null) {
12239                                r = new StringBuilder(256);
12240                            } else {
12241                                r.append(' ');
12242                            }
12243                            r.append(name);
12244                        }
12245                    }
12246                }
12247            }
12248        }
12249
12250        r = null;
12251
12252        // Any package can hold static shared libraries.
12253        if (pkg.staticSharedLibName != null) {
12254            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12255                if (DEBUG_REMOVE && chatty) {
12256                    if (r == null) {
12257                        r = new StringBuilder(256);
12258                    } else {
12259                        r.append(' ');
12260                    }
12261                    r.append(pkg.staticSharedLibName);
12262                }
12263            }
12264        }
12265
12266        if (r != null) {
12267            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12268        }
12269    }
12270
12271    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12272        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12273            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12274                return true;
12275            }
12276        }
12277        return false;
12278    }
12279
12280    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12281    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12282    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12283
12284    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12285        // Update the parent permissions
12286        updatePermissionsLPw(pkg.packageName, pkg, flags);
12287        // Update the child permissions
12288        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12289        for (int i = 0; i < childCount; i++) {
12290            PackageParser.Package childPkg = pkg.childPackages.get(i);
12291            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12292        }
12293    }
12294
12295    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12296            int flags) {
12297        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12298        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12299    }
12300
12301    private void updatePermissionsLPw(String changingPkg,
12302            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12303        // Make sure there are no dangling permission trees.
12304        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12305        while (it.hasNext()) {
12306            final BasePermission bp = it.next();
12307            if (bp.packageSetting == null) {
12308                // We may not yet have parsed the package, so just see if
12309                // we still know about its settings.
12310                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12311            }
12312            if (bp.packageSetting == null) {
12313                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12314                        + " from package " + bp.sourcePackage);
12315                it.remove();
12316            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12317                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12318                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12319                            + " from package " + bp.sourcePackage);
12320                    flags |= UPDATE_PERMISSIONS_ALL;
12321                    it.remove();
12322                }
12323            }
12324        }
12325
12326        // Make sure all dynamic permissions have been assigned to a package,
12327        // and make sure there are no dangling permissions.
12328        it = mSettings.mPermissions.values().iterator();
12329        while (it.hasNext()) {
12330            final BasePermission bp = it.next();
12331            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12332                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12333                        + bp.name + " pkg=" + bp.sourcePackage
12334                        + " info=" + bp.pendingInfo);
12335                if (bp.packageSetting == null && bp.pendingInfo != null) {
12336                    final BasePermission tree = findPermissionTreeLP(bp.name);
12337                    if (tree != null && tree.perm != null) {
12338                        bp.packageSetting = tree.packageSetting;
12339                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12340                                new PermissionInfo(bp.pendingInfo));
12341                        bp.perm.info.packageName = tree.perm.info.packageName;
12342                        bp.perm.info.name = bp.name;
12343                        bp.uid = tree.uid;
12344                    }
12345                }
12346            }
12347            if (bp.packageSetting == null) {
12348                // We may not yet have parsed the package, so just see if
12349                // we still know about its settings.
12350                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12351            }
12352            if (bp.packageSetting == null) {
12353                Slog.w(TAG, "Removing dangling permission: " + bp.name
12354                        + " from package " + bp.sourcePackage);
12355                it.remove();
12356            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12357                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12358                    Slog.i(TAG, "Removing old permission: " + bp.name
12359                            + " from package " + bp.sourcePackage);
12360                    flags |= UPDATE_PERMISSIONS_ALL;
12361                    it.remove();
12362                }
12363            }
12364        }
12365
12366        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12367        // Now update the permissions for all packages, in particular
12368        // replace the granted permissions of the system packages.
12369        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12370            for (PackageParser.Package pkg : mPackages.values()) {
12371                if (pkg != pkgInfo) {
12372                    // Only replace for packages on requested volume
12373                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12374                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12375                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12376                    grantPermissionsLPw(pkg, replace, changingPkg);
12377                }
12378            }
12379        }
12380
12381        if (pkgInfo != null) {
12382            // Only replace for packages on requested volume
12383            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12384            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12385                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12386            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12387        }
12388        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12389    }
12390
12391    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12392            String packageOfInterest) {
12393        // IMPORTANT: There are two types of permissions: install and runtime.
12394        // Install time permissions are granted when the app is installed to
12395        // all device users and users added in the future. Runtime permissions
12396        // are granted at runtime explicitly to specific users. Normal and signature
12397        // protected permissions are install time permissions. Dangerous permissions
12398        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12399        // otherwise they are runtime permissions. This function does not manage
12400        // runtime permissions except for the case an app targeting Lollipop MR1
12401        // being upgraded to target a newer SDK, in which case dangerous permissions
12402        // are transformed from install time to runtime ones.
12403
12404        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12405        if (ps == null) {
12406            return;
12407        }
12408
12409        PermissionsState permissionsState = ps.getPermissionsState();
12410        PermissionsState origPermissions = permissionsState;
12411
12412        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12413
12414        boolean runtimePermissionsRevoked = false;
12415        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12416
12417        boolean changedInstallPermission = false;
12418
12419        if (replace) {
12420            ps.installPermissionsFixed = false;
12421            if (!ps.isSharedUser()) {
12422                origPermissions = new PermissionsState(permissionsState);
12423                permissionsState.reset();
12424            } else {
12425                // We need to know only about runtime permission changes since the
12426                // calling code always writes the install permissions state but
12427                // the runtime ones are written only if changed. The only cases of
12428                // changed runtime permissions here are promotion of an install to
12429                // runtime and revocation of a runtime from a shared user.
12430                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12431                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12432                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12433                    runtimePermissionsRevoked = true;
12434                }
12435            }
12436        }
12437
12438        permissionsState.setGlobalGids(mGlobalGids);
12439
12440        final int N = pkg.requestedPermissions.size();
12441        for (int i=0; i<N; i++) {
12442            final String name = pkg.requestedPermissions.get(i);
12443            final BasePermission bp = mSettings.mPermissions.get(name);
12444            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12445                    >= Build.VERSION_CODES.M;
12446
12447            if (DEBUG_INSTALL) {
12448                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12449            }
12450
12451            if (bp == null || bp.packageSetting == null) {
12452                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12453                    if (DEBUG_PERMISSIONS) {
12454                        Slog.i(TAG, "Unknown permission " + name
12455                                + " in package " + pkg.packageName);
12456                    }
12457                }
12458                continue;
12459            }
12460
12461
12462            // Limit ephemeral apps to ephemeral allowed permissions.
12463            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12464                if (DEBUG_PERMISSIONS) {
12465                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12466                            + pkg.packageName);
12467                }
12468                continue;
12469            }
12470
12471            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12472                if (DEBUG_PERMISSIONS) {
12473                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12474                            + pkg.packageName);
12475                }
12476                continue;
12477            }
12478
12479            final String perm = bp.name;
12480            boolean allowedSig = false;
12481            int grant = GRANT_DENIED;
12482
12483            // Keep track of app op permissions.
12484            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12485                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12486                if (pkgs == null) {
12487                    pkgs = new ArraySet<>();
12488                    mAppOpPermissionPackages.put(bp.name, pkgs);
12489                }
12490                pkgs.add(pkg.packageName);
12491            }
12492
12493            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12494            switch (level) {
12495                case PermissionInfo.PROTECTION_NORMAL: {
12496                    // For all apps normal permissions are install time ones.
12497                    grant = GRANT_INSTALL;
12498                } break;
12499
12500                case PermissionInfo.PROTECTION_DANGEROUS: {
12501                    // If a permission review is required for legacy apps we represent
12502                    // their permissions as always granted runtime ones since we need
12503                    // to keep the review required permission flag per user while an
12504                    // install permission's state is shared across all users.
12505                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12506                        // For legacy apps dangerous permissions are install time ones.
12507                        grant = GRANT_INSTALL;
12508                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12509                        // For legacy apps that became modern, install becomes runtime.
12510                        grant = GRANT_UPGRADE;
12511                    } else if (mPromoteSystemApps
12512                            && isSystemApp(ps)
12513                            && mExistingSystemPackages.contains(ps.name)) {
12514                        // For legacy system apps, install becomes runtime.
12515                        // We cannot check hasInstallPermission() for system apps since those
12516                        // permissions were granted implicitly and not persisted pre-M.
12517                        grant = GRANT_UPGRADE;
12518                    } else {
12519                        // For modern apps keep runtime permissions unchanged.
12520                        grant = GRANT_RUNTIME;
12521                    }
12522                } break;
12523
12524                case PermissionInfo.PROTECTION_SIGNATURE: {
12525                    // For all apps signature permissions are install time ones.
12526                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12527                    if (allowedSig) {
12528                        grant = GRANT_INSTALL;
12529                    }
12530                } break;
12531            }
12532
12533            if (DEBUG_PERMISSIONS) {
12534                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12535            }
12536
12537            if (grant != GRANT_DENIED) {
12538                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12539                    // If this is an existing, non-system package, then
12540                    // we can't add any new permissions to it.
12541                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12542                        // Except...  if this is a permission that was added
12543                        // to the platform (note: need to only do this when
12544                        // updating the platform).
12545                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12546                            grant = GRANT_DENIED;
12547                        }
12548                    }
12549                }
12550
12551                switch (grant) {
12552                    case GRANT_INSTALL: {
12553                        // Revoke this as runtime permission to handle the case of
12554                        // a runtime permission being downgraded to an install one.
12555                        // Also in permission review mode we keep dangerous permissions
12556                        // for legacy apps
12557                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12558                            if (origPermissions.getRuntimePermissionState(
12559                                    bp.name, userId) != null) {
12560                                // Revoke the runtime permission and clear the flags.
12561                                origPermissions.revokeRuntimePermission(bp, userId);
12562                                origPermissions.updatePermissionFlags(bp, userId,
12563                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12564                                // If we revoked a permission permission, we have to write.
12565                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12566                                        changedRuntimePermissionUserIds, userId);
12567                            }
12568                        }
12569                        // Grant an install permission.
12570                        if (permissionsState.grantInstallPermission(bp) !=
12571                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12572                            changedInstallPermission = true;
12573                        }
12574                    } break;
12575
12576                    case GRANT_RUNTIME: {
12577                        // Grant previously granted runtime permissions.
12578                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12579                            PermissionState permissionState = origPermissions
12580                                    .getRuntimePermissionState(bp.name, userId);
12581                            int flags = permissionState != null
12582                                    ? permissionState.getFlags() : 0;
12583                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12584                                // Don't propagate the permission in a permission review mode if
12585                                // the former was revoked, i.e. marked to not propagate on upgrade.
12586                                // Note that in a permission review mode install permissions are
12587                                // represented as constantly granted runtime ones since we need to
12588                                // keep a per user state associated with the permission. Also the
12589                                // revoke on upgrade flag is no longer applicable and is reset.
12590                                final boolean revokeOnUpgrade = (flags & PackageManager
12591                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12592                                if (revokeOnUpgrade) {
12593                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12594                                    // Since we changed the flags, we have to write.
12595                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12596                                            changedRuntimePermissionUserIds, userId);
12597                                }
12598                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12599                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12600                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12601                                        // If we cannot put the permission as it was,
12602                                        // we have to write.
12603                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12604                                                changedRuntimePermissionUserIds, userId);
12605                                    }
12606                                }
12607
12608                                // If the app supports runtime permissions no need for a review.
12609                                if (mPermissionReviewRequired
12610                                        && appSupportsRuntimePermissions
12611                                        && (flags & PackageManager
12612                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12613                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12614                                    // Since we changed the flags, we have to write.
12615                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12616                                            changedRuntimePermissionUserIds, userId);
12617                                }
12618                            } else if (mPermissionReviewRequired
12619                                    && !appSupportsRuntimePermissions) {
12620                                // For legacy apps that need a permission review, every new
12621                                // runtime permission is granted but it is pending a review.
12622                                // We also need to review only platform defined runtime
12623                                // permissions as these are the only ones the platform knows
12624                                // how to disable the API to simulate revocation as legacy
12625                                // apps don't expect to run with revoked permissions.
12626                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12627                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12628                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12629                                        // We changed the flags, hence have to write.
12630                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12631                                                changedRuntimePermissionUserIds, userId);
12632                                    }
12633                                }
12634                                if (permissionsState.grantRuntimePermission(bp, userId)
12635                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12636                                    // We changed the permission, hence have to write.
12637                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12638                                            changedRuntimePermissionUserIds, userId);
12639                                }
12640                            }
12641                            // Propagate the permission flags.
12642                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12643                        }
12644                    } break;
12645
12646                    case GRANT_UPGRADE: {
12647                        // Grant runtime permissions for a previously held install permission.
12648                        PermissionState permissionState = origPermissions
12649                                .getInstallPermissionState(bp.name);
12650                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12651
12652                        if (origPermissions.revokeInstallPermission(bp)
12653                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12654                            // We will be transferring the permission flags, so clear them.
12655                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12656                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12657                            changedInstallPermission = true;
12658                        }
12659
12660                        // If the permission is not to be promoted to runtime we ignore it and
12661                        // also its other flags as they are not applicable to install permissions.
12662                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12663                            for (int userId : currentUserIds) {
12664                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12665                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12666                                    // Transfer the permission flags.
12667                                    permissionsState.updatePermissionFlags(bp, userId,
12668                                            flags, flags);
12669                                    // If we granted the permission, we have to write.
12670                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12671                                            changedRuntimePermissionUserIds, userId);
12672                                }
12673                            }
12674                        }
12675                    } break;
12676
12677                    default: {
12678                        if (packageOfInterest == null
12679                                || packageOfInterest.equals(pkg.packageName)) {
12680                            if (DEBUG_PERMISSIONS) {
12681                                Slog.i(TAG, "Not granting permission " + perm
12682                                        + " to package " + pkg.packageName
12683                                        + " because it was previously installed without");
12684                            }
12685                        }
12686                    } break;
12687                }
12688            } else {
12689                if (permissionsState.revokeInstallPermission(bp) !=
12690                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12691                    // Also drop the permission flags.
12692                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12693                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12694                    changedInstallPermission = true;
12695                    Slog.i(TAG, "Un-granting permission " + perm
12696                            + " from package " + pkg.packageName
12697                            + " (protectionLevel=" + bp.protectionLevel
12698                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12699                            + ")");
12700                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12701                    // Don't print warning for app op permissions, since it is fine for them
12702                    // not to be granted, there is a UI for the user to decide.
12703                    if (DEBUG_PERMISSIONS
12704                            && (packageOfInterest == null
12705                                    || packageOfInterest.equals(pkg.packageName))) {
12706                        Slog.i(TAG, "Not granting permission " + perm
12707                                + " to package " + pkg.packageName
12708                                + " (protectionLevel=" + bp.protectionLevel
12709                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12710                                + ")");
12711                    }
12712                }
12713            }
12714        }
12715
12716        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12717                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12718            // This is the first that we have heard about this package, so the
12719            // permissions we have now selected are fixed until explicitly
12720            // changed.
12721            ps.installPermissionsFixed = true;
12722        }
12723
12724        // Persist the runtime permissions state for users with changes. If permissions
12725        // were revoked because no app in the shared user declares them we have to
12726        // write synchronously to avoid losing runtime permissions state.
12727        for (int userId : changedRuntimePermissionUserIds) {
12728            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12729        }
12730    }
12731
12732    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12733        boolean allowed = false;
12734        final int NP = PackageParser.NEW_PERMISSIONS.length;
12735        for (int ip=0; ip<NP; ip++) {
12736            final PackageParser.NewPermissionInfo npi
12737                    = PackageParser.NEW_PERMISSIONS[ip];
12738            if (npi.name.equals(perm)
12739                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12740                allowed = true;
12741                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12742                        + pkg.packageName);
12743                break;
12744            }
12745        }
12746        return allowed;
12747    }
12748
12749    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12750            BasePermission bp, PermissionsState origPermissions) {
12751        boolean privilegedPermission = (bp.protectionLevel
12752                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12753        boolean privappPermissionsDisable =
12754                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12755        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12756        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12757        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12758                && !platformPackage && platformPermission) {
12759            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12760                    .getPrivAppPermissions(pkg.packageName);
12761            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12762            if (!whitelisted) {
12763                Slog.w(TAG, "Privileged permission " + perm + " for package "
12764                        + pkg.packageName + " - not in privapp-permissions whitelist");
12765                // Only report violations for apps on system image
12766                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12767                    if (mPrivappPermissionsViolations == null) {
12768                        mPrivappPermissionsViolations = new ArraySet<>();
12769                    }
12770                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12771                }
12772                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12773                    return false;
12774                }
12775            }
12776        }
12777        boolean allowed = (compareSignatures(
12778                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12779                        == PackageManager.SIGNATURE_MATCH)
12780                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12781                        == PackageManager.SIGNATURE_MATCH);
12782        if (!allowed && privilegedPermission) {
12783            if (isSystemApp(pkg)) {
12784                // For updated system applications, a system permission
12785                // is granted only if it had been defined by the original application.
12786                if (pkg.isUpdatedSystemApp()) {
12787                    final PackageSetting sysPs = mSettings
12788                            .getDisabledSystemPkgLPr(pkg.packageName);
12789                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12790                        // If the original was granted this permission, we take
12791                        // that grant decision as read and propagate it to the
12792                        // update.
12793                        if (sysPs.isPrivileged()) {
12794                            allowed = true;
12795                        }
12796                    } else {
12797                        // The system apk may have been updated with an older
12798                        // version of the one on the data partition, but which
12799                        // granted a new system permission that it didn't have
12800                        // before.  In this case we do want to allow the app to
12801                        // now get the new permission if the ancestral apk is
12802                        // privileged to get it.
12803                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12804                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12805                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12806                                    allowed = true;
12807                                    break;
12808                                }
12809                            }
12810                        }
12811                        // Also if a privileged parent package on the system image or any of
12812                        // its children requested a privileged permission, the updated child
12813                        // packages can also get the permission.
12814                        if (pkg.parentPackage != null) {
12815                            final PackageSetting disabledSysParentPs = mSettings
12816                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12817                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12818                                    && disabledSysParentPs.isPrivileged()) {
12819                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12820                                    allowed = true;
12821                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12822                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12823                                    for (int i = 0; i < count; i++) {
12824                                        PackageParser.Package disabledSysChildPkg =
12825                                                disabledSysParentPs.pkg.childPackages.get(i);
12826                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12827                                                perm)) {
12828                                            allowed = true;
12829                                            break;
12830                                        }
12831                                    }
12832                                }
12833                            }
12834                        }
12835                    }
12836                } else {
12837                    allowed = isPrivilegedApp(pkg);
12838                }
12839            }
12840        }
12841        if (!allowed) {
12842            if (!allowed && (bp.protectionLevel
12843                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12844                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12845                // If this was a previously normal/dangerous permission that got moved
12846                // to a system permission as part of the runtime permission redesign, then
12847                // we still want to blindly grant it to old apps.
12848                allowed = true;
12849            }
12850            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12851                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12852                // If this permission is to be granted to the system installer and
12853                // this app is an installer, then it gets the permission.
12854                allowed = true;
12855            }
12856            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12857                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12858                // If this permission is to be granted to the system verifier and
12859                // this app is a verifier, then it gets the permission.
12860                allowed = true;
12861            }
12862            if (!allowed && (bp.protectionLevel
12863                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12864                    && isSystemApp(pkg)) {
12865                // Any pre-installed system app is allowed to get this permission.
12866                allowed = true;
12867            }
12868            if (!allowed && (bp.protectionLevel
12869                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12870                // For development permissions, a development permission
12871                // is granted only if it was already granted.
12872                allowed = origPermissions.hasInstallPermission(perm);
12873            }
12874            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12875                    && pkg.packageName.equals(mSetupWizardPackage)) {
12876                // If this permission is to be granted to the system setup wizard and
12877                // this app is a setup wizard, then it gets the permission.
12878                allowed = true;
12879            }
12880        }
12881        return allowed;
12882    }
12883
12884    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12885        final int permCount = pkg.requestedPermissions.size();
12886        for (int j = 0; j < permCount; j++) {
12887            String requestedPermission = pkg.requestedPermissions.get(j);
12888            if (permission.equals(requestedPermission)) {
12889                return true;
12890            }
12891        }
12892        return false;
12893    }
12894
12895    final class ActivityIntentResolver
12896            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12897        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12898                boolean defaultOnly, int userId) {
12899            if (!sUserManager.exists(userId)) return null;
12900            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12901            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12902        }
12903
12904        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12905                int userId) {
12906            if (!sUserManager.exists(userId)) return null;
12907            mFlags = flags;
12908            return super.queryIntent(intent, resolvedType,
12909                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12910                    userId);
12911        }
12912
12913        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12914                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12915            if (!sUserManager.exists(userId)) return null;
12916            if (packageActivities == null) {
12917                return null;
12918            }
12919            mFlags = flags;
12920            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12921            final int N = packageActivities.size();
12922            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12923                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12924
12925            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12926            for (int i = 0; i < N; ++i) {
12927                intentFilters = packageActivities.get(i).intents;
12928                if (intentFilters != null && intentFilters.size() > 0) {
12929                    PackageParser.ActivityIntentInfo[] array =
12930                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12931                    intentFilters.toArray(array);
12932                    listCut.add(array);
12933                }
12934            }
12935            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12936        }
12937
12938        /**
12939         * Finds a privileged activity that matches the specified activity names.
12940         */
12941        private PackageParser.Activity findMatchingActivity(
12942                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12943            for (PackageParser.Activity sysActivity : activityList) {
12944                if (sysActivity.info.name.equals(activityInfo.name)) {
12945                    return sysActivity;
12946                }
12947                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12948                    return sysActivity;
12949                }
12950                if (sysActivity.info.targetActivity != null) {
12951                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12952                        return sysActivity;
12953                    }
12954                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12955                        return sysActivity;
12956                    }
12957                }
12958            }
12959            return null;
12960        }
12961
12962        public class IterGenerator<E> {
12963            public Iterator<E> generate(ActivityIntentInfo info) {
12964                return null;
12965            }
12966        }
12967
12968        public class ActionIterGenerator extends IterGenerator<String> {
12969            @Override
12970            public Iterator<String> generate(ActivityIntentInfo info) {
12971                return info.actionsIterator();
12972            }
12973        }
12974
12975        public class CategoriesIterGenerator extends IterGenerator<String> {
12976            @Override
12977            public Iterator<String> generate(ActivityIntentInfo info) {
12978                return info.categoriesIterator();
12979            }
12980        }
12981
12982        public class SchemesIterGenerator extends IterGenerator<String> {
12983            @Override
12984            public Iterator<String> generate(ActivityIntentInfo info) {
12985                return info.schemesIterator();
12986            }
12987        }
12988
12989        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12990            @Override
12991            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12992                return info.authoritiesIterator();
12993            }
12994        }
12995
12996        /**
12997         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12998         * MODIFIED. Do not pass in a list that should not be changed.
12999         */
13000        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13001                IterGenerator<T> generator, Iterator<T> searchIterator) {
13002            // loop through the set of actions; every one must be found in the intent filter
13003            while (searchIterator.hasNext()) {
13004                // we must have at least one filter in the list to consider a match
13005                if (intentList.size() == 0) {
13006                    break;
13007                }
13008
13009                final T searchAction = searchIterator.next();
13010
13011                // loop through the set of intent filters
13012                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13013                while (intentIter.hasNext()) {
13014                    final ActivityIntentInfo intentInfo = intentIter.next();
13015                    boolean selectionFound = false;
13016
13017                    // loop through the intent filter's selection criteria; at least one
13018                    // of them must match the searched criteria
13019                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13020                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13021                        final T intentSelection = intentSelectionIter.next();
13022                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13023                            selectionFound = true;
13024                            break;
13025                        }
13026                    }
13027
13028                    // the selection criteria wasn't found in this filter's set; this filter
13029                    // is not a potential match
13030                    if (!selectionFound) {
13031                        intentIter.remove();
13032                    }
13033                }
13034            }
13035        }
13036
13037        private boolean isProtectedAction(ActivityIntentInfo filter) {
13038            final Iterator<String> actionsIter = filter.actionsIterator();
13039            while (actionsIter != null && actionsIter.hasNext()) {
13040                final String filterAction = actionsIter.next();
13041                if (PROTECTED_ACTIONS.contains(filterAction)) {
13042                    return true;
13043                }
13044            }
13045            return false;
13046        }
13047
13048        /**
13049         * Adjusts the priority of the given intent filter according to policy.
13050         * <p>
13051         * <ul>
13052         * <li>The priority for non privileged applications is capped to '0'</li>
13053         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13054         * <li>The priority for unbundled updates to privileged applications is capped to the
13055         *      priority defined on the system partition</li>
13056         * </ul>
13057         * <p>
13058         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13059         * allowed to obtain any priority on any action.
13060         */
13061        private void adjustPriority(
13062                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13063            // nothing to do; priority is fine as-is
13064            if (intent.getPriority() <= 0) {
13065                return;
13066            }
13067
13068            final ActivityInfo activityInfo = intent.activity.info;
13069            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13070
13071            final boolean privilegedApp =
13072                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13073            if (!privilegedApp) {
13074                // non-privileged applications can never define a priority >0
13075                if (DEBUG_FILTERS) {
13076                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13077                            + " package: " + applicationInfo.packageName
13078                            + " activity: " + intent.activity.className
13079                            + " origPrio: " + intent.getPriority());
13080                }
13081                intent.setPriority(0);
13082                return;
13083            }
13084
13085            if (systemActivities == null) {
13086                // the system package is not disabled; we're parsing the system partition
13087                if (isProtectedAction(intent)) {
13088                    if (mDeferProtectedFilters) {
13089                        // We can't deal with these just yet. No component should ever obtain a
13090                        // >0 priority for a protected actions, with ONE exception -- the setup
13091                        // wizard. The setup wizard, however, cannot be known until we're able to
13092                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13093                        // until all intent filters have been processed. Chicken, meet egg.
13094                        // Let the filter temporarily have a high priority and rectify the
13095                        // priorities after all system packages have been scanned.
13096                        mProtectedFilters.add(intent);
13097                        if (DEBUG_FILTERS) {
13098                            Slog.i(TAG, "Protected action; save for later;"
13099                                    + " package: " + applicationInfo.packageName
13100                                    + " activity: " + intent.activity.className
13101                                    + " origPrio: " + intent.getPriority());
13102                        }
13103                        return;
13104                    } else {
13105                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13106                            Slog.i(TAG, "No setup wizard;"
13107                                + " All protected intents capped to priority 0");
13108                        }
13109                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13110                            if (DEBUG_FILTERS) {
13111                                Slog.i(TAG, "Found setup wizard;"
13112                                    + " allow priority " + intent.getPriority() + ";"
13113                                    + " package: " + intent.activity.info.packageName
13114                                    + " activity: " + intent.activity.className
13115                                    + " priority: " + intent.getPriority());
13116                            }
13117                            // setup wizard gets whatever it wants
13118                            return;
13119                        }
13120                        if (DEBUG_FILTERS) {
13121                            Slog.i(TAG, "Protected action; cap priority to 0;"
13122                                    + " package: " + intent.activity.info.packageName
13123                                    + " activity: " + intent.activity.className
13124                                    + " origPrio: " + intent.getPriority());
13125                        }
13126                        intent.setPriority(0);
13127                        return;
13128                    }
13129                }
13130                // privileged apps on the system image get whatever priority they request
13131                return;
13132            }
13133
13134            // privileged app unbundled update ... try to find the same activity
13135            final PackageParser.Activity foundActivity =
13136                    findMatchingActivity(systemActivities, activityInfo);
13137            if (foundActivity == null) {
13138                // this is a new activity; it cannot obtain >0 priority
13139                if (DEBUG_FILTERS) {
13140                    Slog.i(TAG, "New activity; cap priority to 0;"
13141                            + " package: " + applicationInfo.packageName
13142                            + " activity: " + intent.activity.className
13143                            + " origPrio: " + intent.getPriority());
13144                }
13145                intent.setPriority(0);
13146                return;
13147            }
13148
13149            // found activity, now check for filter equivalence
13150
13151            // a shallow copy is enough; we modify the list, not its contents
13152            final List<ActivityIntentInfo> intentListCopy =
13153                    new ArrayList<>(foundActivity.intents);
13154            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13155
13156            // find matching action subsets
13157            final Iterator<String> actionsIterator = intent.actionsIterator();
13158            if (actionsIterator != null) {
13159                getIntentListSubset(
13160                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13161                if (intentListCopy.size() == 0) {
13162                    // no more intents to match; we're not equivalent
13163                    if (DEBUG_FILTERS) {
13164                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13165                                + " package: " + applicationInfo.packageName
13166                                + " activity: " + intent.activity.className
13167                                + " origPrio: " + intent.getPriority());
13168                    }
13169                    intent.setPriority(0);
13170                    return;
13171                }
13172            }
13173
13174            // find matching category subsets
13175            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13176            if (categoriesIterator != null) {
13177                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13178                        categoriesIterator);
13179                if (intentListCopy.size() == 0) {
13180                    // no more intents to match; we're not equivalent
13181                    if (DEBUG_FILTERS) {
13182                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13183                                + " package: " + applicationInfo.packageName
13184                                + " activity: " + intent.activity.className
13185                                + " origPrio: " + intent.getPriority());
13186                    }
13187                    intent.setPriority(0);
13188                    return;
13189                }
13190            }
13191
13192            // find matching schemes subsets
13193            final Iterator<String> schemesIterator = intent.schemesIterator();
13194            if (schemesIterator != null) {
13195                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13196                        schemesIterator);
13197                if (intentListCopy.size() == 0) {
13198                    // no more intents to match; we're not equivalent
13199                    if (DEBUG_FILTERS) {
13200                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13201                                + " package: " + applicationInfo.packageName
13202                                + " activity: " + intent.activity.className
13203                                + " origPrio: " + intent.getPriority());
13204                    }
13205                    intent.setPriority(0);
13206                    return;
13207                }
13208            }
13209
13210            // find matching authorities subsets
13211            final Iterator<IntentFilter.AuthorityEntry>
13212                    authoritiesIterator = intent.authoritiesIterator();
13213            if (authoritiesIterator != null) {
13214                getIntentListSubset(intentListCopy,
13215                        new AuthoritiesIterGenerator(),
13216                        authoritiesIterator);
13217                if (intentListCopy.size() == 0) {
13218                    // no more intents to match; we're not equivalent
13219                    if (DEBUG_FILTERS) {
13220                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13221                                + " package: " + applicationInfo.packageName
13222                                + " activity: " + intent.activity.className
13223                                + " origPrio: " + intent.getPriority());
13224                    }
13225                    intent.setPriority(0);
13226                    return;
13227                }
13228            }
13229
13230            // we found matching filter(s); app gets the max priority of all intents
13231            int cappedPriority = 0;
13232            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13233                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13234            }
13235            if (intent.getPriority() > cappedPriority) {
13236                if (DEBUG_FILTERS) {
13237                    Slog.i(TAG, "Found matching filter(s);"
13238                            + " cap priority to " + cappedPriority + ";"
13239                            + " package: " + applicationInfo.packageName
13240                            + " activity: " + intent.activity.className
13241                            + " origPrio: " + intent.getPriority());
13242                }
13243                intent.setPriority(cappedPriority);
13244                return;
13245            }
13246            // all this for nothing; the requested priority was <= what was on the system
13247        }
13248
13249        public final void addActivity(PackageParser.Activity a, String type) {
13250            mActivities.put(a.getComponentName(), a);
13251            if (DEBUG_SHOW_INFO)
13252                Log.v(
13253                TAG, "  " + type + " " +
13254                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13255            if (DEBUG_SHOW_INFO)
13256                Log.v(TAG, "    Class=" + a.info.name);
13257            final int NI = a.intents.size();
13258            for (int j=0; j<NI; j++) {
13259                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13260                if ("activity".equals(type)) {
13261                    final PackageSetting ps =
13262                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13263                    final List<PackageParser.Activity> systemActivities =
13264                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13265                    adjustPriority(systemActivities, intent);
13266                }
13267                if (DEBUG_SHOW_INFO) {
13268                    Log.v(TAG, "    IntentFilter:");
13269                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13270                }
13271                if (!intent.debugCheck()) {
13272                    Log.w(TAG, "==> For Activity " + a.info.name);
13273                }
13274                addFilter(intent);
13275            }
13276        }
13277
13278        public final void removeActivity(PackageParser.Activity a, String type) {
13279            mActivities.remove(a.getComponentName());
13280            if (DEBUG_SHOW_INFO) {
13281                Log.v(TAG, "  " + type + " "
13282                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13283                                : a.info.name) + ":");
13284                Log.v(TAG, "    Class=" + a.info.name);
13285            }
13286            final int NI = a.intents.size();
13287            for (int j=0; j<NI; j++) {
13288                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13289                if (DEBUG_SHOW_INFO) {
13290                    Log.v(TAG, "    IntentFilter:");
13291                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13292                }
13293                removeFilter(intent);
13294            }
13295        }
13296
13297        @Override
13298        protected boolean allowFilterResult(
13299                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13300            ActivityInfo filterAi = filter.activity.info;
13301            for (int i=dest.size()-1; i>=0; i--) {
13302                ActivityInfo destAi = dest.get(i).activityInfo;
13303                if (destAi.name == filterAi.name
13304                        && destAi.packageName == filterAi.packageName) {
13305                    return false;
13306                }
13307            }
13308            return true;
13309        }
13310
13311        @Override
13312        protected ActivityIntentInfo[] newArray(int size) {
13313            return new ActivityIntentInfo[size];
13314        }
13315
13316        @Override
13317        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13318            if (!sUserManager.exists(userId)) return true;
13319            PackageParser.Package p = filter.activity.owner;
13320            if (p != null) {
13321                PackageSetting ps = (PackageSetting)p.mExtras;
13322                if (ps != null) {
13323                    // System apps are never considered stopped for purposes of
13324                    // filtering, because there may be no way for the user to
13325                    // actually re-launch them.
13326                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13327                            && ps.getStopped(userId);
13328                }
13329            }
13330            return false;
13331        }
13332
13333        @Override
13334        protected boolean isPackageForFilter(String packageName,
13335                PackageParser.ActivityIntentInfo info) {
13336            return packageName.equals(info.activity.owner.packageName);
13337        }
13338
13339        @Override
13340        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13341                int match, int userId) {
13342            if (!sUserManager.exists(userId)) return null;
13343            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13344                return null;
13345            }
13346            final PackageParser.Activity activity = info.activity;
13347            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13348            if (ps == null) {
13349                return null;
13350            }
13351            final PackageUserState userState = ps.readUserState(userId);
13352            ActivityInfo ai =
13353                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13354            if (ai == null) {
13355                return null;
13356            }
13357            final boolean matchExplicitlyVisibleOnly =
13358                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13359            final boolean matchVisibleToInstantApp =
13360                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13361            final boolean componentVisible =
13362                    matchVisibleToInstantApp
13363                    && info.isVisibleToInstantApp()
13364                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13365            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13366            // throw out filters that aren't visible to ephemeral apps
13367            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13368                return null;
13369            }
13370            // throw out instant app filters if we're not explicitly requesting them
13371            if (!matchInstantApp && userState.instantApp) {
13372                return null;
13373            }
13374            // throw out instant app filters if updates are available; will trigger
13375            // instant app resolution
13376            if (userState.instantApp && ps.isUpdateAvailable()) {
13377                return null;
13378            }
13379            final ResolveInfo res = new ResolveInfo();
13380            res.activityInfo = ai;
13381            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13382                res.filter = info;
13383            }
13384            if (info != null) {
13385                res.handleAllWebDataURI = info.handleAllWebDataURI();
13386            }
13387            res.priority = info.getPriority();
13388            res.preferredOrder = activity.owner.mPreferredOrder;
13389            //System.out.println("Result: " + res.activityInfo.className +
13390            //                   " = " + res.priority);
13391            res.match = match;
13392            res.isDefault = info.hasDefault;
13393            res.labelRes = info.labelRes;
13394            res.nonLocalizedLabel = info.nonLocalizedLabel;
13395            if (userNeedsBadging(userId)) {
13396                res.noResourceId = true;
13397            } else {
13398                res.icon = info.icon;
13399            }
13400            res.iconResourceId = info.icon;
13401            res.system = res.activityInfo.applicationInfo.isSystemApp();
13402            res.isInstantAppAvailable = userState.instantApp;
13403            return res;
13404        }
13405
13406        @Override
13407        protected void sortResults(List<ResolveInfo> results) {
13408            Collections.sort(results, mResolvePrioritySorter);
13409        }
13410
13411        @Override
13412        protected void dumpFilter(PrintWriter out, String prefix,
13413                PackageParser.ActivityIntentInfo filter) {
13414            out.print(prefix); out.print(
13415                    Integer.toHexString(System.identityHashCode(filter.activity)));
13416                    out.print(' ');
13417                    filter.activity.printComponentShortName(out);
13418                    out.print(" filter ");
13419                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13420        }
13421
13422        @Override
13423        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13424            return filter.activity;
13425        }
13426
13427        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13428            PackageParser.Activity activity = (PackageParser.Activity)label;
13429            out.print(prefix); out.print(
13430                    Integer.toHexString(System.identityHashCode(activity)));
13431                    out.print(' ');
13432                    activity.printComponentShortName(out);
13433            if (count > 1) {
13434                out.print(" ("); out.print(count); out.print(" filters)");
13435            }
13436            out.println();
13437        }
13438
13439        // Keys are String (activity class name), values are Activity.
13440        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13441                = new ArrayMap<ComponentName, PackageParser.Activity>();
13442        private int mFlags;
13443    }
13444
13445    private final class ServiceIntentResolver
13446            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13447        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13448                boolean defaultOnly, int userId) {
13449            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13450            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13451        }
13452
13453        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13454                int userId) {
13455            if (!sUserManager.exists(userId)) return null;
13456            mFlags = flags;
13457            return super.queryIntent(intent, resolvedType,
13458                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13459                    userId);
13460        }
13461
13462        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13463                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13464            if (!sUserManager.exists(userId)) return null;
13465            if (packageServices == null) {
13466                return null;
13467            }
13468            mFlags = flags;
13469            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13470            final int N = packageServices.size();
13471            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13472                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13473
13474            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13475            for (int i = 0; i < N; ++i) {
13476                intentFilters = packageServices.get(i).intents;
13477                if (intentFilters != null && intentFilters.size() > 0) {
13478                    PackageParser.ServiceIntentInfo[] array =
13479                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13480                    intentFilters.toArray(array);
13481                    listCut.add(array);
13482                }
13483            }
13484            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13485        }
13486
13487        public final void addService(PackageParser.Service s) {
13488            mServices.put(s.getComponentName(), s);
13489            if (DEBUG_SHOW_INFO) {
13490                Log.v(TAG, "  "
13491                        + (s.info.nonLocalizedLabel != null
13492                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13493                Log.v(TAG, "    Class=" + s.info.name);
13494            }
13495            final int NI = s.intents.size();
13496            int j;
13497            for (j=0; j<NI; j++) {
13498                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13499                if (DEBUG_SHOW_INFO) {
13500                    Log.v(TAG, "    IntentFilter:");
13501                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13502                }
13503                if (!intent.debugCheck()) {
13504                    Log.w(TAG, "==> For Service " + s.info.name);
13505                }
13506                addFilter(intent);
13507            }
13508        }
13509
13510        public final void removeService(PackageParser.Service s) {
13511            mServices.remove(s.getComponentName());
13512            if (DEBUG_SHOW_INFO) {
13513                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13514                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13515                Log.v(TAG, "    Class=" + s.info.name);
13516            }
13517            final int NI = s.intents.size();
13518            int j;
13519            for (j=0; j<NI; j++) {
13520                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13521                if (DEBUG_SHOW_INFO) {
13522                    Log.v(TAG, "    IntentFilter:");
13523                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13524                }
13525                removeFilter(intent);
13526            }
13527        }
13528
13529        @Override
13530        protected boolean allowFilterResult(
13531                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13532            ServiceInfo filterSi = filter.service.info;
13533            for (int i=dest.size()-1; i>=0; i--) {
13534                ServiceInfo destAi = dest.get(i).serviceInfo;
13535                if (destAi.name == filterSi.name
13536                        && destAi.packageName == filterSi.packageName) {
13537                    return false;
13538                }
13539            }
13540            return true;
13541        }
13542
13543        @Override
13544        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13545            return new PackageParser.ServiceIntentInfo[size];
13546        }
13547
13548        @Override
13549        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13550            if (!sUserManager.exists(userId)) return true;
13551            PackageParser.Package p = filter.service.owner;
13552            if (p != null) {
13553                PackageSetting ps = (PackageSetting)p.mExtras;
13554                if (ps != null) {
13555                    // System apps are never considered stopped for purposes of
13556                    // filtering, because there may be no way for the user to
13557                    // actually re-launch them.
13558                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13559                            && ps.getStopped(userId);
13560                }
13561            }
13562            return false;
13563        }
13564
13565        @Override
13566        protected boolean isPackageForFilter(String packageName,
13567                PackageParser.ServiceIntentInfo info) {
13568            return packageName.equals(info.service.owner.packageName);
13569        }
13570
13571        @Override
13572        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13573                int match, int userId) {
13574            if (!sUserManager.exists(userId)) return null;
13575            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13576            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13577                return null;
13578            }
13579            final PackageParser.Service service = info.service;
13580            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13581            if (ps == null) {
13582                return null;
13583            }
13584            final PackageUserState userState = ps.readUserState(userId);
13585            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13586                    userState, userId);
13587            if (si == null) {
13588                return null;
13589            }
13590            final boolean matchVisibleToInstantApp =
13591                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13592            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13593            // throw out filters that aren't visible to ephemeral apps
13594            if (matchVisibleToInstantApp
13595                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13596                return null;
13597            }
13598            // throw out ephemeral filters if we're not explicitly requesting them
13599            if (!isInstantApp && userState.instantApp) {
13600                return null;
13601            }
13602            // throw out instant app filters if updates are available; will trigger
13603            // instant app resolution
13604            if (userState.instantApp && ps.isUpdateAvailable()) {
13605                return null;
13606            }
13607            final ResolveInfo res = new ResolveInfo();
13608            res.serviceInfo = si;
13609            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13610                res.filter = filter;
13611            }
13612            res.priority = info.getPriority();
13613            res.preferredOrder = service.owner.mPreferredOrder;
13614            res.match = match;
13615            res.isDefault = info.hasDefault;
13616            res.labelRes = info.labelRes;
13617            res.nonLocalizedLabel = info.nonLocalizedLabel;
13618            res.icon = info.icon;
13619            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13620            return res;
13621        }
13622
13623        @Override
13624        protected void sortResults(List<ResolveInfo> results) {
13625            Collections.sort(results, mResolvePrioritySorter);
13626        }
13627
13628        @Override
13629        protected void dumpFilter(PrintWriter out, String prefix,
13630                PackageParser.ServiceIntentInfo filter) {
13631            out.print(prefix); out.print(
13632                    Integer.toHexString(System.identityHashCode(filter.service)));
13633                    out.print(' ');
13634                    filter.service.printComponentShortName(out);
13635                    out.print(" filter ");
13636                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13637        }
13638
13639        @Override
13640        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13641            return filter.service;
13642        }
13643
13644        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13645            PackageParser.Service service = (PackageParser.Service)label;
13646            out.print(prefix); out.print(
13647                    Integer.toHexString(System.identityHashCode(service)));
13648                    out.print(' ');
13649                    service.printComponentShortName(out);
13650            if (count > 1) {
13651                out.print(" ("); out.print(count); out.print(" filters)");
13652            }
13653            out.println();
13654        }
13655
13656//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13657//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13658//            final List<ResolveInfo> retList = Lists.newArrayList();
13659//            while (i.hasNext()) {
13660//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13661//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13662//                    retList.add(resolveInfo);
13663//                }
13664//            }
13665//            return retList;
13666//        }
13667
13668        // Keys are String (activity class name), values are Activity.
13669        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13670                = new ArrayMap<ComponentName, PackageParser.Service>();
13671        private int mFlags;
13672    }
13673
13674    private final class ProviderIntentResolver
13675            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13676        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13677                boolean defaultOnly, int userId) {
13678            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13679            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13680        }
13681
13682        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13683                int userId) {
13684            if (!sUserManager.exists(userId))
13685                return null;
13686            mFlags = flags;
13687            return super.queryIntent(intent, resolvedType,
13688                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13689                    userId);
13690        }
13691
13692        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13693                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13694            if (!sUserManager.exists(userId))
13695                return null;
13696            if (packageProviders == null) {
13697                return null;
13698            }
13699            mFlags = flags;
13700            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13701            final int N = packageProviders.size();
13702            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13703                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13704
13705            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13706            for (int i = 0; i < N; ++i) {
13707                intentFilters = packageProviders.get(i).intents;
13708                if (intentFilters != null && intentFilters.size() > 0) {
13709                    PackageParser.ProviderIntentInfo[] array =
13710                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13711                    intentFilters.toArray(array);
13712                    listCut.add(array);
13713                }
13714            }
13715            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13716        }
13717
13718        public final void addProvider(PackageParser.Provider p) {
13719            if (mProviders.containsKey(p.getComponentName())) {
13720                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13721                return;
13722            }
13723
13724            mProviders.put(p.getComponentName(), p);
13725            if (DEBUG_SHOW_INFO) {
13726                Log.v(TAG, "  "
13727                        + (p.info.nonLocalizedLabel != null
13728                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13729                Log.v(TAG, "    Class=" + p.info.name);
13730            }
13731            final int NI = p.intents.size();
13732            int j;
13733            for (j = 0; j < NI; j++) {
13734                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13735                if (DEBUG_SHOW_INFO) {
13736                    Log.v(TAG, "    IntentFilter:");
13737                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13738                }
13739                if (!intent.debugCheck()) {
13740                    Log.w(TAG, "==> For Provider " + p.info.name);
13741                }
13742                addFilter(intent);
13743            }
13744        }
13745
13746        public final void removeProvider(PackageParser.Provider p) {
13747            mProviders.remove(p.getComponentName());
13748            if (DEBUG_SHOW_INFO) {
13749                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13750                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13751                Log.v(TAG, "    Class=" + p.info.name);
13752            }
13753            final int NI = p.intents.size();
13754            int j;
13755            for (j = 0; j < NI; j++) {
13756                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13757                if (DEBUG_SHOW_INFO) {
13758                    Log.v(TAG, "    IntentFilter:");
13759                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13760                }
13761                removeFilter(intent);
13762            }
13763        }
13764
13765        @Override
13766        protected boolean allowFilterResult(
13767                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13768            ProviderInfo filterPi = filter.provider.info;
13769            for (int i = dest.size() - 1; i >= 0; i--) {
13770                ProviderInfo destPi = dest.get(i).providerInfo;
13771                if (destPi.name == filterPi.name
13772                        && destPi.packageName == filterPi.packageName) {
13773                    return false;
13774                }
13775            }
13776            return true;
13777        }
13778
13779        @Override
13780        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13781            return new PackageParser.ProviderIntentInfo[size];
13782        }
13783
13784        @Override
13785        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13786            if (!sUserManager.exists(userId))
13787                return true;
13788            PackageParser.Package p = filter.provider.owner;
13789            if (p != null) {
13790                PackageSetting ps = (PackageSetting) p.mExtras;
13791                if (ps != null) {
13792                    // System apps are never considered stopped for purposes of
13793                    // filtering, because there may be no way for the user to
13794                    // actually re-launch them.
13795                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13796                            && ps.getStopped(userId);
13797                }
13798            }
13799            return false;
13800        }
13801
13802        @Override
13803        protected boolean isPackageForFilter(String packageName,
13804                PackageParser.ProviderIntentInfo info) {
13805            return packageName.equals(info.provider.owner.packageName);
13806        }
13807
13808        @Override
13809        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13810                int match, int userId) {
13811            if (!sUserManager.exists(userId))
13812                return null;
13813            final PackageParser.ProviderIntentInfo info = filter;
13814            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13815                return null;
13816            }
13817            final PackageParser.Provider provider = info.provider;
13818            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13819            if (ps == null) {
13820                return null;
13821            }
13822            final PackageUserState userState = ps.readUserState(userId);
13823            final boolean matchVisibleToInstantApp =
13824                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13825            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13826            // throw out filters that aren't visible to instant applications
13827            if (matchVisibleToInstantApp
13828                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13829                return null;
13830            }
13831            // throw out instant application filters if we're not explicitly requesting them
13832            if (!isInstantApp && userState.instantApp) {
13833                return null;
13834            }
13835            // throw out instant application filters if updates are available; will trigger
13836            // instant application resolution
13837            if (userState.instantApp && ps.isUpdateAvailable()) {
13838                return null;
13839            }
13840            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13841                    userState, userId);
13842            if (pi == null) {
13843                return null;
13844            }
13845            final ResolveInfo res = new ResolveInfo();
13846            res.providerInfo = pi;
13847            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13848                res.filter = filter;
13849            }
13850            res.priority = info.getPriority();
13851            res.preferredOrder = provider.owner.mPreferredOrder;
13852            res.match = match;
13853            res.isDefault = info.hasDefault;
13854            res.labelRes = info.labelRes;
13855            res.nonLocalizedLabel = info.nonLocalizedLabel;
13856            res.icon = info.icon;
13857            res.system = res.providerInfo.applicationInfo.isSystemApp();
13858            return res;
13859        }
13860
13861        @Override
13862        protected void sortResults(List<ResolveInfo> results) {
13863            Collections.sort(results, mResolvePrioritySorter);
13864        }
13865
13866        @Override
13867        protected void dumpFilter(PrintWriter out, String prefix,
13868                PackageParser.ProviderIntentInfo filter) {
13869            out.print(prefix);
13870            out.print(
13871                    Integer.toHexString(System.identityHashCode(filter.provider)));
13872            out.print(' ');
13873            filter.provider.printComponentShortName(out);
13874            out.print(" filter ");
13875            out.println(Integer.toHexString(System.identityHashCode(filter)));
13876        }
13877
13878        @Override
13879        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13880            return filter.provider;
13881        }
13882
13883        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13884            PackageParser.Provider provider = (PackageParser.Provider)label;
13885            out.print(prefix); out.print(
13886                    Integer.toHexString(System.identityHashCode(provider)));
13887                    out.print(' ');
13888                    provider.printComponentShortName(out);
13889            if (count > 1) {
13890                out.print(" ("); out.print(count); out.print(" filters)");
13891            }
13892            out.println();
13893        }
13894
13895        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13896                = new ArrayMap<ComponentName, PackageParser.Provider>();
13897        private int mFlags;
13898    }
13899
13900    static final class EphemeralIntentResolver
13901            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13902        /**
13903         * The result that has the highest defined order. Ordering applies on a
13904         * per-package basis. Mapping is from package name to Pair of order and
13905         * EphemeralResolveInfo.
13906         * <p>
13907         * NOTE: This is implemented as a field variable for convenience and efficiency.
13908         * By having a field variable, we're able to track filter ordering as soon as
13909         * a non-zero order is defined. Otherwise, multiple loops across the result set
13910         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13911         * this needs to be contained entirely within {@link #filterResults}.
13912         */
13913        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13914
13915        @Override
13916        protected AuxiliaryResolveInfo[] newArray(int size) {
13917            return new AuxiliaryResolveInfo[size];
13918        }
13919
13920        @Override
13921        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13922            return true;
13923        }
13924
13925        @Override
13926        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13927                int userId) {
13928            if (!sUserManager.exists(userId)) {
13929                return null;
13930            }
13931            final String packageName = responseObj.resolveInfo.getPackageName();
13932            final Integer order = responseObj.getOrder();
13933            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13934                    mOrderResult.get(packageName);
13935            // ordering is enabled and this item's order isn't high enough
13936            if (lastOrderResult != null && lastOrderResult.first >= order) {
13937                return null;
13938            }
13939            final InstantAppResolveInfo res = responseObj.resolveInfo;
13940            if (order > 0) {
13941                // non-zero order, enable ordering
13942                mOrderResult.put(packageName, new Pair<>(order, res));
13943            }
13944            return responseObj;
13945        }
13946
13947        @Override
13948        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13949            // only do work if ordering is enabled [most of the time it won't be]
13950            if (mOrderResult.size() == 0) {
13951                return;
13952            }
13953            int resultSize = results.size();
13954            for (int i = 0; i < resultSize; i++) {
13955                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13956                final String packageName = info.getPackageName();
13957                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13958                if (savedInfo == null) {
13959                    // package doesn't having ordering
13960                    continue;
13961                }
13962                if (savedInfo.second == info) {
13963                    // circled back to the highest ordered item; remove from order list
13964                    mOrderResult.remove(savedInfo);
13965                    if (mOrderResult.size() == 0) {
13966                        // no more ordered items
13967                        break;
13968                    }
13969                    continue;
13970                }
13971                // item has a worse order, remove it from the result list
13972                results.remove(i);
13973                resultSize--;
13974                i--;
13975            }
13976        }
13977    }
13978
13979    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13980            new Comparator<ResolveInfo>() {
13981        public int compare(ResolveInfo r1, ResolveInfo r2) {
13982            int v1 = r1.priority;
13983            int v2 = r2.priority;
13984            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13985            if (v1 != v2) {
13986                return (v1 > v2) ? -1 : 1;
13987            }
13988            v1 = r1.preferredOrder;
13989            v2 = r2.preferredOrder;
13990            if (v1 != v2) {
13991                return (v1 > v2) ? -1 : 1;
13992            }
13993            if (r1.isDefault != r2.isDefault) {
13994                return r1.isDefault ? -1 : 1;
13995            }
13996            v1 = r1.match;
13997            v2 = r2.match;
13998            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13999            if (v1 != v2) {
14000                return (v1 > v2) ? -1 : 1;
14001            }
14002            if (r1.system != r2.system) {
14003                return r1.system ? -1 : 1;
14004            }
14005            if (r1.activityInfo != null) {
14006                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14007            }
14008            if (r1.serviceInfo != null) {
14009                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14010            }
14011            if (r1.providerInfo != null) {
14012                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14013            }
14014            return 0;
14015        }
14016    };
14017
14018    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14019            new Comparator<ProviderInfo>() {
14020        public int compare(ProviderInfo p1, ProviderInfo p2) {
14021            final int v1 = p1.initOrder;
14022            final int v2 = p2.initOrder;
14023            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14024        }
14025    };
14026
14027    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14028            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14029            final int[] userIds) {
14030        mHandler.post(new Runnable() {
14031            @Override
14032            public void run() {
14033                try {
14034                    final IActivityManager am = ActivityManager.getService();
14035                    if (am == null) return;
14036                    final int[] resolvedUserIds;
14037                    if (userIds == null) {
14038                        resolvedUserIds = am.getRunningUserIds();
14039                    } else {
14040                        resolvedUserIds = userIds;
14041                    }
14042                    for (int id : resolvedUserIds) {
14043                        final Intent intent = new Intent(action,
14044                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14045                        if (extras != null) {
14046                            intent.putExtras(extras);
14047                        }
14048                        if (targetPkg != null) {
14049                            intent.setPackage(targetPkg);
14050                        }
14051                        // Modify the UID when posting to other users
14052                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14053                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14054                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14055                            intent.putExtra(Intent.EXTRA_UID, uid);
14056                        }
14057                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14058                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14059                        if (DEBUG_BROADCASTS) {
14060                            RuntimeException here = new RuntimeException("here");
14061                            here.fillInStackTrace();
14062                            Slog.d(TAG, "Sending to user " + id + ": "
14063                                    + intent.toShortString(false, true, false, false)
14064                                    + " " + intent.getExtras(), here);
14065                        }
14066                        am.broadcastIntent(null, intent, null, finishedReceiver,
14067                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14068                                null, finishedReceiver != null, false, id);
14069                    }
14070                } catch (RemoteException ex) {
14071                }
14072            }
14073        });
14074    }
14075
14076    /**
14077     * Check if the external storage media is available. This is true if there
14078     * is a mounted external storage medium or if the external storage is
14079     * emulated.
14080     */
14081    private boolean isExternalMediaAvailable() {
14082        return mMediaMounted || Environment.isExternalStorageEmulated();
14083    }
14084
14085    @Override
14086    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14088            return null;
14089        }
14090        // writer
14091        synchronized (mPackages) {
14092            if (!isExternalMediaAvailable()) {
14093                // If the external storage is no longer mounted at this point,
14094                // the caller may not have been able to delete all of this
14095                // packages files and can not delete any more.  Bail.
14096                return null;
14097            }
14098            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14099            if (lastPackage != null) {
14100                pkgs.remove(lastPackage);
14101            }
14102            if (pkgs.size() > 0) {
14103                return pkgs.get(0);
14104            }
14105        }
14106        return null;
14107    }
14108
14109    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14110        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14111                userId, andCode ? 1 : 0, packageName);
14112        if (mSystemReady) {
14113            msg.sendToTarget();
14114        } else {
14115            if (mPostSystemReadyMessages == null) {
14116                mPostSystemReadyMessages = new ArrayList<>();
14117            }
14118            mPostSystemReadyMessages.add(msg);
14119        }
14120    }
14121
14122    void startCleaningPackages() {
14123        // reader
14124        if (!isExternalMediaAvailable()) {
14125            return;
14126        }
14127        synchronized (mPackages) {
14128            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14129                return;
14130            }
14131        }
14132        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14133        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14134        IActivityManager am = ActivityManager.getService();
14135        if (am != null) {
14136            int dcsUid = -1;
14137            synchronized (mPackages) {
14138                if (!mDefaultContainerWhitelisted) {
14139                    mDefaultContainerWhitelisted = true;
14140                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14141                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14142                }
14143            }
14144            try {
14145                if (dcsUid > 0) {
14146                    am.backgroundWhitelistUid(dcsUid);
14147                }
14148                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14149                        UserHandle.USER_SYSTEM);
14150            } catch (RemoteException e) {
14151            }
14152        }
14153    }
14154
14155    @Override
14156    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14157            int installFlags, String installerPackageName, int userId) {
14158        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14159
14160        final int callingUid = Binder.getCallingUid();
14161        enforceCrossUserPermission(callingUid, userId,
14162                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14163
14164        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14165            try {
14166                if (observer != null) {
14167                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14168                }
14169            } catch (RemoteException re) {
14170            }
14171            return;
14172        }
14173
14174        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14175            installFlags |= PackageManager.INSTALL_FROM_ADB;
14176
14177        } else {
14178            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14179            // about installerPackageName.
14180
14181            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14182            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14183        }
14184
14185        UserHandle user;
14186        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14187            user = UserHandle.ALL;
14188        } else {
14189            user = new UserHandle(userId);
14190        }
14191
14192        // Only system components can circumvent runtime permissions when installing.
14193        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14194                && mContext.checkCallingOrSelfPermission(Manifest.permission
14195                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14196            throw new SecurityException("You need the "
14197                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14198                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14199        }
14200
14201        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14202                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14203            throw new IllegalArgumentException(
14204                    "New installs into ASEC containers no longer supported");
14205        }
14206
14207        final File originFile = new File(originPath);
14208        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14209
14210        final Message msg = mHandler.obtainMessage(INIT_COPY);
14211        final VerificationInfo verificationInfo = new VerificationInfo(
14212                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14213        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14214                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14215                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14216                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14217        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14218        msg.obj = params;
14219
14220        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14221                System.identityHashCode(msg.obj));
14222        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14223                System.identityHashCode(msg.obj));
14224
14225        mHandler.sendMessage(msg);
14226    }
14227
14228
14229    /**
14230     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14231     * it is acting on behalf on an enterprise or the user).
14232     *
14233     * Note that the ordering of the conditionals in this method is important. The checks we perform
14234     * are as follows, in this order:
14235     *
14236     * 1) If the install is being performed by a system app, we can trust the app to have set the
14237     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14238     *    what it is.
14239     * 2) If the install is being performed by a device or profile owner app, the install reason
14240     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14241     *    set the install reason correctly. If the app targets an older SDK version where install
14242     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14243     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14244     * 3) In all other cases, the install is being performed by a regular app that is neither part
14245     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14246     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14247     *    set to enterprise policy and if so, change it to unknown instead.
14248     */
14249    private int fixUpInstallReason(String installerPackageName, int installerUid,
14250            int installReason) {
14251        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14252                == PERMISSION_GRANTED) {
14253            // If the install is being performed by a system app, we trust that app to have set the
14254            // install reason correctly.
14255            return installReason;
14256        }
14257
14258        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14259            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14260        if (dpm != null) {
14261            ComponentName owner = null;
14262            try {
14263                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14264                if (owner == null) {
14265                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14266                }
14267            } catch (RemoteException e) {
14268            }
14269            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14270                // If the install is being performed by a device or profile owner, the install
14271                // reason should be enterprise policy.
14272                return PackageManager.INSTALL_REASON_POLICY;
14273            }
14274        }
14275
14276        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14277            // If the install is being performed by a regular app (i.e. neither system app nor
14278            // device or profile owner), we have no reason to believe that the app is acting on
14279            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14280            // change it to unknown instead.
14281            return PackageManager.INSTALL_REASON_UNKNOWN;
14282        }
14283
14284        // If the install is being performed by a regular app and the install reason was set to any
14285        // value but enterprise policy, leave the install reason unchanged.
14286        return installReason;
14287    }
14288
14289    void installStage(String packageName, File stagedDir, String stagedCid,
14290            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14291            String installerPackageName, int installerUid, UserHandle user,
14292            Certificate[][] certificates) {
14293        if (DEBUG_EPHEMERAL) {
14294            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14295                Slog.d(TAG, "Ephemeral install of " + packageName);
14296            }
14297        }
14298        final VerificationInfo verificationInfo = new VerificationInfo(
14299                sessionParams.originatingUri, sessionParams.referrerUri,
14300                sessionParams.originatingUid, installerUid);
14301
14302        final OriginInfo origin;
14303        if (stagedDir != null) {
14304            origin = OriginInfo.fromStagedFile(stagedDir);
14305        } else {
14306            origin = OriginInfo.fromStagedContainer(stagedCid);
14307        }
14308
14309        final Message msg = mHandler.obtainMessage(INIT_COPY);
14310        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14311                sessionParams.installReason);
14312        final InstallParams params = new InstallParams(origin, null, observer,
14313                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14314                verificationInfo, user, sessionParams.abiOverride,
14315                sessionParams.grantedRuntimePermissions, certificates, installReason);
14316        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14317        msg.obj = params;
14318
14319        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14320                System.identityHashCode(msg.obj));
14321        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14322                System.identityHashCode(msg.obj));
14323
14324        mHandler.sendMessage(msg);
14325    }
14326
14327    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14328            int userId) {
14329        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14330        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14331
14332        // Send a session commit broadcast
14333        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14334        info.installReason = pkgSetting.getInstallReason(userId);
14335        info.appPackageName = packageName;
14336        sendSessionCommitBroadcast(info, userId);
14337    }
14338
14339    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14340        if (ArrayUtils.isEmpty(userIds)) {
14341            return;
14342        }
14343        Bundle extras = new Bundle(1);
14344        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14345        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14346
14347        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14348                packageName, extras, 0, null, null, userIds);
14349        if (isSystem) {
14350            mHandler.post(() -> {
14351                        for (int userId : userIds) {
14352                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14353                        }
14354                    }
14355            );
14356        }
14357    }
14358
14359    /**
14360     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14361     * automatically without needing an explicit launch.
14362     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14363     */
14364    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14365        // If user is not running, the app didn't miss any broadcast
14366        if (!mUserManagerInternal.isUserRunning(userId)) {
14367            return;
14368        }
14369        final IActivityManager am = ActivityManager.getService();
14370        try {
14371            // Deliver LOCKED_BOOT_COMPLETED first
14372            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14373                    .setPackage(packageName);
14374            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14375            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14376                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14377
14378            // Deliver BOOT_COMPLETED only if user is unlocked
14379            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14380                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14381                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14382                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14383            }
14384        } catch (RemoteException e) {
14385            throw e.rethrowFromSystemServer();
14386        }
14387    }
14388
14389    @Override
14390    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14391            int userId) {
14392        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14393        PackageSetting pkgSetting;
14394        final int callingUid = Binder.getCallingUid();
14395        enforceCrossUserPermission(callingUid, userId,
14396                true /* requireFullPermission */, true /* checkShell */,
14397                "setApplicationHiddenSetting for user " + userId);
14398
14399        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14400            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14401            return false;
14402        }
14403
14404        long callingId = Binder.clearCallingIdentity();
14405        try {
14406            boolean sendAdded = false;
14407            boolean sendRemoved = false;
14408            // writer
14409            synchronized (mPackages) {
14410                pkgSetting = mSettings.mPackages.get(packageName);
14411                if (pkgSetting == null) {
14412                    return false;
14413                }
14414                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14415                    return false;
14416                }
14417                // Do not allow "android" is being disabled
14418                if ("android".equals(packageName)) {
14419                    Slog.w(TAG, "Cannot hide package: android");
14420                    return false;
14421                }
14422                // Cannot hide static shared libs as they are considered
14423                // a part of the using app (emulating static linking). Also
14424                // static libs are installed always on internal storage.
14425                PackageParser.Package pkg = mPackages.get(packageName);
14426                if (pkg != null && pkg.staticSharedLibName != null) {
14427                    Slog.w(TAG, "Cannot hide package: " + packageName
14428                            + " providing static shared library: "
14429                            + pkg.staticSharedLibName);
14430                    return false;
14431                }
14432                // Only allow protected packages to hide themselves.
14433                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14434                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14435                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14436                    return false;
14437                }
14438
14439                if (pkgSetting.getHidden(userId) != hidden) {
14440                    pkgSetting.setHidden(hidden, userId);
14441                    mSettings.writePackageRestrictionsLPr(userId);
14442                    if (hidden) {
14443                        sendRemoved = true;
14444                    } else {
14445                        sendAdded = true;
14446                    }
14447                }
14448            }
14449            if (sendAdded) {
14450                sendPackageAddedForUser(packageName, pkgSetting, userId);
14451                return true;
14452            }
14453            if (sendRemoved) {
14454                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14455                        "hiding pkg");
14456                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14457                return true;
14458            }
14459        } finally {
14460            Binder.restoreCallingIdentity(callingId);
14461        }
14462        return false;
14463    }
14464
14465    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14466            int userId) {
14467        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14468        info.removedPackage = packageName;
14469        info.installerPackageName = pkgSetting.installerPackageName;
14470        info.removedUsers = new int[] {userId};
14471        info.broadcastUsers = new int[] {userId};
14472        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14473        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14474    }
14475
14476    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14477        if (pkgList.length > 0) {
14478            Bundle extras = new Bundle(1);
14479            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14480
14481            sendPackageBroadcast(
14482                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14483                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14484                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14485                    new int[] {userId});
14486        }
14487    }
14488
14489    /**
14490     * Returns true if application is not found or there was an error. Otherwise it returns
14491     * the hidden state of the package for the given user.
14492     */
14493    @Override
14494    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14495        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14496        final int callingUid = Binder.getCallingUid();
14497        enforceCrossUserPermission(callingUid, userId,
14498                true /* requireFullPermission */, false /* checkShell */,
14499                "getApplicationHidden for user " + userId);
14500        PackageSetting ps;
14501        long callingId = Binder.clearCallingIdentity();
14502        try {
14503            // writer
14504            synchronized (mPackages) {
14505                ps = mSettings.mPackages.get(packageName);
14506                if (ps == null) {
14507                    return true;
14508                }
14509                if (filterAppAccessLPr(ps, callingUid, userId)) {
14510                    return true;
14511                }
14512                return ps.getHidden(userId);
14513            }
14514        } finally {
14515            Binder.restoreCallingIdentity(callingId);
14516        }
14517    }
14518
14519    /**
14520     * @hide
14521     */
14522    @Override
14523    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14524            int installReason) {
14525        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14526                null);
14527        PackageSetting pkgSetting;
14528        final int callingUid = Binder.getCallingUid();
14529        enforceCrossUserPermission(callingUid, userId,
14530                true /* requireFullPermission */, true /* checkShell */,
14531                "installExistingPackage for user " + userId);
14532        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14533            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14534        }
14535
14536        long callingId = Binder.clearCallingIdentity();
14537        try {
14538            boolean installed = false;
14539            final boolean instantApp =
14540                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14541            final boolean fullApp =
14542                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14543
14544            // writer
14545            synchronized (mPackages) {
14546                pkgSetting = mSettings.mPackages.get(packageName);
14547                if (pkgSetting == null) {
14548                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14549                }
14550                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14551                    // only allow the existing package to be used if it's installed as a full
14552                    // application for at least one user
14553                    boolean installAllowed = false;
14554                    for (int checkUserId : sUserManager.getUserIds()) {
14555                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14556                        if (installAllowed) {
14557                            break;
14558                        }
14559                    }
14560                    if (!installAllowed) {
14561                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14562                    }
14563                }
14564                if (!pkgSetting.getInstalled(userId)) {
14565                    pkgSetting.setInstalled(true, userId);
14566                    pkgSetting.setHidden(false, userId);
14567                    pkgSetting.setInstallReason(installReason, userId);
14568                    mSettings.writePackageRestrictionsLPr(userId);
14569                    mSettings.writeKernelMappingLPr(pkgSetting);
14570                    installed = true;
14571                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14572                    // upgrade app from instant to full; we don't allow app downgrade
14573                    installed = true;
14574                }
14575                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14576            }
14577
14578            if (installed) {
14579                if (pkgSetting.pkg != null) {
14580                    synchronized (mInstallLock) {
14581                        // We don't need to freeze for a brand new install
14582                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14583                    }
14584                }
14585                sendPackageAddedForUser(packageName, pkgSetting, userId);
14586                synchronized (mPackages) {
14587                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14588                }
14589            }
14590        } finally {
14591            Binder.restoreCallingIdentity(callingId);
14592        }
14593
14594        return PackageManager.INSTALL_SUCCEEDED;
14595    }
14596
14597    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14598            boolean instantApp, boolean fullApp) {
14599        // no state specified; do nothing
14600        if (!instantApp && !fullApp) {
14601            return;
14602        }
14603        if (userId != UserHandle.USER_ALL) {
14604            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14605                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14606            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14607                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14608            }
14609        } else {
14610            for (int currentUserId : sUserManager.getUserIds()) {
14611                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14612                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14613                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14614                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14615                }
14616            }
14617        }
14618    }
14619
14620    boolean isUserRestricted(int userId, String restrictionKey) {
14621        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14622        if (restrictions.getBoolean(restrictionKey, false)) {
14623            Log.w(TAG, "User is restricted: " + restrictionKey);
14624            return true;
14625        }
14626        return false;
14627    }
14628
14629    @Override
14630    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14631            int userId) {
14632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14633        final int callingUid = Binder.getCallingUid();
14634        enforceCrossUserPermission(callingUid, userId,
14635                true /* requireFullPermission */, true /* checkShell */,
14636                "setPackagesSuspended for user " + userId);
14637
14638        if (ArrayUtils.isEmpty(packageNames)) {
14639            return packageNames;
14640        }
14641
14642        // List of package names for whom the suspended state has changed.
14643        List<String> changedPackages = new ArrayList<>(packageNames.length);
14644        // List of package names for whom the suspended state is not set as requested in this
14645        // method.
14646        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14647        long callingId = Binder.clearCallingIdentity();
14648        try {
14649            for (int i = 0; i < packageNames.length; i++) {
14650                String packageName = packageNames[i];
14651                boolean changed = false;
14652                final int appId;
14653                synchronized (mPackages) {
14654                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14655                    if (pkgSetting == null
14656                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14657                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14658                                + "\". Skipping suspending/un-suspending.");
14659                        unactionedPackages.add(packageName);
14660                        continue;
14661                    }
14662                    appId = pkgSetting.appId;
14663                    if (pkgSetting.getSuspended(userId) != suspended) {
14664                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14665                            unactionedPackages.add(packageName);
14666                            continue;
14667                        }
14668                        pkgSetting.setSuspended(suspended, userId);
14669                        mSettings.writePackageRestrictionsLPr(userId);
14670                        changed = true;
14671                        changedPackages.add(packageName);
14672                    }
14673                }
14674
14675                if (changed && suspended) {
14676                    killApplication(packageName, UserHandle.getUid(userId, appId),
14677                            "suspending package");
14678                }
14679            }
14680        } finally {
14681            Binder.restoreCallingIdentity(callingId);
14682        }
14683
14684        if (!changedPackages.isEmpty()) {
14685            sendPackagesSuspendedForUser(changedPackages.toArray(
14686                    new String[changedPackages.size()]), userId, suspended);
14687        }
14688
14689        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14690    }
14691
14692    @Override
14693    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14694        final int callingUid = Binder.getCallingUid();
14695        enforceCrossUserPermission(callingUid, userId,
14696                true /* requireFullPermission */, false /* checkShell */,
14697                "isPackageSuspendedForUser for user " + userId);
14698        synchronized (mPackages) {
14699            final PackageSetting ps = mSettings.mPackages.get(packageName);
14700            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14701                throw new IllegalArgumentException("Unknown target package: " + packageName);
14702            }
14703            return ps.getSuspended(userId);
14704        }
14705    }
14706
14707    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14708        if (isPackageDeviceAdmin(packageName, userId)) {
14709            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14710                    + "\": has an active device admin");
14711            return false;
14712        }
14713
14714        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14715        if (packageName.equals(activeLauncherPackageName)) {
14716            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14717                    + "\": contains the active launcher");
14718            return false;
14719        }
14720
14721        if (packageName.equals(mRequiredInstallerPackage)) {
14722            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14723                    + "\": required for package installation");
14724            return false;
14725        }
14726
14727        if (packageName.equals(mRequiredUninstallerPackage)) {
14728            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14729                    + "\": required for package uninstallation");
14730            return false;
14731        }
14732
14733        if (packageName.equals(mRequiredVerifierPackage)) {
14734            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14735                    + "\": required for package verification");
14736            return false;
14737        }
14738
14739        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14740            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14741                    + "\": is the default dialer");
14742            return false;
14743        }
14744
14745        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14747                    + "\": protected package");
14748            return false;
14749        }
14750
14751        // Cannot suspend static shared libs as they are considered
14752        // a part of the using app (emulating static linking). Also
14753        // static libs are installed always on internal storage.
14754        PackageParser.Package pkg = mPackages.get(packageName);
14755        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14756            Slog.w(TAG, "Cannot suspend package: " + packageName
14757                    + " providing static shared library: "
14758                    + pkg.staticSharedLibName);
14759            return false;
14760        }
14761
14762        return true;
14763    }
14764
14765    private String getActiveLauncherPackageName(int userId) {
14766        Intent intent = new Intent(Intent.ACTION_MAIN);
14767        intent.addCategory(Intent.CATEGORY_HOME);
14768        ResolveInfo resolveInfo = resolveIntent(
14769                intent,
14770                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14771                PackageManager.MATCH_DEFAULT_ONLY,
14772                userId);
14773
14774        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14775    }
14776
14777    private String getDefaultDialerPackageName(int userId) {
14778        synchronized (mPackages) {
14779            return mSettings.getDefaultDialerPackageNameLPw(userId);
14780        }
14781    }
14782
14783    @Override
14784    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14785        mContext.enforceCallingOrSelfPermission(
14786                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14787                "Only package verification agents can verify applications");
14788
14789        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14790        final PackageVerificationResponse response = new PackageVerificationResponse(
14791                verificationCode, Binder.getCallingUid());
14792        msg.arg1 = id;
14793        msg.obj = response;
14794        mHandler.sendMessage(msg);
14795    }
14796
14797    @Override
14798    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14799            long millisecondsToDelay) {
14800        mContext.enforceCallingOrSelfPermission(
14801                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14802                "Only package verification agents can extend verification timeouts");
14803
14804        final PackageVerificationState state = mPendingVerification.get(id);
14805        final PackageVerificationResponse response = new PackageVerificationResponse(
14806                verificationCodeAtTimeout, Binder.getCallingUid());
14807
14808        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14809            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14810        }
14811        if (millisecondsToDelay < 0) {
14812            millisecondsToDelay = 0;
14813        }
14814        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14815                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14816            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14817        }
14818
14819        if ((state != null) && !state.timeoutExtended()) {
14820            state.extendTimeout();
14821
14822            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14823            msg.arg1 = id;
14824            msg.obj = response;
14825            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14826        }
14827    }
14828
14829    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14830            int verificationCode, UserHandle user) {
14831        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14832        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14833        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14834        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14835        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14836
14837        mContext.sendBroadcastAsUser(intent, user,
14838                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14839    }
14840
14841    private ComponentName matchComponentForVerifier(String packageName,
14842            List<ResolveInfo> receivers) {
14843        ActivityInfo targetReceiver = null;
14844
14845        final int NR = receivers.size();
14846        for (int i = 0; i < NR; i++) {
14847            final ResolveInfo info = receivers.get(i);
14848            if (info.activityInfo == null) {
14849                continue;
14850            }
14851
14852            if (packageName.equals(info.activityInfo.packageName)) {
14853                targetReceiver = info.activityInfo;
14854                break;
14855            }
14856        }
14857
14858        if (targetReceiver == null) {
14859            return null;
14860        }
14861
14862        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14863    }
14864
14865    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14866            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14867        if (pkgInfo.verifiers.length == 0) {
14868            return null;
14869        }
14870
14871        final int N = pkgInfo.verifiers.length;
14872        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14873        for (int i = 0; i < N; i++) {
14874            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14875
14876            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14877                    receivers);
14878            if (comp == null) {
14879                continue;
14880            }
14881
14882            final int verifierUid = getUidForVerifier(verifierInfo);
14883            if (verifierUid == -1) {
14884                continue;
14885            }
14886
14887            if (DEBUG_VERIFY) {
14888                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14889                        + " with the correct signature");
14890            }
14891            sufficientVerifiers.add(comp);
14892            verificationState.addSufficientVerifier(verifierUid);
14893        }
14894
14895        return sufficientVerifiers;
14896    }
14897
14898    private int getUidForVerifier(VerifierInfo verifierInfo) {
14899        synchronized (mPackages) {
14900            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14901            if (pkg == null) {
14902                return -1;
14903            } else if (pkg.mSignatures.length != 1) {
14904                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14905                        + " has more than one signature; ignoring");
14906                return -1;
14907            }
14908
14909            /*
14910             * If the public key of the package's signature does not match
14911             * our expected public key, then this is a different package and
14912             * we should skip.
14913             */
14914
14915            final byte[] expectedPublicKey;
14916            try {
14917                final Signature verifierSig = pkg.mSignatures[0];
14918                final PublicKey publicKey = verifierSig.getPublicKey();
14919                expectedPublicKey = publicKey.getEncoded();
14920            } catch (CertificateException e) {
14921                return -1;
14922            }
14923
14924            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14925
14926            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14927                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14928                        + " does not have the expected public key; ignoring");
14929                return -1;
14930            }
14931
14932            return pkg.applicationInfo.uid;
14933        }
14934    }
14935
14936    @Override
14937    public void finishPackageInstall(int token, boolean didLaunch) {
14938        enforceSystemOrRoot("Only the system is allowed to finish installs");
14939
14940        if (DEBUG_INSTALL) {
14941            Slog.v(TAG, "BM finishing package install for " + token);
14942        }
14943        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14944
14945        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14946        mHandler.sendMessage(msg);
14947    }
14948
14949    /**
14950     * Get the verification agent timeout.  Used for both the APK verifier and the
14951     * intent filter verifier.
14952     *
14953     * @return verification timeout in milliseconds
14954     */
14955    private long getVerificationTimeout() {
14956        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14957                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14958                DEFAULT_VERIFICATION_TIMEOUT);
14959    }
14960
14961    /**
14962     * Get the default verification agent response code.
14963     *
14964     * @return default verification response code
14965     */
14966    private int getDefaultVerificationResponse(UserHandle user) {
14967        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14968            return PackageManager.VERIFICATION_REJECT;
14969        }
14970        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14971                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14972                DEFAULT_VERIFICATION_RESPONSE);
14973    }
14974
14975    /**
14976     * Check whether or not package verification has been enabled.
14977     *
14978     * @return true if verification should be performed
14979     */
14980    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14981        if (!DEFAULT_VERIFY_ENABLE) {
14982            return false;
14983        }
14984
14985        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14986
14987        // Check if installing from ADB
14988        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14989            // Do not run verification in a test harness environment
14990            if (ActivityManager.isRunningInTestHarness()) {
14991                return false;
14992            }
14993            if (ensureVerifyAppsEnabled) {
14994                return true;
14995            }
14996            // Check if the developer does not want package verification for ADB installs
14997            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14998                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14999                return false;
15000            }
15001        } else {
15002            // only when not installed from ADB, skip verification for instant apps when
15003            // the installer and verifier are the same.
15004            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15005                if (mInstantAppInstallerActivity != null
15006                        && mInstantAppInstallerActivity.packageName.equals(
15007                                mRequiredVerifierPackage)) {
15008                    try {
15009                        mContext.getSystemService(AppOpsManager.class)
15010                                .checkPackage(installerUid, mRequiredVerifierPackage);
15011                        if (DEBUG_VERIFY) {
15012                            Slog.i(TAG, "disable verification for instant app");
15013                        }
15014                        return false;
15015                    } catch (SecurityException ignore) { }
15016                }
15017            }
15018        }
15019
15020        if (ensureVerifyAppsEnabled) {
15021            return true;
15022        }
15023
15024        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15025                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15026    }
15027
15028    @Override
15029    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15030            throws RemoteException {
15031        mContext.enforceCallingOrSelfPermission(
15032                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15033                "Only intentfilter verification agents can verify applications");
15034
15035        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15036        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15037                Binder.getCallingUid(), verificationCode, failedDomains);
15038        msg.arg1 = id;
15039        msg.obj = response;
15040        mHandler.sendMessage(msg);
15041    }
15042
15043    @Override
15044    public int getIntentVerificationStatus(String packageName, int userId) {
15045        final int callingUid = Binder.getCallingUid();
15046        if (getInstantAppPackageName(callingUid) != null) {
15047            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15048        }
15049        synchronized (mPackages) {
15050            final PackageSetting ps = mSettings.mPackages.get(packageName);
15051            if (ps == null
15052                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15053                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15054            }
15055            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15056        }
15057    }
15058
15059    @Override
15060    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15061        mContext.enforceCallingOrSelfPermission(
15062                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15063
15064        boolean result = false;
15065        synchronized (mPackages) {
15066            final PackageSetting ps = mSettings.mPackages.get(packageName);
15067            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15068                return false;
15069            }
15070            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15071        }
15072        if (result) {
15073            scheduleWritePackageRestrictionsLocked(userId);
15074        }
15075        return result;
15076    }
15077
15078    @Override
15079    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15080            String packageName) {
15081        final int callingUid = Binder.getCallingUid();
15082        if (getInstantAppPackageName(callingUid) != null) {
15083            return ParceledListSlice.emptyList();
15084        }
15085        synchronized (mPackages) {
15086            final PackageSetting ps = mSettings.mPackages.get(packageName);
15087            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15088                return ParceledListSlice.emptyList();
15089            }
15090            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15091        }
15092    }
15093
15094    @Override
15095    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15096        if (TextUtils.isEmpty(packageName)) {
15097            return ParceledListSlice.emptyList();
15098        }
15099        final int callingUid = Binder.getCallingUid();
15100        final int callingUserId = UserHandle.getUserId(callingUid);
15101        synchronized (mPackages) {
15102            PackageParser.Package pkg = mPackages.get(packageName);
15103            if (pkg == null || pkg.activities == null) {
15104                return ParceledListSlice.emptyList();
15105            }
15106            if (pkg.mExtras == null) {
15107                return ParceledListSlice.emptyList();
15108            }
15109            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15110            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15111                return ParceledListSlice.emptyList();
15112            }
15113            final int count = pkg.activities.size();
15114            ArrayList<IntentFilter> result = new ArrayList<>();
15115            for (int n=0; n<count; n++) {
15116                PackageParser.Activity activity = pkg.activities.get(n);
15117                if (activity.intents != null && activity.intents.size() > 0) {
15118                    result.addAll(activity.intents);
15119                }
15120            }
15121            return new ParceledListSlice<>(result);
15122        }
15123    }
15124
15125    @Override
15126    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15127        mContext.enforceCallingOrSelfPermission(
15128                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15129
15130        synchronized (mPackages) {
15131            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15132            if (packageName != null) {
15133                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15134                        packageName, userId);
15135            }
15136            return result;
15137        }
15138    }
15139
15140    @Override
15141    public String getDefaultBrowserPackageName(int userId) {
15142        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15143            return null;
15144        }
15145        synchronized (mPackages) {
15146            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15147        }
15148    }
15149
15150    /**
15151     * Get the "allow unknown sources" setting.
15152     *
15153     * @return the current "allow unknown sources" setting
15154     */
15155    private int getUnknownSourcesSettings() {
15156        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15157                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15158                -1);
15159    }
15160
15161    @Override
15162    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15163        final int callingUid = Binder.getCallingUid();
15164        if (getInstantAppPackageName(callingUid) != null) {
15165            return;
15166        }
15167        // writer
15168        synchronized (mPackages) {
15169            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15170            if (targetPackageSetting == null
15171                    || filterAppAccessLPr(
15172                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15173                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15174            }
15175
15176            PackageSetting installerPackageSetting;
15177            if (installerPackageName != null) {
15178                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15179                if (installerPackageSetting == null) {
15180                    throw new IllegalArgumentException("Unknown installer package: "
15181                            + installerPackageName);
15182                }
15183            } else {
15184                installerPackageSetting = null;
15185            }
15186
15187            Signature[] callerSignature;
15188            Object obj = mSettings.getUserIdLPr(callingUid);
15189            if (obj != null) {
15190                if (obj instanceof SharedUserSetting) {
15191                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15192                } else if (obj instanceof PackageSetting) {
15193                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15194                } else {
15195                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15196                }
15197            } else {
15198                throw new SecurityException("Unknown calling UID: " + callingUid);
15199            }
15200
15201            // Verify: can't set installerPackageName to a package that is
15202            // not signed with the same cert as the caller.
15203            if (installerPackageSetting != null) {
15204                if (compareSignatures(callerSignature,
15205                        installerPackageSetting.signatures.mSignatures)
15206                        != PackageManager.SIGNATURE_MATCH) {
15207                    throw new SecurityException(
15208                            "Caller does not have same cert as new installer package "
15209                            + installerPackageName);
15210                }
15211            }
15212
15213            // Verify: if target already has an installer package, it must
15214            // be signed with the same cert as the caller.
15215            if (targetPackageSetting.installerPackageName != null) {
15216                PackageSetting setting = mSettings.mPackages.get(
15217                        targetPackageSetting.installerPackageName);
15218                // If the currently set package isn't valid, then it's always
15219                // okay to change it.
15220                if (setting != null) {
15221                    if (compareSignatures(callerSignature,
15222                            setting.signatures.mSignatures)
15223                            != PackageManager.SIGNATURE_MATCH) {
15224                        throw new SecurityException(
15225                                "Caller does not have same cert as old installer package "
15226                                + targetPackageSetting.installerPackageName);
15227                    }
15228                }
15229            }
15230
15231            // Okay!
15232            targetPackageSetting.installerPackageName = installerPackageName;
15233            if (installerPackageName != null) {
15234                mSettings.mInstallerPackages.add(installerPackageName);
15235            }
15236            scheduleWriteSettingsLocked();
15237        }
15238    }
15239
15240    @Override
15241    public void setApplicationCategoryHint(String packageName, int categoryHint,
15242            String callerPackageName) {
15243        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15244            throw new SecurityException("Instant applications don't have access to this method");
15245        }
15246        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15247                callerPackageName);
15248        synchronized (mPackages) {
15249            PackageSetting ps = mSettings.mPackages.get(packageName);
15250            if (ps == null) {
15251                throw new IllegalArgumentException("Unknown target package " + packageName);
15252            }
15253            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15254                throw new IllegalArgumentException("Unknown target package " + packageName);
15255            }
15256            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15257                throw new IllegalArgumentException("Calling package " + callerPackageName
15258                        + " is not installer for " + packageName);
15259            }
15260
15261            if (ps.categoryHint != categoryHint) {
15262                ps.categoryHint = categoryHint;
15263                scheduleWriteSettingsLocked();
15264            }
15265        }
15266    }
15267
15268    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15269        // Queue up an async operation since the package installation may take a little while.
15270        mHandler.post(new Runnable() {
15271            public void run() {
15272                mHandler.removeCallbacks(this);
15273                 // Result object to be returned
15274                PackageInstalledInfo res = new PackageInstalledInfo();
15275                res.setReturnCode(currentStatus);
15276                res.uid = -1;
15277                res.pkg = null;
15278                res.removedInfo = null;
15279                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15280                    args.doPreInstall(res.returnCode);
15281                    synchronized (mInstallLock) {
15282                        installPackageTracedLI(args, res);
15283                    }
15284                    args.doPostInstall(res.returnCode, res.uid);
15285                }
15286
15287                // A restore should be performed at this point if (a) the install
15288                // succeeded, (b) the operation is not an update, and (c) the new
15289                // package has not opted out of backup participation.
15290                final boolean update = res.removedInfo != null
15291                        && res.removedInfo.removedPackage != null;
15292                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15293                boolean doRestore = !update
15294                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15295
15296                // Set up the post-install work request bookkeeping.  This will be used
15297                // and cleaned up by the post-install event handling regardless of whether
15298                // there's a restore pass performed.  Token values are >= 1.
15299                int token;
15300                if (mNextInstallToken < 0) mNextInstallToken = 1;
15301                token = mNextInstallToken++;
15302
15303                PostInstallData data = new PostInstallData(args, res);
15304                mRunningInstalls.put(token, data);
15305                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15306
15307                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15308                    // Pass responsibility to the Backup Manager.  It will perform a
15309                    // restore if appropriate, then pass responsibility back to the
15310                    // Package Manager to run the post-install observer callbacks
15311                    // and broadcasts.
15312                    IBackupManager bm = IBackupManager.Stub.asInterface(
15313                            ServiceManager.getService(Context.BACKUP_SERVICE));
15314                    if (bm != null) {
15315                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15316                                + " to BM for possible restore");
15317                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15318                        try {
15319                            // TODO: http://b/22388012
15320                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15321                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15322                            } else {
15323                                doRestore = false;
15324                            }
15325                        } catch (RemoteException e) {
15326                            // can't happen; the backup manager is local
15327                        } catch (Exception e) {
15328                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15329                            doRestore = false;
15330                        }
15331                    } else {
15332                        Slog.e(TAG, "Backup Manager not found!");
15333                        doRestore = false;
15334                    }
15335                }
15336
15337                if (!doRestore) {
15338                    // No restore possible, or the Backup Manager was mysteriously not
15339                    // available -- just fire the post-install work request directly.
15340                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15341
15342                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15343
15344                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15345                    mHandler.sendMessage(msg);
15346                }
15347            }
15348        });
15349    }
15350
15351    /**
15352     * Callback from PackageSettings whenever an app is first transitioned out of the
15353     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15354     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15355     * here whether the app is the target of an ongoing install, and only send the
15356     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15357     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15358     * handling.
15359     */
15360    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15361        // Serialize this with the rest of the install-process message chain.  In the
15362        // restore-at-install case, this Runnable will necessarily run before the
15363        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15364        // are coherent.  In the non-restore case, the app has already completed install
15365        // and been launched through some other means, so it is not in a problematic
15366        // state for observers to see the FIRST_LAUNCH signal.
15367        mHandler.post(new Runnable() {
15368            @Override
15369            public void run() {
15370                for (int i = 0; i < mRunningInstalls.size(); i++) {
15371                    final PostInstallData data = mRunningInstalls.valueAt(i);
15372                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15373                        continue;
15374                    }
15375                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15376                        // right package; but is it for the right user?
15377                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15378                            if (userId == data.res.newUsers[uIndex]) {
15379                                if (DEBUG_BACKUP) {
15380                                    Slog.i(TAG, "Package " + pkgName
15381                                            + " being restored so deferring FIRST_LAUNCH");
15382                                }
15383                                return;
15384                            }
15385                        }
15386                    }
15387                }
15388                // didn't find it, so not being restored
15389                if (DEBUG_BACKUP) {
15390                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15391                }
15392                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15393            }
15394        });
15395    }
15396
15397    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15398        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15399                installerPkg, null, userIds);
15400    }
15401
15402    private abstract class HandlerParams {
15403        private static final int MAX_RETRIES = 4;
15404
15405        /**
15406         * Number of times startCopy() has been attempted and had a non-fatal
15407         * error.
15408         */
15409        private int mRetries = 0;
15410
15411        /** User handle for the user requesting the information or installation. */
15412        private final UserHandle mUser;
15413        String traceMethod;
15414        int traceCookie;
15415
15416        HandlerParams(UserHandle user) {
15417            mUser = user;
15418        }
15419
15420        UserHandle getUser() {
15421            return mUser;
15422        }
15423
15424        HandlerParams setTraceMethod(String traceMethod) {
15425            this.traceMethod = traceMethod;
15426            return this;
15427        }
15428
15429        HandlerParams setTraceCookie(int traceCookie) {
15430            this.traceCookie = traceCookie;
15431            return this;
15432        }
15433
15434        final boolean startCopy() {
15435            boolean res;
15436            try {
15437                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15438
15439                if (++mRetries > MAX_RETRIES) {
15440                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15441                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15442                    handleServiceError();
15443                    return false;
15444                } else {
15445                    handleStartCopy();
15446                    res = true;
15447                }
15448            } catch (RemoteException e) {
15449                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15450                mHandler.sendEmptyMessage(MCS_RECONNECT);
15451                res = false;
15452            }
15453            handleReturnCode();
15454            return res;
15455        }
15456
15457        final void serviceError() {
15458            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15459            handleServiceError();
15460            handleReturnCode();
15461        }
15462
15463        abstract void handleStartCopy() throws RemoteException;
15464        abstract void handleServiceError();
15465        abstract void handleReturnCode();
15466    }
15467
15468    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15469        for (File path : paths) {
15470            try {
15471                mcs.clearDirectory(path.getAbsolutePath());
15472            } catch (RemoteException e) {
15473            }
15474        }
15475    }
15476
15477    static class OriginInfo {
15478        /**
15479         * Location where install is coming from, before it has been
15480         * copied/renamed into place. This could be a single monolithic APK
15481         * file, or a cluster directory. This location may be untrusted.
15482         */
15483        final File file;
15484        final String cid;
15485
15486        /**
15487         * Flag indicating that {@link #file} or {@link #cid} has already been
15488         * staged, meaning downstream users don't need to defensively copy the
15489         * contents.
15490         */
15491        final boolean staged;
15492
15493        /**
15494         * Flag indicating that {@link #file} or {@link #cid} is an already
15495         * installed app that is being moved.
15496         */
15497        final boolean existing;
15498
15499        final String resolvedPath;
15500        final File resolvedFile;
15501
15502        static OriginInfo fromNothing() {
15503            return new OriginInfo(null, null, false, false);
15504        }
15505
15506        static OriginInfo fromUntrustedFile(File file) {
15507            return new OriginInfo(file, null, false, false);
15508        }
15509
15510        static OriginInfo fromExistingFile(File file) {
15511            return new OriginInfo(file, null, false, true);
15512        }
15513
15514        static OriginInfo fromStagedFile(File file) {
15515            return new OriginInfo(file, null, true, false);
15516        }
15517
15518        static OriginInfo fromStagedContainer(String cid) {
15519            return new OriginInfo(null, cid, true, false);
15520        }
15521
15522        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15523            this.file = file;
15524            this.cid = cid;
15525            this.staged = staged;
15526            this.existing = existing;
15527
15528            if (cid != null) {
15529                resolvedPath = PackageHelper.getSdDir(cid);
15530                resolvedFile = new File(resolvedPath);
15531            } else if (file != null) {
15532                resolvedPath = file.getAbsolutePath();
15533                resolvedFile = file;
15534            } else {
15535                resolvedPath = null;
15536                resolvedFile = null;
15537            }
15538        }
15539    }
15540
15541    static class MoveInfo {
15542        final int moveId;
15543        final String fromUuid;
15544        final String toUuid;
15545        final String packageName;
15546        final String dataAppName;
15547        final int appId;
15548        final String seinfo;
15549        final int targetSdkVersion;
15550
15551        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15552                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15553            this.moveId = moveId;
15554            this.fromUuid = fromUuid;
15555            this.toUuid = toUuid;
15556            this.packageName = packageName;
15557            this.dataAppName = dataAppName;
15558            this.appId = appId;
15559            this.seinfo = seinfo;
15560            this.targetSdkVersion = targetSdkVersion;
15561        }
15562    }
15563
15564    static class VerificationInfo {
15565        /** A constant used to indicate that a uid value is not present. */
15566        public static final int NO_UID = -1;
15567
15568        /** URI referencing where the package was downloaded from. */
15569        final Uri originatingUri;
15570
15571        /** HTTP referrer URI associated with the originatingURI. */
15572        final Uri referrer;
15573
15574        /** UID of the application that the install request originated from. */
15575        final int originatingUid;
15576
15577        /** UID of application requesting the install */
15578        final int installerUid;
15579
15580        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15581            this.originatingUri = originatingUri;
15582            this.referrer = referrer;
15583            this.originatingUid = originatingUid;
15584            this.installerUid = installerUid;
15585        }
15586    }
15587
15588    class InstallParams extends HandlerParams {
15589        final OriginInfo origin;
15590        final MoveInfo move;
15591        final IPackageInstallObserver2 observer;
15592        int installFlags;
15593        final String installerPackageName;
15594        final String volumeUuid;
15595        private InstallArgs mArgs;
15596        private int mRet;
15597        final String packageAbiOverride;
15598        final String[] grantedRuntimePermissions;
15599        final VerificationInfo verificationInfo;
15600        final Certificate[][] certificates;
15601        final int installReason;
15602
15603        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15604                int installFlags, String installerPackageName, String volumeUuid,
15605                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15606                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15607            super(user);
15608            this.origin = origin;
15609            this.move = move;
15610            this.observer = observer;
15611            this.installFlags = installFlags;
15612            this.installerPackageName = installerPackageName;
15613            this.volumeUuid = volumeUuid;
15614            this.verificationInfo = verificationInfo;
15615            this.packageAbiOverride = packageAbiOverride;
15616            this.grantedRuntimePermissions = grantedPermissions;
15617            this.certificates = certificates;
15618            this.installReason = installReason;
15619        }
15620
15621        @Override
15622        public String toString() {
15623            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15624                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15625        }
15626
15627        private int installLocationPolicy(PackageInfoLite pkgLite) {
15628            String packageName = pkgLite.packageName;
15629            int installLocation = pkgLite.installLocation;
15630            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15631            // reader
15632            synchronized (mPackages) {
15633                // Currently installed package which the new package is attempting to replace or
15634                // null if no such package is installed.
15635                PackageParser.Package installedPkg = mPackages.get(packageName);
15636                // Package which currently owns the data which the new package will own if installed.
15637                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15638                // will be null whereas dataOwnerPkg will contain information about the package
15639                // which was uninstalled while keeping its data.
15640                PackageParser.Package dataOwnerPkg = installedPkg;
15641                if (dataOwnerPkg  == null) {
15642                    PackageSetting ps = mSettings.mPackages.get(packageName);
15643                    if (ps != null) {
15644                        dataOwnerPkg = ps.pkg;
15645                    }
15646                }
15647
15648                if (dataOwnerPkg != null) {
15649                    // If installed, the package will get access to data left on the device by its
15650                    // predecessor. As a security measure, this is permited only if this is not a
15651                    // version downgrade or if the predecessor package is marked as debuggable and
15652                    // a downgrade is explicitly requested.
15653                    //
15654                    // On debuggable platform builds, downgrades are permitted even for
15655                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15656                    // not offer security guarantees and thus it's OK to disable some security
15657                    // mechanisms to make debugging/testing easier on those builds. However, even on
15658                    // debuggable builds downgrades of packages are permitted only if requested via
15659                    // installFlags. This is because we aim to keep the behavior of debuggable
15660                    // platform builds as close as possible to the behavior of non-debuggable
15661                    // platform builds.
15662                    final boolean downgradeRequested =
15663                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15664                    final boolean packageDebuggable =
15665                                (dataOwnerPkg.applicationInfo.flags
15666                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15667                    final boolean downgradePermitted =
15668                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15669                    if (!downgradePermitted) {
15670                        try {
15671                            checkDowngrade(dataOwnerPkg, pkgLite);
15672                        } catch (PackageManagerException e) {
15673                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15674                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15675                        }
15676                    }
15677                }
15678
15679                if (installedPkg != null) {
15680                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15681                        // Check for updated system application.
15682                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15683                            if (onSd) {
15684                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15685                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15686                            }
15687                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15688                        } else {
15689                            if (onSd) {
15690                                // Install flag overrides everything.
15691                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15692                            }
15693                            // If current upgrade specifies particular preference
15694                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15695                                // Application explicitly specified internal.
15696                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15697                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15698                                // App explictly prefers external. Let policy decide
15699                            } else {
15700                                // Prefer previous location
15701                                if (isExternal(installedPkg)) {
15702                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15703                                }
15704                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15705                            }
15706                        }
15707                    } else {
15708                        // Invalid install. Return error code
15709                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15710                    }
15711                }
15712            }
15713            // All the special cases have been taken care of.
15714            // Return result based on recommended install location.
15715            if (onSd) {
15716                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15717            }
15718            return pkgLite.recommendedInstallLocation;
15719        }
15720
15721        /*
15722         * Invoke remote method to get package information and install
15723         * location values. Override install location based on default
15724         * policy if needed and then create install arguments based
15725         * on the install location.
15726         */
15727        public void handleStartCopy() throws RemoteException {
15728            int ret = PackageManager.INSTALL_SUCCEEDED;
15729
15730            // If we're already staged, we've firmly committed to an install location
15731            if (origin.staged) {
15732                if (origin.file != null) {
15733                    installFlags |= PackageManager.INSTALL_INTERNAL;
15734                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15735                } else if (origin.cid != null) {
15736                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15737                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15738                } else {
15739                    throw new IllegalStateException("Invalid stage location");
15740                }
15741            }
15742
15743            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15744            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15745            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15746            PackageInfoLite pkgLite = null;
15747
15748            if (onInt && onSd) {
15749                // Check if both bits are set.
15750                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15751                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15752            } else if (onSd && ephemeral) {
15753                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15754                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15755            } else {
15756                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15757                        packageAbiOverride);
15758
15759                if (DEBUG_EPHEMERAL && ephemeral) {
15760                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15761                }
15762
15763                /*
15764                 * If we have too little free space, try to free cache
15765                 * before giving up.
15766                 */
15767                if (!origin.staged && pkgLite.recommendedInstallLocation
15768                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15769                    // TODO: focus freeing disk space on the target device
15770                    final StorageManager storage = StorageManager.from(mContext);
15771                    final long lowThreshold = storage.getStorageLowBytes(
15772                            Environment.getDataDirectory());
15773
15774                    final long sizeBytes = mContainerService.calculateInstalledSize(
15775                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15776
15777                    try {
15778                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15779                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15780                                installFlags, packageAbiOverride);
15781                    } catch (InstallerException e) {
15782                        Slog.w(TAG, "Failed to free cache", e);
15783                    }
15784
15785                    /*
15786                     * The cache free must have deleted the file we
15787                     * downloaded to install.
15788                     *
15789                     * TODO: fix the "freeCache" call to not delete
15790                     *       the file we care about.
15791                     */
15792                    if (pkgLite.recommendedInstallLocation
15793                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15794                        pkgLite.recommendedInstallLocation
15795                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15796                    }
15797                }
15798            }
15799
15800            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15801                int loc = pkgLite.recommendedInstallLocation;
15802                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15803                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15804                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15805                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15806                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15807                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15808                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15809                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15810                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15811                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15812                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15813                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15814                } else {
15815                    // Override with defaults if needed.
15816                    loc = installLocationPolicy(pkgLite);
15817                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15818                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15819                    } else if (!onSd && !onInt) {
15820                        // Override install location with flags
15821                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15822                            // Set the flag to install on external media.
15823                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15824                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15825                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15826                            if (DEBUG_EPHEMERAL) {
15827                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15828                            }
15829                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15830                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15831                                    |PackageManager.INSTALL_INTERNAL);
15832                        } else {
15833                            // Make sure the flag for installing on external
15834                            // media is unset
15835                            installFlags |= PackageManager.INSTALL_INTERNAL;
15836                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15837                        }
15838                    }
15839                }
15840            }
15841
15842            final InstallArgs args = createInstallArgs(this);
15843            mArgs = args;
15844
15845            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15846                // TODO: http://b/22976637
15847                // Apps installed for "all" users use the device owner to verify the app
15848                UserHandle verifierUser = getUser();
15849                if (verifierUser == UserHandle.ALL) {
15850                    verifierUser = UserHandle.SYSTEM;
15851                }
15852
15853                /*
15854                 * Determine if we have any installed package verifiers. If we
15855                 * do, then we'll defer to them to verify the packages.
15856                 */
15857                final int requiredUid = mRequiredVerifierPackage == null ? -1
15858                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15859                                verifierUser.getIdentifier());
15860                final int installerUid =
15861                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15862                if (!origin.existing && requiredUid != -1
15863                        && isVerificationEnabled(
15864                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15865                    final Intent verification = new Intent(
15866                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15867                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15868                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15869                            PACKAGE_MIME_TYPE);
15870                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15871
15872                    // Query all live verifiers based on current user state
15873                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15874                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15875
15876                    if (DEBUG_VERIFY) {
15877                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15878                                + verification.toString() + " with " + pkgLite.verifiers.length
15879                                + " optional verifiers");
15880                    }
15881
15882                    final int verificationId = mPendingVerificationToken++;
15883
15884                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15885
15886                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15887                            installerPackageName);
15888
15889                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15890                            installFlags);
15891
15892                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15893                            pkgLite.packageName);
15894
15895                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15896                            pkgLite.versionCode);
15897
15898                    if (verificationInfo != null) {
15899                        if (verificationInfo.originatingUri != null) {
15900                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15901                                    verificationInfo.originatingUri);
15902                        }
15903                        if (verificationInfo.referrer != null) {
15904                            verification.putExtra(Intent.EXTRA_REFERRER,
15905                                    verificationInfo.referrer);
15906                        }
15907                        if (verificationInfo.originatingUid >= 0) {
15908                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15909                                    verificationInfo.originatingUid);
15910                        }
15911                        if (verificationInfo.installerUid >= 0) {
15912                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15913                                    verificationInfo.installerUid);
15914                        }
15915                    }
15916
15917                    final PackageVerificationState verificationState = new PackageVerificationState(
15918                            requiredUid, args);
15919
15920                    mPendingVerification.append(verificationId, verificationState);
15921
15922                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15923                            receivers, verificationState);
15924
15925                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15926                    final long idleDuration = getVerificationTimeout();
15927
15928                    /*
15929                     * If any sufficient verifiers were listed in the package
15930                     * manifest, attempt to ask them.
15931                     */
15932                    if (sufficientVerifiers != null) {
15933                        final int N = sufficientVerifiers.size();
15934                        if (N == 0) {
15935                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15936                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15937                        } else {
15938                            for (int i = 0; i < N; i++) {
15939                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15940                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15941                                        verifierComponent.getPackageName(), idleDuration,
15942                                        verifierUser.getIdentifier(), false, "package verifier");
15943
15944                                final Intent sufficientIntent = new Intent(verification);
15945                                sufficientIntent.setComponent(verifierComponent);
15946                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15947                            }
15948                        }
15949                    }
15950
15951                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15952                            mRequiredVerifierPackage, receivers);
15953                    if (ret == PackageManager.INSTALL_SUCCEEDED
15954                            && mRequiredVerifierPackage != null) {
15955                        Trace.asyncTraceBegin(
15956                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15957                        /*
15958                         * Send the intent to the required verification agent,
15959                         * but only start the verification timeout after the
15960                         * target BroadcastReceivers have run.
15961                         */
15962                        verification.setComponent(requiredVerifierComponent);
15963                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15964                                mRequiredVerifierPackage, idleDuration,
15965                                verifierUser.getIdentifier(), false, "package verifier");
15966                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15967                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15968                                new BroadcastReceiver() {
15969                                    @Override
15970                                    public void onReceive(Context context, Intent intent) {
15971                                        final Message msg = mHandler
15972                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15973                                        msg.arg1 = verificationId;
15974                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15975                                    }
15976                                }, null, 0, null, null);
15977
15978                        /*
15979                         * We don't want the copy to proceed until verification
15980                         * succeeds, so null out this field.
15981                         */
15982                        mArgs = null;
15983                    }
15984                } else {
15985                    /*
15986                     * No package verification is enabled, so immediately start
15987                     * the remote call to initiate copy using temporary file.
15988                     */
15989                    ret = args.copyApk(mContainerService, true);
15990                }
15991            }
15992
15993            mRet = ret;
15994        }
15995
15996        @Override
15997        void handleReturnCode() {
15998            // If mArgs is null, then MCS couldn't be reached. When it
15999            // reconnects, it will try again to install. At that point, this
16000            // will succeed.
16001            if (mArgs != null) {
16002                processPendingInstall(mArgs, mRet);
16003            }
16004        }
16005
16006        @Override
16007        void handleServiceError() {
16008            mArgs = createInstallArgs(this);
16009            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16010        }
16011
16012        public boolean isForwardLocked() {
16013            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16014        }
16015    }
16016
16017    /**
16018     * Used during creation of InstallArgs
16019     *
16020     * @param installFlags package installation flags
16021     * @return true if should be installed on external storage
16022     */
16023    private static boolean installOnExternalAsec(int installFlags) {
16024        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16025            return false;
16026        }
16027        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16028            return true;
16029        }
16030        return false;
16031    }
16032
16033    /**
16034     * Used during creation of InstallArgs
16035     *
16036     * @param installFlags package installation flags
16037     * @return true if should be installed as forward locked
16038     */
16039    private static boolean installForwardLocked(int installFlags) {
16040        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16041    }
16042
16043    private InstallArgs createInstallArgs(InstallParams params) {
16044        if (params.move != null) {
16045            return new MoveInstallArgs(params);
16046        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16047            return new AsecInstallArgs(params);
16048        } else {
16049            return new FileInstallArgs(params);
16050        }
16051    }
16052
16053    /**
16054     * Create args that describe an existing installed package. Typically used
16055     * when cleaning up old installs, or used as a move source.
16056     */
16057    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16058            String resourcePath, String[] instructionSets) {
16059        final boolean isInAsec;
16060        if (installOnExternalAsec(installFlags)) {
16061            /* Apps on SD card are always in ASEC containers. */
16062            isInAsec = true;
16063        } else if (installForwardLocked(installFlags)
16064                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16065            /*
16066             * Forward-locked apps are only in ASEC containers if they're the
16067             * new style
16068             */
16069            isInAsec = true;
16070        } else {
16071            isInAsec = false;
16072        }
16073
16074        if (isInAsec) {
16075            return new AsecInstallArgs(codePath, instructionSets,
16076                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16077        } else {
16078            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16079        }
16080    }
16081
16082    static abstract class InstallArgs {
16083        /** @see InstallParams#origin */
16084        final OriginInfo origin;
16085        /** @see InstallParams#move */
16086        final MoveInfo move;
16087
16088        final IPackageInstallObserver2 observer;
16089        // Always refers to PackageManager flags only
16090        final int installFlags;
16091        final String installerPackageName;
16092        final String volumeUuid;
16093        final UserHandle user;
16094        final String abiOverride;
16095        final String[] installGrantPermissions;
16096        /** If non-null, drop an async trace when the install completes */
16097        final String traceMethod;
16098        final int traceCookie;
16099        final Certificate[][] certificates;
16100        final int installReason;
16101
16102        // The list of instruction sets supported by this app. This is currently
16103        // only used during the rmdex() phase to clean up resources. We can get rid of this
16104        // if we move dex files under the common app path.
16105        /* nullable */ String[] instructionSets;
16106
16107        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16108                int installFlags, String installerPackageName, String volumeUuid,
16109                UserHandle user, String[] instructionSets,
16110                String abiOverride, String[] installGrantPermissions,
16111                String traceMethod, int traceCookie, Certificate[][] certificates,
16112                int installReason) {
16113            this.origin = origin;
16114            this.move = move;
16115            this.installFlags = installFlags;
16116            this.observer = observer;
16117            this.installerPackageName = installerPackageName;
16118            this.volumeUuid = volumeUuid;
16119            this.user = user;
16120            this.instructionSets = instructionSets;
16121            this.abiOverride = abiOverride;
16122            this.installGrantPermissions = installGrantPermissions;
16123            this.traceMethod = traceMethod;
16124            this.traceCookie = traceCookie;
16125            this.certificates = certificates;
16126            this.installReason = installReason;
16127        }
16128
16129        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16130        abstract int doPreInstall(int status);
16131
16132        /**
16133         * Rename package into final resting place. All paths on the given
16134         * scanned package should be updated to reflect the rename.
16135         */
16136        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16137        abstract int doPostInstall(int status, int uid);
16138
16139        /** @see PackageSettingBase#codePathString */
16140        abstract String getCodePath();
16141        /** @see PackageSettingBase#resourcePathString */
16142        abstract String getResourcePath();
16143
16144        // Need installer lock especially for dex file removal.
16145        abstract void cleanUpResourcesLI();
16146        abstract boolean doPostDeleteLI(boolean delete);
16147
16148        /**
16149         * Called before the source arguments are copied. This is used mostly
16150         * for MoveParams when it needs to read the source file to put it in the
16151         * destination.
16152         */
16153        int doPreCopy() {
16154            return PackageManager.INSTALL_SUCCEEDED;
16155        }
16156
16157        /**
16158         * Called after the source arguments are copied. This is used mostly for
16159         * MoveParams when it needs to read the source file to put it in the
16160         * destination.
16161         */
16162        int doPostCopy(int uid) {
16163            return PackageManager.INSTALL_SUCCEEDED;
16164        }
16165
16166        protected boolean isFwdLocked() {
16167            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16168        }
16169
16170        protected boolean isExternalAsec() {
16171            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16172        }
16173
16174        protected boolean isEphemeral() {
16175            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16176        }
16177
16178        UserHandle getUser() {
16179            return user;
16180        }
16181    }
16182
16183    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16184        if (!allCodePaths.isEmpty()) {
16185            if (instructionSets == null) {
16186                throw new IllegalStateException("instructionSet == null");
16187            }
16188            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16189            for (String codePath : allCodePaths) {
16190                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16191                    try {
16192                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16193                    } catch (InstallerException ignored) {
16194                    }
16195                }
16196            }
16197        }
16198    }
16199
16200    /**
16201     * Logic to handle installation of non-ASEC applications, including copying
16202     * and renaming logic.
16203     */
16204    class FileInstallArgs extends InstallArgs {
16205        private File codeFile;
16206        private File resourceFile;
16207
16208        // Example topology:
16209        // /data/app/com.example/base.apk
16210        // /data/app/com.example/split_foo.apk
16211        // /data/app/com.example/lib/arm/libfoo.so
16212        // /data/app/com.example/lib/arm64/libfoo.so
16213        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16214
16215        /** New install */
16216        FileInstallArgs(InstallParams params) {
16217            super(params.origin, params.move, params.observer, params.installFlags,
16218                    params.installerPackageName, params.volumeUuid,
16219                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16220                    params.grantedRuntimePermissions,
16221                    params.traceMethod, params.traceCookie, params.certificates,
16222                    params.installReason);
16223            if (isFwdLocked()) {
16224                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16225            }
16226        }
16227
16228        /** Existing install */
16229        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16230            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16231                    null, null, null, 0, null /*certificates*/,
16232                    PackageManager.INSTALL_REASON_UNKNOWN);
16233            this.codeFile = (codePath != null) ? new File(codePath) : null;
16234            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16235        }
16236
16237        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16238            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16239            try {
16240                return doCopyApk(imcs, temp);
16241            } finally {
16242                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16243            }
16244        }
16245
16246        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16247            if (origin.staged) {
16248                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16249                codeFile = origin.file;
16250                resourceFile = origin.file;
16251                return PackageManager.INSTALL_SUCCEEDED;
16252            }
16253
16254            try {
16255                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16256                final File tempDir =
16257                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16258                codeFile = tempDir;
16259                resourceFile = tempDir;
16260            } catch (IOException e) {
16261                Slog.w(TAG, "Failed to create copy file: " + e);
16262                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16263            }
16264
16265            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16266                @Override
16267                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16268                    if (!FileUtils.isValidExtFilename(name)) {
16269                        throw new IllegalArgumentException("Invalid filename: " + name);
16270                    }
16271                    try {
16272                        final File file = new File(codeFile, name);
16273                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16274                                O_RDWR | O_CREAT, 0644);
16275                        Os.chmod(file.getAbsolutePath(), 0644);
16276                        return new ParcelFileDescriptor(fd);
16277                    } catch (ErrnoException e) {
16278                        throw new RemoteException("Failed to open: " + e.getMessage());
16279                    }
16280                }
16281            };
16282
16283            int ret = PackageManager.INSTALL_SUCCEEDED;
16284            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16285            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16286                Slog.e(TAG, "Failed to copy package");
16287                return ret;
16288            }
16289
16290            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16291            NativeLibraryHelper.Handle handle = null;
16292            try {
16293                handle = NativeLibraryHelper.Handle.create(codeFile);
16294                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16295                        abiOverride);
16296            } catch (IOException e) {
16297                Slog.e(TAG, "Copying native libraries failed", e);
16298                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16299            } finally {
16300                IoUtils.closeQuietly(handle);
16301            }
16302
16303            return ret;
16304        }
16305
16306        int doPreInstall(int status) {
16307            if (status != PackageManager.INSTALL_SUCCEEDED) {
16308                cleanUp();
16309            }
16310            return status;
16311        }
16312
16313        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16314            if (status != PackageManager.INSTALL_SUCCEEDED) {
16315                cleanUp();
16316                return false;
16317            }
16318
16319            final File targetDir = codeFile.getParentFile();
16320            final File beforeCodeFile = codeFile;
16321            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16322
16323            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16324            try {
16325                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16326            } catch (ErrnoException e) {
16327                Slog.w(TAG, "Failed to rename", e);
16328                return false;
16329            }
16330
16331            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16332                Slog.w(TAG, "Failed to restorecon");
16333                return false;
16334            }
16335
16336            // Reflect the rename internally
16337            codeFile = afterCodeFile;
16338            resourceFile = afterCodeFile;
16339
16340            // Reflect the rename in scanned details
16341            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16342            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16343                    afterCodeFile, pkg.baseCodePath));
16344            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16345                    afterCodeFile, pkg.splitCodePaths));
16346
16347            // Reflect the rename in app info
16348            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16349            pkg.setApplicationInfoCodePath(pkg.codePath);
16350            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16351            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16352            pkg.setApplicationInfoResourcePath(pkg.codePath);
16353            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16354            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16355
16356            return true;
16357        }
16358
16359        int doPostInstall(int status, int uid) {
16360            if (status != PackageManager.INSTALL_SUCCEEDED) {
16361                cleanUp();
16362            }
16363            return status;
16364        }
16365
16366        @Override
16367        String getCodePath() {
16368            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16369        }
16370
16371        @Override
16372        String getResourcePath() {
16373            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16374        }
16375
16376        private boolean cleanUp() {
16377            if (codeFile == null || !codeFile.exists()) {
16378                return false;
16379            }
16380
16381            removeCodePathLI(codeFile);
16382
16383            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16384                resourceFile.delete();
16385            }
16386
16387            return true;
16388        }
16389
16390        void cleanUpResourcesLI() {
16391            // Try enumerating all code paths before deleting
16392            List<String> allCodePaths = Collections.EMPTY_LIST;
16393            if (codeFile != null && codeFile.exists()) {
16394                try {
16395                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16396                    allCodePaths = pkg.getAllCodePaths();
16397                } catch (PackageParserException e) {
16398                    // Ignored; we tried our best
16399                }
16400            }
16401
16402            cleanUp();
16403            removeDexFiles(allCodePaths, instructionSets);
16404        }
16405
16406        boolean doPostDeleteLI(boolean delete) {
16407            // XXX err, shouldn't we respect the delete flag?
16408            cleanUpResourcesLI();
16409            return true;
16410        }
16411    }
16412
16413    private boolean isAsecExternal(String cid) {
16414        final String asecPath = PackageHelper.getSdFilesystem(cid);
16415        return !asecPath.startsWith(mAsecInternalPath);
16416    }
16417
16418    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16419            PackageManagerException {
16420        if (copyRet < 0) {
16421            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16422                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16423                throw new PackageManagerException(copyRet, message);
16424            }
16425        }
16426    }
16427
16428    /**
16429     * Extract the StorageManagerService "container ID" from the full code path of an
16430     * .apk.
16431     */
16432    static String cidFromCodePath(String fullCodePath) {
16433        int eidx = fullCodePath.lastIndexOf("/");
16434        String subStr1 = fullCodePath.substring(0, eidx);
16435        int sidx = subStr1.lastIndexOf("/");
16436        return subStr1.substring(sidx+1, eidx);
16437    }
16438
16439    /**
16440     * Logic to handle installation of ASEC applications, including copying and
16441     * renaming logic.
16442     */
16443    class AsecInstallArgs extends InstallArgs {
16444        static final String RES_FILE_NAME = "pkg.apk";
16445        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16446
16447        String cid;
16448        String packagePath;
16449        String resourcePath;
16450
16451        /** New install */
16452        AsecInstallArgs(InstallParams params) {
16453            super(params.origin, params.move, params.observer, params.installFlags,
16454                    params.installerPackageName, params.volumeUuid,
16455                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16456                    params.grantedRuntimePermissions,
16457                    params.traceMethod, params.traceCookie, params.certificates,
16458                    params.installReason);
16459        }
16460
16461        /** Existing install */
16462        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16463                        boolean isExternal, boolean isForwardLocked) {
16464            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16465                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16466                    instructionSets, null, null, null, 0, null /*certificates*/,
16467                    PackageManager.INSTALL_REASON_UNKNOWN);
16468            // Hackily pretend we're still looking at a full code path
16469            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16470                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16471            }
16472
16473            // Extract cid from fullCodePath
16474            int eidx = fullCodePath.lastIndexOf("/");
16475            String subStr1 = fullCodePath.substring(0, eidx);
16476            int sidx = subStr1.lastIndexOf("/");
16477            cid = subStr1.substring(sidx+1, eidx);
16478            setMountPath(subStr1);
16479        }
16480
16481        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16482            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16483                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16484                    instructionSets, null, null, null, 0, null /*certificates*/,
16485                    PackageManager.INSTALL_REASON_UNKNOWN);
16486            this.cid = cid;
16487            setMountPath(PackageHelper.getSdDir(cid));
16488        }
16489
16490        void createCopyFile() {
16491            cid = mInstallerService.allocateExternalStageCidLegacy();
16492        }
16493
16494        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16495            if (origin.staged && origin.cid != null) {
16496                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16497                cid = origin.cid;
16498                setMountPath(PackageHelper.getSdDir(cid));
16499                return PackageManager.INSTALL_SUCCEEDED;
16500            }
16501
16502            if (temp) {
16503                createCopyFile();
16504            } else {
16505                /*
16506                 * Pre-emptively destroy the container since it's destroyed if
16507                 * copying fails due to it existing anyway.
16508                 */
16509                PackageHelper.destroySdDir(cid);
16510            }
16511
16512            final String newMountPath = imcs.copyPackageToContainer(
16513                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16514                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16515
16516            if (newMountPath != null) {
16517                setMountPath(newMountPath);
16518                return PackageManager.INSTALL_SUCCEEDED;
16519            } else {
16520                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16521            }
16522        }
16523
16524        @Override
16525        String getCodePath() {
16526            return packagePath;
16527        }
16528
16529        @Override
16530        String getResourcePath() {
16531            return resourcePath;
16532        }
16533
16534        int doPreInstall(int status) {
16535            if (status != PackageManager.INSTALL_SUCCEEDED) {
16536                // Destroy container
16537                PackageHelper.destroySdDir(cid);
16538            } else {
16539                boolean mounted = PackageHelper.isContainerMounted(cid);
16540                if (!mounted) {
16541                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16542                            Process.SYSTEM_UID);
16543                    if (newMountPath != null) {
16544                        setMountPath(newMountPath);
16545                    } else {
16546                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16547                    }
16548                }
16549            }
16550            return status;
16551        }
16552
16553        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16554            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16555            String newMountPath = null;
16556            if (PackageHelper.isContainerMounted(cid)) {
16557                // Unmount the container
16558                if (!PackageHelper.unMountSdDir(cid)) {
16559                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16560                    return false;
16561                }
16562            }
16563            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16564                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16565                        " which might be stale. Will try to clean up.");
16566                // Clean up the stale container and proceed to recreate.
16567                if (!PackageHelper.destroySdDir(newCacheId)) {
16568                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16569                    return false;
16570                }
16571                // Successfully cleaned up stale container. Try to rename again.
16572                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16573                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16574                            + " inspite of cleaning it up.");
16575                    return false;
16576                }
16577            }
16578            if (!PackageHelper.isContainerMounted(newCacheId)) {
16579                Slog.w(TAG, "Mounting container " + newCacheId);
16580                newMountPath = PackageHelper.mountSdDir(newCacheId,
16581                        getEncryptKey(), Process.SYSTEM_UID);
16582            } else {
16583                newMountPath = PackageHelper.getSdDir(newCacheId);
16584            }
16585            if (newMountPath == null) {
16586                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16587                return false;
16588            }
16589            Log.i(TAG, "Succesfully renamed " + cid +
16590                    " to " + newCacheId +
16591                    " at new path: " + newMountPath);
16592            cid = newCacheId;
16593
16594            final File beforeCodeFile = new File(packagePath);
16595            setMountPath(newMountPath);
16596            final File afterCodeFile = new File(packagePath);
16597
16598            // Reflect the rename in scanned details
16599            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16600            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16601                    afterCodeFile, pkg.baseCodePath));
16602            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16603                    afterCodeFile, pkg.splitCodePaths));
16604
16605            // Reflect the rename in app info
16606            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16607            pkg.setApplicationInfoCodePath(pkg.codePath);
16608            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16609            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16610            pkg.setApplicationInfoResourcePath(pkg.codePath);
16611            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16612            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16613
16614            return true;
16615        }
16616
16617        private void setMountPath(String mountPath) {
16618            final File mountFile = new File(mountPath);
16619
16620            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16621            if (monolithicFile.exists()) {
16622                packagePath = monolithicFile.getAbsolutePath();
16623                if (isFwdLocked()) {
16624                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16625                } else {
16626                    resourcePath = packagePath;
16627                }
16628            } else {
16629                packagePath = mountFile.getAbsolutePath();
16630                resourcePath = packagePath;
16631            }
16632        }
16633
16634        int doPostInstall(int status, int uid) {
16635            if (status != PackageManager.INSTALL_SUCCEEDED) {
16636                cleanUp();
16637            } else {
16638                final int groupOwner;
16639                final String protectedFile;
16640                if (isFwdLocked()) {
16641                    groupOwner = UserHandle.getSharedAppGid(uid);
16642                    protectedFile = RES_FILE_NAME;
16643                } else {
16644                    groupOwner = -1;
16645                    protectedFile = null;
16646                }
16647
16648                if (uid < Process.FIRST_APPLICATION_UID
16649                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16650                    Slog.e(TAG, "Failed to finalize " + cid);
16651                    PackageHelper.destroySdDir(cid);
16652                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16653                }
16654
16655                boolean mounted = PackageHelper.isContainerMounted(cid);
16656                if (!mounted) {
16657                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16658                }
16659            }
16660            return status;
16661        }
16662
16663        private void cleanUp() {
16664            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16665
16666            // Destroy secure container
16667            PackageHelper.destroySdDir(cid);
16668        }
16669
16670        private List<String> getAllCodePaths() {
16671            final File codeFile = new File(getCodePath());
16672            if (codeFile != null && codeFile.exists()) {
16673                try {
16674                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16675                    return pkg.getAllCodePaths();
16676                } catch (PackageParserException e) {
16677                    // Ignored; we tried our best
16678                }
16679            }
16680            return Collections.EMPTY_LIST;
16681        }
16682
16683        void cleanUpResourcesLI() {
16684            // Enumerate all code paths before deleting
16685            cleanUpResourcesLI(getAllCodePaths());
16686        }
16687
16688        private void cleanUpResourcesLI(List<String> allCodePaths) {
16689            cleanUp();
16690            removeDexFiles(allCodePaths, instructionSets);
16691        }
16692
16693        String getPackageName() {
16694            return getAsecPackageName(cid);
16695        }
16696
16697        boolean doPostDeleteLI(boolean delete) {
16698            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16699            final List<String> allCodePaths = getAllCodePaths();
16700            boolean mounted = PackageHelper.isContainerMounted(cid);
16701            if (mounted) {
16702                // Unmount first
16703                if (PackageHelper.unMountSdDir(cid)) {
16704                    mounted = false;
16705                }
16706            }
16707            if (!mounted && delete) {
16708                cleanUpResourcesLI(allCodePaths);
16709            }
16710            return !mounted;
16711        }
16712
16713        @Override
16714        int doPreCopy() {
16715            if (isFwdLocked()) {
16716                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16717                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16718                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16719                }
16720            }
16721
16722            return PackageManager.INSTALL_SUCCEEDED;
16723        }
16724
16725        @Override
16726        int doPostCopy(int uid) {
16727            if (isFwdLocked()) {
16728                if (uid < Process.FIRST_APPLICATION_UID
16729                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16730                                RES_FILE_NAME)) {
16731                    Slog.e(TAG, "Failed to finalize " + cid);
16732                    PackageHelper.destroySdDir(cid);
16733                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16734                }
16735            }
16736
16737            return PackageManager.INSTALL_SUCCEEDED;
16738        }
16739    }
16740
16741    /**
16742     * Logic to handle movement of existing installed applications.
16743     */
16744    class MoveInstallArgs extends InstallArgs {
16745        private File codeFile;
16746        private File resourceFile;
16747
16748        /** New install */
16749        MoveInstallArgs(InstallParams params) {
16750            super(params.origin, params.move, params.observer, params.installFlags,
16751                    params.installerPackageName, params.volumeUuid,
16752                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16753                    params.grantedRuntimePermissions,
16754                    params.traceMethod, params.traceCookie, params.certificates,
16755                    params.installReason);
16756        }
16757
16758        int copyApk(IMediaContainerService imcs, boolean temp) {
16759            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16760                    + move.fromUuid + " to " + move.toUuid);
16761            synchronized (mInstaller) {
16762                try {
16763                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16764                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16765                } catch (InstallerException e) {
16766                    Slog.w(TAG, "Failed to move app", e);
16767                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16768                }
16769            }
16770
16771            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16772            resourceFile = codeFile;
16773            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16774
16775            return PackageManager.INSTALL_SUCCEEDED;
16776        }
16777
16778        int doPreInstall(int status) {
16779            if (status != PackageManager.INSTALL_SUCCEEDED) {
16780                cleanUp(move.toUuid);
16781            }
16782            return status;
16783        }
16784
16785        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16786            if (status != PackageManager.INSTALL_SUCCEEDED) {
16787                cleanUp(move.toUuid);
16788                return false;
16789            }
16790
16791            // Reflect the move in app info
16792            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16793            pkg.setApplicationInfoCodePath(pkg.codePath);
16794            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16795            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16796            pkg.setApplicationInfoResourcePath(pkg.codePath);
16797            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16798            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16799
16800            return true;
16801        }
16802
16803        int doPostInstall(int status, int uid) {
16804            if (status == PackageManager.INSTALL_SUCCEEDED) {
16805                cleanUp(move.fromUuid);
16806            } else {
16807                cleanUp(move.toUuid);
16808            }
16809            return status;
16810        }
16811
16812        @Override
16813        String getCodePath() {
16814            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16815        }
16816
16817        @Override
16818        String getResourcePath() {
16819            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16820        }
16821
16822        private boolean cleanUp(String volumeUuid) {
16823            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16824                    move.dataAppName);
16825            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16826            final int[] userIds = sUserManager.getUserIds();
16827            synchronized (mInstallLock) {
16828                // Clean up both app data and code
16829                // All package moves are frozen until finished
16830                for (int userId : userIds) {
16831                    try {
16832                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16833                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16834                    } catch (InstallerException e) {
16835                        Slog.w(TAG, String.valueOf(e));
16836                    }
16837                }
16838                removeCodePathLI(codeFile);
16839            }
16840            return true;
16841        }
16842
16843        void cleanUpResourcesLI() {
16844            throw new UnsupportedOperationException();
16845        }
16846
16847        boolean doPostDeleteLI(boolean delete) {
16848            throw new UnsupportedOperationException();
16849        }
16850    }
16851
16852    static String getAsecPackageName(String packageCid) {
16853        int idx = packageCid.lastIndexOf("-");
16854        if (idx == -1) {
16855            return packageCid;
16856        }
16857        return packageCid.substring(0, idx);
16858    }
16859
16860    // Utility method used to create code paths based on package name and available index.
16861    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16862        String idxStr = "";
16863        int idx = 1;
16864        // Fall back to default value of idx=1 if prefix is not
16865        // part of oldCodePath
16866        if (oldCodePath != null) {
16867            String subStr = oldCodePath;
16868            // Drop the suffix right away
16869            if (suffix != null && subStr.endsWith(suffix)) {
16870                subStr = subStr.substring(0, subStr.length() - suffix.length());
16871            }
16872            // If oldCodePath already contains prefix find out the
16873            // ending index to either increment or decrement.
16874            int sidx = subStr.lastIndexOf(prefix);
16875            if (sidx != -1) {
16876                subStr = subStr.substring(sidx + prefix.length());
16877                if (subStr != null) {
16878                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16879                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16880                    }
16881                    try {
16882                        idx = Integer.parseInt(subStr);
16883                        if (idx <= 1) {
16884                            idx++;
16885                        } else {
16886                            idx--;
16887                        }
16888                    } catch(NumberFormatException e) {
16889                    }
16890                }
16891            }
16892        }
16893        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16894        return prefix + idxStr;
16895    }
16896
16897    private File getNextCodePath(File targetDir, String packageName) {
16898        File result;
16899        SecureRandom random = new SecureRandom();
16900        byte[] bytes = new byte[16];
16901        do {
16902            random.nextBytes(bytes);
16903            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16904            result = new File(targetDir, packageName + "-" + suffix);
16905        } while (result.exists());
16906        return result;
16907    }
16908
16909    // Utility method that returns the relative package path with respect
16910    // to the installation directory. Like say for /data/data/com.test-1.apk
16911    // string com.test-1 is returned.
16912    static String deriveCodePathName(String codePath) {
16913        if (codePath == null) {
16914            return null;
16915        }
16916        final File codeFile = new File(codePath);
16917        final String name = codeFile.getName();
16918        if (codeFile.isDirectory()) {
16919            return name;
16920        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16921            final int lastDot = name.lastIndexOf('.');
16922            return name.substring(0, lastDot);
16923        } else {
16924            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16925            return null;
16926        }
16927    }
16928
16929    static class PackageInstalledInfo {
16930        String name;
16931        int uid;
16932        // The set of users that originally had this package installed.
16933        int[] origUsers;
16934        // The set of users that now have this package installed.
16935        int[] newUsers;
16936        PackageParser.Package pkg;
16937        int returnCode;
16938        String returnMsg;
16939        PackageRemovedInfo removedInfo;
16940        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16941
16942        public void setError(int code, String msg) {
16943            setReturnCode(code);
16944            setReturnMessage(msg);
16945            Slog.w(TAG, msg);
16946        }
16947
16948        public void setError(String msg, PackageParserException e) {
16949            setReturnCode(e.error);
16950            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16951            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16952            for (int i = 0; i < childCount; i++) {
16953                addedChildPackages.valueAt(i).setError(msg, e);
16954            }
16955            Slog.w(TAG, msg, e);
16956        }
16957
16958        public void setError(String msg, PackageManagerException e) {
16959            returnCode = e.error;
16960            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16961            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16962            for (int i = 0; i < childCount; i++) {
16963                addedChildPackages.valueAt(i).setError(msg, e);
16964            }
16965            Slog.w(TAG, msg, e);
16966        }
16967
16968        public void setReturnCode(int returnCode) {
16969            this.returnCode = returnCode;
16970            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16971            for (int i = 0; i < childCount; i++) {
16972                addedChildPackages.valueAt(i).returnCode = returnCode;
16973            }
16974        }
16975
16976        private void setReturnMessage(String returnMsg) {
16977            this.returnMsg = returnMsg;
16978            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16979            for (int i = 0; i < childCount; i++) {
16980                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16981            }
16982        }
16983
16984        // In some error cases we want to convey more info back to the observer
16985        String origPackage;
16986        String origPermission;
16987    }
16988
16989    /*
16990     * Install a non-existing package.
16991     */
16992    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16993            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16994            PackageInstalledInfo res, int installReason) {
16995        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16996
16997        // Remember this for later, in case we need to rollback this install
16998        String pkgName = pkg.packageName;
16999
17000        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17001
17002        synchronized(mPackages) {
17003            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17004            if (renamedPackage != null) {
17005                // A package with the same name is already installed, though
17006                // it has been renamed to an older name.  The package we
17007                // are trying to install should be installed as an update to
17008                // the existing one, but that has not been requested, so bail.
17009                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17010                        + " without first uninstalling package running as "
17011                        + renamedPackage);
17012                return;
17013            }
17014            if (mPackages.containsKey(pkgName)) {
17015                // Don't allow installation over an existing package with the same name.
17016                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17017                        + " without first uninstalling.");
17018                return;
17019            }
17020        }
17021
17022        try {
17023            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17024                    System.currentTimeMillis(), user);
17025
17026            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17027
17028            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17029                prepareAppDataAfterInstallLIF(newPackage);
17030
17031            } else {
17032                // Remove package from internal structures, but keep around any
17033                // data that might have already existed
17034                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17035                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17036            }
17037        } catch (PackageManagerException e) {
17038            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17039        }
17040
17041        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17042    }
17043
17044    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17045        // Can't rotate keys during boot or if sharedUser.
17046        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17047                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17048            return false;
17049        }
17050        // app is using upgradeKeySets; make sure all are valid
17051        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17052        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17053        for (int i = 0; i < upgradeKeySets.length; i++) {
17054            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17055                Slog.wtf(TAG, "Package "
17056                         + (oldPs.name != null ? oldPs.name : "<null>")
17057                         + " contains upgrade-key-set reference to unknown key-set: "
17058                         + upgradeKeySets[i]
17059                         + " reverting to signatures check.");
17060                return false;
17061            }
17062        }
17063        return true;
17064    }
17065
17066    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17067        // Upgrade keysets are being used.  Determine if new package has a superset of the
17068        // required keys.
17069        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17070        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17071        for (int i = 0; i < upgradeKeySets.length; i++) {
17072            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17073            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17074                return true;
17075            }
17076        }
17077        return false;
17078    }
17079
17080    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17081        try (DigestInputStream digestStream =
17082                new DigestInputStream(new FileInputStream(file), digest)) {
17083            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17084        }
17085    }
17086
17087    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17088            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17089            int installReason) {
17090        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17091
17092        final PackageParser.Package oldPackage;
17093        final PackageSetting ps;
17094        final String pkgName = pkg.packageName;
17095        final int[] allUsers;
17096        final int[] installedUsers;
17097
17098        synchronized(mPackages) {
17099            oldPackage = mPackages.get(pkgName);
17100            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17101
17102            // don't allow upgrade to target a release SDK from a pre-release SDK
17103            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17104                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17105            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17106                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17107            if (oldTargetsPreRelease
17108                    && !newTargetsPreRelease
17109                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17110                Slog.w(TAG, "Can't install package targeting released sdk");
17111                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17112                return;
17113            }
17114
17115            ps = mSettings.mPackages.get(pkgName);
17116
17117            // verify signatures are valid
17118            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17119                if (!checkUpgradeKeySetLP(ps, pkg)) {
17120                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17121                            "New package not signed by keys specified by upgrade-keysets: "
17122                                    + pkgName);
17123                    return;
17124                }
17125            } else {
17126                // default to original signature matching
17127                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17128                        != PackageManager.SIGNATURE_MATCH) {
17129                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17130                            "New package has a different signature: " + pkgName);
17131                    return;
17132                }
17133            }
17134
17135            // don't allow a system upgrade unless the upgrade hash matches
17136            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17137                byte[] digestBytes = null;
17138                try {
17139                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17140                    updateDigest(digest, new File(pkg.baseCodePath));
17141                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17142                        for (String path : pkg.splitCodePaths) {
17143                            updateDigest(digest, new File(path));
17144                        }
17145                    }
17146                    digestBytes = digest.digest();
17147                } catch (NoSuchAlgorithmException | IOException e) {
17148                    res.setError(INSTALL_FAILED_INVALID_APK,
17149                            "Could not compute hash: " + pkgName);
17150                    return;
17151                }
17152                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17153                    res.setError(INSTALL_FAILED_INVALID_APK,
17154                            "New package fails restrict-update check: " + pkgName);
17155                    return;
17156                }
17157                // retain upgrade restriction
17158                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17159            }
17160
17161            // Check for shared user id changes
17162            String invalidPackageName =
17163                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17164            if (invalidPackageName != null) {
17165                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17166                        "Package " + invalidPackageName + " tried to change user "
17167                                + oldPackage.mSharedUserId);
17168                return;
17169            }
17170
17171            // In case of rollback, remember per-user/profile install state
17172            allUsers = sUserManager.getUserIds();
17173            installedUsers = ps.queryInstalledUsers(allUsers, true);
17174
17175            // don't allow an upgrade from full to ephemeral
17176            if (isInstantApp) {
17177                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17178                    for (int currentUser : allUsers) {
17179                        if (!ps.getInstantApp(currentUser)) {
17180                            // can't downgrade from full to instant
17181                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17182                                    + " for user: " + currentUser);
17183                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17184                            return;
17185                        }
17186                    }
17187                } else if (!ps.getInstantApp(user.getIdentifier())) {
17188                    // can't downgrade from full to instant
17189                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17190                            + " for user: " + user.getIdentifier());
17191                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17192                    return;
17193                }
17194            }
17195        }
17196
17197        // Update what is removed
17198        res.removedInfo = new PackageRemovedInfo(this);
17199        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17200        res.removedInfo.removedPackage = oldPackage.packageName;
17201        res.removedInfo.installerPackageName = ps.installerPackageName;
17202        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17203        res.removedInfo.isUpdate = true;
17204        res.removedInfo.origUsers = installedUsers;
17205        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17206        for (int i = 0; i < installedUsers.length; i++) {
17207            final int userId = installedUsers[i];
17208            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17209        }
17210
17211        final int childCount = (oldPackage.childPackages != null)
17212                ? oldPackage.childPackages.size() : 0;
17213        for (int i = 0; i < childCount; i++) {
17214            boolean childPackageUpdated = false;
17215            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17216            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17217            if (res.addedChildPackages != null) {
17218                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17219                if (childRes != null) {
17220                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17221                    childRes.removedInfo.removedPackage = childPkg.packageName;
17222                    if (childPs != null) {
17223                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17224                    }
17225                    childRes.removedInfo.isUpdate = true;
17226                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17227                    childPackageUpdated = true;
17228                }
17229            }
17230            if (!childPackageUpdated) {
17231                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17232                childRemovedRes.removedPackage = childPkg.packageName;
17233                if (childPs != null) {
17234                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17235                }
17236                childRemovedRes.isUpdate = false;
17237                childRemovedRes.dataRemoved = true;
17238                synchronized (mPackages) {
17239                    if (childPs != null) {
17240                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17241                    }
17242                }
17243                if (res.removedInfo.removedChildPackages == null) {
17244                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17245                }
17246                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17247            }
17248        }
17249
17250        boolean sysPkg = (isSystemApp(oldPackage));
17251        if (sysPkg) {
17252            // Set the system/privileged flags as needed
17253            final boolean privileged =
17254                    (oldPackage.applicationInfo.privateFlags
17255                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17256            final int systemPolicyFlags = policyFlags
17257                    | PackageParser.PARSE_IS_SYSTEM
17258                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17259
17260            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17261                    user, allUsers, installerPackageName, res, installReason);
17262        } else {
17263            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17264                    user, allUsers, installerPackageName, res, installReason);
17265        }
17266    }
17267
17268    @Override
17269    public List<String> getPreviousCodePaths(String packageName) {
17270        final int callingUid = Binder.getCallingUid();
17271        final List<String> result = new ArrayList<>();
17272        if (getInstantAppPackageName(callingUid) != null) {
17273            return result;
17274        }
17275        final PackageSetting ps = mSettings.mPackages.get(packageName);
17276        if (ps != null
17277                && ps.oldCodePaths != null
17278                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17279            result.addAll(ps.oldCodePaths);
17280        }
17281        return result;
17282    }
17283
17284    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17285            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17286            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17287            int installReason) {
17288        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17289                + deletedPackage);
17290
17291        String pkgName = deletedPackage.packageName;
17292        boolean deletedPkg = true;
17293        boolean addedPkg = false;
17294        boolean updatedSettings = false;
17295        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17296        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17297                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17298
17299        final long origUpdateTime = (pkg.mExtras != null)
17300                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17301
17302        // First delete the existing package while retaining the data directory
17303        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17304                res.removedInfo, true, pkg)) {
17305            // If the existing package wasn't successfully deleted
17306            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17307            deletedPkg = false;
17308        } else {
17309            // Successfully deleted the old package; proceed with replace.
17310
17311            // If deleted package lived in a container, give users a chance to
17312            // relinquish resources before killing.
17313            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17314                if (DEBUG_INSTALL) {
17315                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17316                }
17317                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17318                final ArrayList<String> pkgList = new ArrayList<String>(1);
17319                pkgList.add(deletedPackage.applicationInfo.packageName);
17320                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17321            }
17322
17323            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17324                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17325            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17326
17327            try {
17328                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17329                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17330                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17331                        installReason);
17332
17333                // Update the in-memory copy of the previous code paths.
17334                PackageSetting ps = mSettings.mPackages.get(pkgName);
17335                if (!killApp) {
17336                    if (ps.oldCodePaths == null) {
17337                        ps.oldCodePaths = new ArraySet<>();
17338                    }
17339                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17340                    if (deletedPackage.splitCodePaths != null) {
17341                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17342                    }
17343                } else {
17344                    ps.oldCodePaths = null;
17345                }
17346                if (ps.childPackageNames != null) {
17347                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17348                        final String childPkgName = ps.childPackageNames.get(i);
17349                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17350                        childPs.oldCodePaths = ps.oldCodePaths;
17351                    }
17352                }
17353                // set instant app status, but, only if it's explicitly specified
17354                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17355                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17356                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17357                prepareAppDataAfterInstallLIF(newPackage);
17358                addedPkg = true;
17359                mDexManager.notifyPackageUpdated(newPackage.packageName,
17360                        newPackage.baseCodePath, newPackage.splitCodePaths);
17361            } catch (PackageManagerException e) {
17362                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17363            }
17364        }
17365
17366        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17367            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17368
17369            // Revert all internal state mutations and added folders for the failed install
17370            if (addedPkg) {
17371                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17372                        res.removedInfo, true, null);
17373            }
17374
17375            // Restore the old package
17376            if (deletedPkg) {
17377                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17378                File restoreFile = new File(deletedPackage.codePath);
17379                // Parse old package
17380                boolean oldExternal = isExternal(deletedPackage);
17381                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17382                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17383                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17384                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17385                try {
17386                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17387                            null);
17388                } catch (PackageManagerException e) {
17389                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17390                            + e.getMessage());
17391                    return;
17392                }
17393
17394                synchronized (mPackages) {
17395                    // Ensure the installer package name up to date
17396                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17397
17398                    // Update permissions for restored package
17399                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17400
17401                    mSettings.writeLPr();
17402                }
17403
17404                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17405            }
17406        } else {
17407            synchronized (mPackages) {
17408                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17409                if (ps != null) {
17410                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17411                    if (res.removedInfo.removedChildPackages != null) {
17412                        final int childCount = res.removedInfo.removedChildPackages.size();
17413                        // Iterate in reverse as we may modify the collection
17414                        for (int i = childCount - 1; i >= 0; i--) {
17415                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17416                            if (res.addedChildPackages.containsKey(childPackageName)) {
17417                                res.removedInfo.removedChildPackages.removeAt(i);
17418                            } else {
17419                                PackageRemovedInfo childInfo = res.removedInfo
17420                                        .removedChildPackages.valueAt(i);
17421                                childInfo.removedForAllUsers = mPackages.get(
17422                                        childInfo.removedPackage) == null;
17423                            }
17424                        }
17425                    }
17426                }
17427            }
17428        }
17429    }
17430
17431    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17432            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17433            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17434            int installReason) {
17435        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17436                + ", old=" + deletedPackage);
17437
17438        final boolean disabledSystem;
17439
17440        // Remove existing system package
17441        removePackageLI(deletedPackage, true);
17442
17443        synchronized (mPackages) {
17444            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17445        }
17446        if (!disabledSystem) {
17447            // We didn't need to disable the .apk as a current system package,
17448            // which means we are replacing another update that is already
17449            // installed.  We need to make sure to delete the older one's .apk.
17450            res.removedInfo.args = createInstallArgsForExisting(0,
17451                    deletedPackage.applicationInfo.getCodePath(),
17452                    deletedPackage.applicationInfo.getResourcePath(),
17453                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17454        } else {
17455            res.removedInfo.args = null;
17456        }
17457
17458        // Successfully disabled the old package. Now proceed with re-installation
17459        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17460                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17461        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17462
17463        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17464        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17465                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17466
17467        PackageParser.Package newPackage = null;
17468        try {
17469            // Add the package to the internal data structures
17470            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17471
17472            // Set the update and install times
17473            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17474            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17475                    System.currentTimeMillis());
17476
17477            // Update the package dynamic state if succeeded
17478            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17479                // Now that the install succeeded make sure we remove data
17480                // directories for any child package the update removed.
17481                final int deletedChildCount = (deletedPackage.childPackages != null)
17482                        ? deletedPackage.childPackages.size() : 0;
17483                final int newChildCount = (newPackage.childPackages != null)
17484                        ? newPackage.childPackages.size() : 0;
17485                for (int i = 0; i < deletedChildCount; i++) {
17486                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17487                    boolean childPackageDeleted = true;
17488                    for (int j = 0; j < newChildCount; j++) {
17489                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17490                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17491                            childPackageDeleted = false;
17492                            break;
17493                        }
17494                    }
17495                    if (childPackageDeleted) {
17496                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17497                                deletedChildPkg.packageName);
17498                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17499                            PackageRemovedInfo removedChildRes = res.removedInfo
17500                                    .removedChildPackages.get(deletedChildPkg.packageName);
17501                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17502                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17503                        }
17504                    }
17505                }
17506
17507                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17508                        installReason);
17509                prepareAppDataAfterInstallLIF(newPackage);
17510
17511                mDexManager.notifyPackageUpdated(newPackage.packageName,
17512                            newPackage.baseCodePath, newPackage.splitCodePaths);
17513            }
17514        } catch (PackageManagerException e) {
17515            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17516            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17517        }
17518
17519        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17520            // Re installation failed. Restore old information
17521            // Remove new pkg information
17522            if (newPackage != null) {
17523                removeInstalledPackageLI(newPackage, true);
17524            }
17525            // Add back the old system package
17526            try {
17527                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17528            } catch (PackageManagerException e) {
17529                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17530            }
17531
17532            synchronized (mPackages) {
17533                if (disabledSystem) {
17534                    enableSystemPackageLPw(deletedPackage);
17535                }
17536
17537                // Ensure the installer package name up to date
17538                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17539
17540                // Update permissions for restored package
17541                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17542
17543                mSettings.writeLPr();
17544            }
17545
17546            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17547                    + " after failed upgrade");
17548        }
17549    }
17550
17551    /**
17552     * Checks whether the parent or any of the child packages have a change shared
17553     * user. For a package to be a valid update the shred users of the parent and
17554     * the children should match. We may later support changing child shared users.
17555     * @param oldPkg The updated package.
17556     * @param newPkg The update package.
17557     * @return The shared user that change between the versions.
17558     */
17559    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17560            PackageParser.Package newPkg) {
17561        // Check parent shared user
17562        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17563            return newPkg.packageName;
17564        }
17565        // Check child shared users
17566        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17567        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17568        for (int i = 0; i < newChildCount; i++) {
17569            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17570            // If this child was present, did it have the same shared user?
17571            for (int j = 0; j < oldChildCount; j++) {
17572                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17573                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17574                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17575                    return newChildPkg.packageName;
17576                }
17577            }
17578        }
17579        return null;
17580    }
17581
17582    private void removeNativeBinariesLI(PackageSetting ps) {
17583        // Remove the lib path for the parent package
17584        if (ps != null) {
17585            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17586            // Remove the lib path for the child packages
17587            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17588            for (int i = 0; i < childCount; i++) {
17589                PackageSetting childPs = null;
17590                synchronized (mPackages) {
17591                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17592                }
17593                if (childPs != null) {
17594                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17595                            .legacyNativeLibraryPathString);
17596                }
17597            }
17598        }
17599    }
17600
17601    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17602        // Enable the parent package
17603        mSettings.enableSystemPackageLPw(pkg.packageName);
17604        // Enable the child packages
17605        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17606        for (int i = 0; i < childCount; i++) {
17607            PackageParser.Package childPkg = pkg.childPackages.get(i);
17608            mSettings.enableSystemPackageLPw(childPkg.packageName);
17609        }
17610    }
17611
17612    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17613            PackageParser.Package newPkg) {
17614        // Disable the parent package (parent always replaced)
17615        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17616        // Disable the child packages
17617        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17618        for (int i = 0; i < childCount; i++) {
17619            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17620            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17621            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17622        }
17623        return disabled;
17624    }
17625
17626    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17627            String installerPackageName) {
17628        // Enable the parent package
17629        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17630        // Enable the child packages
17631        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17632        for (int i = 0; i < childCount; i++) {
17633            PackageParser.Package childPkg = pkg.childPackages.get(i);
17634            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17635        }
17636    }
17637
17638    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17639        // Collect all used permissions in the UID
17640        ArraySet<String> usedPermissions = new ArraySet<>();
17641        final int packageCount = su.packages.size();
17642        for (int i = 0; i < packageCount; i++) {
17643            PackageSetting ps = su.packages.valueAt(i);
17644            if (ps.pkg == null) {
17645                continue;
17646            }
17647            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17648            for (int j = 0; j < requestedPermCount; j++) {
17649                String permission = ps.pkg.requestedPermissions.get(j);
17650                BasePermission bp = mSettings.mPermissions.get(permission);
17651                if (bp != null) {
17652                    usedPermissions.add(permission);
17653                }
17654            }
17655        }
17656
17657        PermissionsState permissionsState = su.getPermissionsState();
17658        // Prune install permissions
17659        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17660        final int installPermCount = installPermStates.size();
17661        for (int i = installPermCount - 1; i >= 0;  i--) {
17662            PermissionState permissionState = installPermStates.get(i);
17663            if (!usedPermissions.contains(permissionState.getName())) {
17664                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17665                if (bp != null) {
17666                    permissionsState.revokeInstallPermission(bp);
17667                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17668                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17669                }
17670            }
17671        }
17672
17673        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17674
17675        // Prune runtime permissions
17676        for (int userId : allUserIds) {
17677            List<PermissionState> runtimePermStates = permissionsState
17678                    .getRuntimePermissionStates(userId);
17679            final int runtimePermCount = runtimePermStates.size();
17680            for (int i = runtimePermCount - 1; i >= 0; i--) {
17681                PermissionState permissionState = runtimePermStates.get(i);
17682                if (!usedPermissions.contains(permissionState.getName())) {
17683                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17684                    if (bp != null) {
17685                        permissionsState.revokeRuntimePermission(bp, userId);
17686                        permissionsState.updatePermissionFlags(bp, userId,
17687                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17688                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17689                                runtimePermissionChangedUserIds, userId);
17690                    }
17691                }
17692            }
17693        }
17694
17695        return runtimePermissionChangedUserIds;
17696    }
17697
17698    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17699            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17700        // Update the parent package setting
17701        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17702                res, user, installReason);
17703        // Update the child packages setting
17704        final int childCount = (newPackage.childPackages != null)
17705                ? newPackage.childPackages.size() : 0;
17706        for (int i = 0; i < childCount; i++) {
17707            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17708            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17709            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17710                    childRes.origUsers, childRes, user, installReason);
17711        }
17712    }
17713
17714    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17715            String installerPackageName, int[] allUsers, int[] installedForUsers,
17716            PackageInstalledInfo res, UserHandle user, int installReason) {
17717        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17718
17719        String pkgName = newPackage.packageName;
17720        synchronized (mPackages) {
17721            //write settings. the installStatus will be incomplete at this stage.
17722            //note that the new package setting would have already been
17723            //added to mPackages. It hasn't been persisted yet.
17724            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17725            // TODO: Remove this write? It's also written at the end of this method
17726            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17727            mSettings.writeLPr();
17728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17729        }
17730
17731        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17732        synchronized (mPackages) {
17733            updatePermissionsLPw(newPackage.packageName, newPackage,
17734                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17735                            ? UPDATE_PERMISSIONS_ALL : 0));
17736            // For system-bundled packages, we assume that installing an upgraded version
17737            // of the package implies that the user actually wants to run that new code,
17738            // so we enable the package.
17739            PackageSetting ps = mSettings.mPackages.get(pkgName);
17740            final int userId = user.getIdentifier();
17741            if (ps != null) {
17742                if (isSystemApp(newPackage)) {
17743                    if (DEBUG_INSTALL) {
17744                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17745                    }
17746                    // Enable system package for requested users
17747                    if (res.origUsers != null) {
17748                        for (int origUserId : res.origUsers) {
17749                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17750                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17751                                        origUserId, installerPackageName);
17752                            }
17753                        }
17754                    }
17755                    // Also convey the prior install/uninstall state
17756                    if (allUsers != null && installedForUsers != null) {
17757                        for (int currentUserId : allUsers) {
17758                            final boolean installed = ArrayUtils.contains(
17759                                    installedForUsers, currentUserId);
17760                            if (DEBUG_INSTALL) {
17761                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17762                            }
17763                            ps.setInstalled(installed, currentUserId);
17764                        }
17765                        // these install state changes will be persisted in the
17766                        // upcoming call to mSettings.writeLPr().
17767                    }
17768                }
17769                // It's implied that when a user requests installation, they want the app to be
17770                // installed and enabled.
17771                if (userId != UserHandle.USER_ALL) {
17772                    ps.setInstalled(true, userId);
17773                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17774                }
17775
17776                // When replacing an existing package, preserve the original install reason for all
17777                // users that had the package installed before.
17778                final Set<Integer> previousUserIds = new ArraySet<>();
17779                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17780                    final int installReasonCount = res.removedInfo.installReasons.size();
17781                    for (int i = 0; i < installReasonCount; i++) {
17782                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17783                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17784                        ps.setInstallReason(previousInstallReason, previousUserId);
17785                        previousUserIds.add(previousUserId);
17786                    }
17787                }
17788
17789                // Set install reason for users that are having the package newly installed.
17790                if (userId == UserHandle.USER_ALL) {
17791                    for (int currentUserId : sUserManager.getUserIds()) {
17792                        if (!previousUserIds.contains(currentUserId)) {
17793                            ps.setInstallReason(installReason, currentUserId);
17794                        }
17795                    }
17796                } else if (!previousUserIds.contains(userId)) {
17797                    ps.setInstallReason(installReason, userId);
17798                }
17799                mSettings.writeKernelMappingLPr(ps);
17800            }
17801            res.name = pkgName;
17802            res.uid = newPackage.applicationInfo.uid;
17803            res.pkg = newPackage;
17804            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17805            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17806            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17807            //to update install status
17808            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17809            mSettings.writeLPr();
17810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17811        }
17812
17813        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17814    }
17815
17816    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17817        try {
17818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17819            installPackageLI(args, res);
17820        } finally {
17821            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17822        }
17823    }
17824
17825    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17826        final int installFlags = args.installFlags;
17827        final String installerPackageName = args.installerPackageName;
17828        final String volumeUuid = args.volumeUuid;
17829        final File tmpPackageFile = new File(args.getCodePath());
17830        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17831        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17832                || (args.volumeUuid != null));
17833        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17834        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17835        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17836        boolean replace = false;
17837        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17838        if (args.move != null) {
17839            // moving a complete application; perform an initial scan on the new install location
17840            scanFlags |= SCAN_INITIAL;
17841        }
17842        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17843            scanFlags |= SCAN_DONT_KILL_APP;
17844        }
17845        if (instantApp) {
17846            scanFlags |= SCAN_AS_INSTANT_APP;
17847        }
17848        if (fullApp) {
17849            scanFlags |= SCAN_AS_FULL_APP;
17850        }
17851
17852        // Result object to be returned
17853        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17854
17855        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17856
17857        // Sanity check
17858        if (instantApp && (forwardLocked || onExternal)) {
17859            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17860                    + " external=" + onExternal);
17861            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17862            return;
17863        }
17864
17865        // Retrieve PackageSettings and parse package
17866        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17867                | PackageParser.PARSE_ENFORCE_CODE
17868                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17869                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17870                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17871                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17872        PackageParser pp = new PackageParser();
17873        pp.setSeparateProcesses(mSeparateProcesses);
17874        pp.setDisplayMetrics(mMetrics);
17875        pp.setCallback(mPackageParserCallback);
17876
17877        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17878        final PackageParser.Package pkg;
17879        try {
17880            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17881        } catch (PackageParserException e) {
17882            res.setError("Failed parse during installPackageLI", e);
17883            return;
17884        } finally {
17885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17886        }
17887
17888        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17889        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17890            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17891            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17892                    "Instant app package must target O");
17893            return;
17894        }
17895        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17896            Slog.w(TAG, "Instant app package " + pkg.packageName
17897                    + " does not target targetSandboxVersion 2");
17898            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17899                    "Instant app package must use targetSanboxVersion 2");
17900            return;
17901        }
17902
17903        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17904            // Static shared libraries have synthetic package names
17905            renameStaticSharedLibraryPackage(pkg);
17906
17907            // No static shared libs on external storage
17908            if (onExternal) {
17909                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17910                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17911                        "Packages declaring static-shared libs cannot be updated");
17912                return;
17913            }
17914        }
17915
17916        // If we are installing a clustered package add results for the children
17917        if (pkg.childPackages != null) {
17918            synchronized (mPackages) {
17919                final int childCount = pkg.childPackages.size();
17920                for (int i = 0; i < childCount; i++) {
17921                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17922                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17923                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17924                    childRes.pkg = childPkg;
17925                    childRes.name = childPkg.packageName;
17926                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17927                    if (childPs != null) {
17928                        childRes.origUsers = childPs.queryInstalledUsers(
17929                                sUserManager.getUserIds(), true);
17930                    }
17931                    if ((mPackages.containsKey(childPkg.packageName))) {
17932                        childRes.removedInfo = new PackageRemovedInfo(this);
17933                        childRes.removedInfo.removedPackage = childPkg.packageName;
17934                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17935                    }
17936                    if (res.addedChildPackages == null) {
17937                        res.addedChildPackages = new ArrayMap<>();
17938                    }
17939                    res.addedChildPackages.put(childPkg.packageName, childRes);
17940                }
17941            }
17942        }
17943
17944        // If package doesn't declare API override, mark that we have an install
17945        // time CPU ABI override.
17946        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17947            pkg.cpuAbiOverride = args.abiOverride;
17948        }
17949
17950        String pkgName = res.name = pkg.packageName;
17951        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17952            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17953                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17954                return;
17955            }
17956        }
17957
17958        try {
17959            // either use what we've been given or parse directly from the APK
17960            if (args.certificates != null) {
17961                try {
17962                    PackageParser.populateCertificates(pkg, args.certificates);
17963                } catch (PackageParserException e) {
17964                    // there was something wrong with the certificates we were given;
17965                    // try to pull them from the APK
17966                    PackageParser.collectCertificates(pkg, parseFlags);
17967                }
17968            } else {
17969                PackageParser.collectCertificates(pkg, parseFlags);
17970            }
17971        } catch (PackageParserException e) {
17972            res.setError("Failed collect during installPackageLI", e);
17973            return;
17974        }
17975
17976        // Get rid of all references to package scan path via parser.
17977        pp = null;
17978        String oldCodePath = null;
17979        boolean systemApp = false;
17980        synchronized (mPackages) {
17981            // Check if installing already existing package
17982            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17983                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17984                if (pkg.mOriginalPackages != null
17985                        && pkg.mOriginalPackages.contains(oldName)
17986                        && mPackages.containsKey(oldName)) {
17987                    // This package is derived from an original package,
17988                    // and this device has been updating from that original
17989                    // name.  We must continue using the original name, so
17990                    // rename the new package here.
17991                    pkg.setPackageName(oldName);
17992                    pkgName = pkg.packageName;
17993                    replace = true;
17994                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17995                            + oldName + " pkgName=" + pkgName);
17996                } else if (mPackages.containsKey(pkgName)) {
17997                    // This package, under its official name, already exists
17998                    // on the device; we should replace it.
17999                    replace = true;
18000                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18001                }
18002
18003                // Child packages are installed through the parent package
18004                if (pkg.parentPackage != null) {
18005                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18006                            "Package " + pkg.packageName + " is child of package "
18007                                    + pkg.parentPackage.parentPackage + ". Child packages "
18008                                    + "can be updated only through the parent package.");
18009                    return;
18010                }
18011
18012                if (replace) {
18013                    // Prevent apps opting out from runtime permissions
18014                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18015                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18016                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18017                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18018                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18019                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18020                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18021                                        + " doesn't support runtime permissions but the old"
18022                                        + " target SDK " + oldTargetSdk + " does.");
18023                        return;
18024                    }
18025                    // Prevent apps from downgrading their targetSandbox.
18026                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18027                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18028                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18029                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18030                                "Package " + pkg.packageName + " new target sandbox "
18031                                + newTargetSandbox + " is incompatible with the previous value of"
18032                                + oldTargetSandbox + ".");
18033                        return;
18034                    }
18035
18036                    // Prevent installing of child packages
18037                    if (oldPackage.parentPackage != null) {
18038                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18039                                "Package " + pkg.packageName + " is child of package "
18040                                        + oldPackage.parentPackage + ". Child packages "
18041                                        + "can be updated only through the parent package.");
18042                        return;
18043                    }
18044                }
18045            }
18046
18047            PackageSetting ps = mSettings.mPackages.get(pkgName);
18048            if (ps != null) {
18049                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18050
18051                // Static shared libs have same package with different versions where
18052                // we internally use a synthetic package name to allow multiple versions
18053                // of the same package, therefore we need to compare signatures against
18054                // the package setting for the latest library version.
18055                PackageSetting signatureCheckPs = ps;
18056                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18057                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18058                    if (libraryEntry != null) {
18059                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18060                    }
18061                }
18062
18063                // Quick sanity check that we're signed correctly if updating;
18064                // we'll check this again later when scanning, but we want to
18065                // bail early here before tripping over redefined permissions.
18066                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18067                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18068                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18069                                + pkg.packageName + " upgrade keys do not match the "
18070                                + "previously installed version");
18071                        return;
18072                    }
18073                } else {
18074                    try {
18075                        verifySignaturesLP(signatureCheckPs, pkg);
18076                    } catch (PackageManagerException e) {
18077                        res.setError(e.error, e.getMessage());
18078                        return;
18079                    }
18080                }
18081
18082                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18083                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18084                    systemApp = (ps.pkg.applicationInfo.flags &
18085                            ApplicationInfo.FLAG_SYSTEM) != 0;
18086                }
18087                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18088            }
18089
18090            int N = pkg.permissions.size();
18091            for (int i = N-1; i >= 0; i--) {
18092                PackageParser.Permission perm = pkg.permissions.get(i);
18093                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18094
18095                // Don't allow anyone but the system to define ephemeral permissions.
18096                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18097                        && !systemApp) {
18098                    Slog.w(TAG, "Non-System package " + pkg.packageName
18099                            + " attempting to delcare ephemeral permission "
18100                            + perm.info.name + "; Removing ephemeral.");
18101                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18102                }
18103                // Check whether the newly-scanned package wants to define an already-defined perm
18104                if (bp != null) {
18105                    // If the defining package is signed with our cert, it's okay.  This
18106                    // also includes the "updating the same package" case, of course.
18107                    // "updating same package" could also involve key-rotation.
18108                    final boolean sigsOk;
18109                    if (bp.sourcePackage.equals(pkg.packageName)
18110                            && (bp.packageSetting instanceof PackageSetting)
18111                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18112                                    scanFlags))) {
18113                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18114                    } else {
18115                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18116                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18117                    }
18118                    if (!sigsOk) {
18119                        // If the owning package is the system itself, we log but allow
18120                        // install to proceed; we fail the install on all other permission
18121                        // redefinitions.
18122                        if (!bp.sourcePackage.equals("android")) {
18123                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18124                                    + pkg.packageName + " attempting to redeclare permission "
18125                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18126                            res.origPermission = perm.info.name;
18127                            res.origPackage = bp.sourcePackage;
18128                            return;
18129                        } else {
18130                            Slog.w(TAG, "Package " + pkg.packageName
18131                                    + " attempting to redeclare system permission "
18132                                    + perm.info.name + "; ignoring new declaration");
18133                            pkg.permissions.remove(i);
18134                        }
18135                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18136                        // Prevent apps to change protection level to dangerous from any other
18137                        // type as this would allow a privilege escalation where an app adds a
18138                        // normal/signature permission in other app's group and later redefines
18139                        // it as dangerous leading to the group auto-grant.
18140                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18141                                == PermissionInfo.PROTECTION_DANGEROUS) {
18142                            if (bp != null && !bp.isRuntime()) {
18143                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18144                                        + "non-runtime permission " + perm.info.name
18145                                        + " to runtime; keeping old protection level");
18146                                perm.info.protectionLevel = bp.protectionLevel;
18147                            }
18148                        }
18149                    }
18150                }
18151            }
18152        }
18153
18154        if (systemApp) {
18155            if (onExternal) {
18156                // Abort update; system app can't be replaced with app on sdcard
18157                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18158                        "Cannot install updates to system apps on sdcard");
18159                return;
18160            } else if (instantApp) {
18161                // Abort update; system app can't be replaced with an instant app
18162                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18163                        "Cannot update a system app with an instant app");
18164                return;
18165            }
18166        }
18167
18168        if (args.move != null) {
18169            // We did an in-place move, so dex is ready to roll
18170            scanFlags |= SCAN_NO_DEX;
18171            scanFlags |= SCAN_MOVE;
18172
18173            synchronized (mPackages) {
18174                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18175                if (ps == null) {
18176                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18177                            "Missing settings for moved package " + pkgName);
18178                }
18179
18180                // We moved the entire application as-is, so bring over the
18181                // previously derived ABI information.
18182                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18183                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18184            }
18185
18186        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18187            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18188            scanFlags |= SCAN_NO_DEX;
18189
18190            try {
18191                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18192                    args.abiOverride : pkg.cpuAbiOverride);
18193                final boolean extractNativeLibs = !pkg.isLibrary();
18194                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18195                        extractNativeLibs, mAppLib32InstallDir);
18196            } catch (PackageManagerException pme) {
18197                Slog.e(TAG, "Error deriving application ABI", pme);
18198                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18199                return;
18200            }
18201
18202            // Shared libraries for the package need to be updated.
18203            synchronized (mPackages) {
18204                try {
18205                    updateSharedLibrariesLPr(pkg, null);
18206                } catch (PackageManagerException e) {
18207                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18208                }
18209            }
18210
18211            // dexopt can take some time to complete, so, for instant apps, we skip this
18212            // step during installation. Instead, we'll take extra time the first time the
18213            // instant app starts. It's preferred to do it this way to provide continuous
18214            // progress to the user instead of mysteriously blocking somewhere in the
18215            // middle of running an instant app. The default behaviour can be overridden
18216            // via gservices.
18217            if (!instantApp || Global.getInt(
18218                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18219                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18220                // Do not run PackageDexOptimizer through the local performDexOpt
18221                // method because `pkg` may not be in `mPackages` yet.
18222                //
18223                // Also, don't fail application installs if the dexopt step fails.
18224                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18225                        null /* instructionSets */, false /* checkProfiles */,
18226                        getCompilerFilterForReason(REASON_INSTALL),
18227                        getOrCreateCompilerPackageStats(pkg),
18228                        mDexManager.isUsedByOtherApps(pkg.packageName),
18229                        true /* bootComplete */);
18230                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18231            }
18232
18233            // Notify BackgroundDexOptService that the package has been changed.
18234            // If this is an update of a package which used to fail to compile,
18235            // BDOS will remove it from its blacklist.
18236            // TODO: Layering violation
18237            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18238        }
18239
18240        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18241            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18242            return;
18243        }
18244
18245        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18246
18247        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18248                "installPackageLI")) {
18249            if (replace) {
18250                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18251                    // Static libs have a synthetic package name containing the version
18252                    // and cannot be updated as an update would get a new package name,
18253                    // unless this is the exact same version code which is useful for
18254                    // development.
18255                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18256                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18257                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18258                                + "static-shared libs cannot be updated");
18259                        return;
18260                    }
18261                }
18262                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18263                        installerPackageName, res, args.installReason);
18264            } else {
18265                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18266                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18267            }
18268        }
18269
18270        synchronized (mPackages) {
18271            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18272            if (ps != null) {
18273                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18274                ps.setUpdateAvailable(false /*updateAvailable*/);
18275            }
18276
18277            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18278            for (int i = 0; i < childCount; i++) {
18279                PackageParser.Package childPkg = pkg.childPackages.get(i);
18280                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18281                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18282                if (childPs != null) {
18283                    childRes.newUsers = childPs.queryInstalledUsers(
18284                            sUserManager.getUserIds(), true);
18285                }
18286            }
18287
18288            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18289                updateSequenceNumberLP(ps, res.newUsers);
18290                updateInstantAppInstallerLocked(pkgName);
18291            }
18292        }
18293    }
18294
18295    private void startIntentFilterVerifications(int userId, boolean replacing,
18296            PackageParser.Package pkg) {
18297        if (mIntentFilterVerifierComponent == null) {
18298            Slog.w(TAG, "No IntentFilter verification will not be done as "
18299                    + "there is no IntentFilterVerifier available!");
18300            return;
18301        }
18302
18303        final int verifierUid = getPackageUid(
18304                mIntentFilterVerifierComponent.getPackageName(),
18305                MATCH_DEBUG_TRIAGED_MISSING,
18306                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18307
18308        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18309        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18310        mHandler.sendMessage(msg);
18311
18312        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18313        for (int i = 0; i < childCount; i++) {
18314            PackageParser.Package childPkg = pkg.childPackages.get(i);
18315            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18316            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18317            mHandler.sendMessage(msg);
18318        }
18319    }
18320
18321    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18322            PackageParser.Package pkg) {
18323        int size = pkg.activities.size();
18324        if (size == 0) {
18325            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18326                    "No activity, so no need to verify any IntentFilter!");
18327            return;
18328        }
18329
18330        final boolean hasDomainURLs = hasDomainURLs(pkg);
18331        if (!hasDomainURLs) {
18332            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18333                    "No domain URLs, so no need to verify any IntentFilter!");
18334            return;
18335        }
18336
18337        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18338                + " if any IntentFilter from the " + size
18339                + " Activities needs verification ...");
18340
18341        int count = 0;
18342        final String packageName = pkg.packageName;
18343
18344        synchronized (mPackages) {
18345            // If this is a new install and we see that we've already run verification for this
18346            // package, we have nothing to do: it means the state was restored from backup.
18347            if (!replacing) {
18348                IntentFilterVerificationInfo ivi =
18349                        mSettings.getIntentFilterVerificationLPr(packageName);
18350                if (ivi != null) {
18351                    if (DEBUG_DOMAIN_VERIFICATION) {
18352                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18353                                + ivi.getStatusString());
18354                    }
18355                    return;
18356                }
18357            }
18358
18359            // If any filters need to be verified, then all need to be.
18360            boolean needToVerify = false;
18361            for (PackageParser.Activity a : pkg.activities) {
18362                for (ActivityIntentInfo filter : a.intents) {
18363                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18364                        if (DEBUG_DOMAIN_VERIFICATION) {
18365                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18366                        }
18367                        needToVerify = true;
18368                        break;
18369                    }
18370                }
18371            }
18372
18373            if (needToVerify) {
18374                final int verificationId = mIntentFilterVerificationToken++;
18375                for (PackageParser.Activity a : pkg.activities) {
18376                    for (ActivityIntentInfo filter : a.intents) {
18377                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18378                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18379                                    "Verification needed for IntentFilter:" + filter.toString());
18380                            mIntentFilterVerifier.addOneIntentFilterVerification(
18381                                    verifierUid, userId, verificationId, filter, packageName);
18382                            count++;
18383                        }
18384                    }
18385                }
18386            }
18387        }
18388
18389        if (count > 0) {
18390            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18391                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18392                    +  " for userId:" + userId);
18393            mIntentFilterVerifier.startVerifications(userId);
18394        } else {
18395            if (DEBUG_DOMAIN_VERIFICATION) {
18396                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18397            }
18398        }
18399    }
18400
18401    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18402        final ComponentName cn  = filter.activity.getComponentName();
18403        final String packageName = cn.getPackageName();
18404
18405        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18406                packageName);
18407        if (ivi == null) {
18408            return true;
18409        }
18410        int status = ivi.getStatus();
18411        switch (status) {
18412            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18413            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18414                return true;
18415
18416            default:
18417                // Nothing to do
18418                return false;
18419        }
18420    }
18421
18422    private static boolean isMultiArch(ApplicationInfo info) {
18423        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18424    }
18425
18426    private static boolean isExternal(PackageParser.Package pkg) {
18427        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18428    }
18429
18430    private static boolean isExternal(PackageSetting ps) {
18431        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18432    }
18433
18434    private static boolean isSystemApp(PackageParser.Package pkg) {
18435        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18436    }
18437
18438    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18439        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18440    }
18441
18442    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18443        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18444    }
18445
18446    private static boolean isSystemApp(PackageSetting ps) {
18447        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18448    }
18449
18450    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18451        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18452    }
18453
18454    private int packageFlagsToInstallFlags(PackageSetting ps) {
18455        int installFlags = 0;
18456        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18457            // This existing package was an external ASEC install when we have
18458            // the external flag without a UUID
18459            installFlags |= PackageManager.INSTALL_EXTERNAL;
18460        }
18461        if (ps.isForwardLocked()) {
18462            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18463        }
18464        return installFlags;
18465    }
18466
18467    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18468        if (isExternal(pkg)) {
18469            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18470                return StorageManager.UUID_PRIMARY_PHYSICAL;
18471            } else {
18472                return pkg.volumeUuid;
18473            }
18474        } else {
18475            return StorageManager.UUID_PRIVATE_INTERNAL;
18476        }
18477    }
18478
18479    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18480        if (isExternal(pkg)) {
18481            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18482                return mSettings.getExternalVersion();
18483            } else {
18484                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18485            }
18486        } else {
18487            return mSettings.getInternalVersion();
18488        }
18489    }
18490
18491    private void deleteTempPackageFiles() {
18492        final FilenameFilter filter = new FilenameFilter() {
18493            public boolean accept(File dir, String name) {
18494                return name.startsWith("vmdl") && name.endsWith(".tmp");
18495            }
18496        };
18497        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18498            file.delete();
18499        }
18500    }
18501
18502    @Override
18503    public void deletePackageAsUser(String packageName, int versionCode,
18504            IPackageDeleteObserver observer, int userId, int flags) {
18505        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18506                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18507    }
18508
18509    @Override
18510    public void deletePackageVersioned(VersionedPackage versionedPackage,
18511            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18512        final int callingUid = Binder.getCallingUid();
18513        mContext.enforceCallingOrSelfPermission(
18514                android.Manifest.permission.DELETE_PACKAGES, null);
18515        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18516        Preconditions.checkNotNull(versionedPackage);
18517        Preconditions.checkNotNull(observer);
18518        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18519                PackageManager.VERSION_CODE_HIGHEST,
18520                Integer.MAX_VALUE, "versionCode must be >= -1");
18521
18522        final String packageName = versionedPackage.getPackageName();
18523        final int versionCode = versionedPackage.getVersionCode();
18524        final String internalPackageName;
18525        synchronized (mPackages) {
18526            // Normalize package name to handle renamed packages and static libs
18527            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18528                    versionedPackage.getVersionCode());
18529        }
18530
18531        final int uid = Binder.getCallingUid();
18532        if (!isOrphaned(internalPackageName)
18533                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18534            try {
18535                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18536                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18537                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18538                observer.onUserActionRequired(intent);
18539            } catch (RemoteException re) {
18540            }
18541            return;
18542        }
18543        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18544        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18545        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18546            mContext.enforceCallingOrSelfPermission(
18547                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18548                    "deletePackage for user " + userId);
18549        }
18550
18551        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18552            try {
18553                observer.onPackageDeleted(packageName,
18554                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18555            } catch (RemoteException re) {
18556            }
18557            return;
18558        }
18559
18560        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18561            try {
18562                observer.onPackageDeleted(packageName,
18563                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18564            } catch (RemoteException re) {
18565            }
18566            return;
18567        }
18568
18569        if (DEBUG_REMOVE) {
18570            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18571                    + " deleteAllUsers: " + deleteAllUsers + " version="
18572                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18573                    ? "VERSION_CODE_HIGHEST" : versionCode));
18574        }
18575        // Queue up an async operation since the package deletion may take a little while.
18576        mHandler.post(new Runnable() {
18577            public void run() {
18578                mHandler.removeCallbacks(this);
18579                int returnCode;
18580                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18581                boolean doDeletePackage = true;
18582                if (ps != null) {
18583                    final boolean targetIsInstantApp =
18584                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18585                    doDeletePackage = !targetIsInstantApp
18586                            || canViewInstantApps;
18587                }
18588                if (doDeletePackage) {
18589                    if (!deleteAllUsers) {
18590                        returnCode = deletePackageX(internalPackageName, versionCode,
18591                                userId, deleteFlags);
18592                    } else {
18593                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18594                                internalPackageName, users);
18595                        // If nobody is blocking uninstall, proceed with delete for all users
18596                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18597                            returnCode = deletePackageX(internalPackageName, versionCode,
18598                                    userId, deleteFlags);
18599                        } else {
18600                            // Otherwise uninstall individually for users with blockUninstalls=false
18601                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18602                            for (int userId : users) {
18603                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18604                                    returnCode = deletePackageX(internalPackageName, versionCode,
18605                                            userId, userFlags);
18606                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18607                                        Slog.w(TAG, "Package delete failed for user " + userId
18608                                                + ", returnCode " + returnCode);
18609                                    }
18610                                }
18611                            }
18612                            // The app has only been marked uninstalled for certain users.
18613                            // We still need to report that delete was blocked
18614                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18615                        }
18616                    }
18617                } else {
18618                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18619                }
18620                try {
18621                    observer.onPackageDeleted(packageName, returnCode, null);
18622                } catch (RemoteException e) {
18623                    Log.i(TAG, "Observer no longer exists.");
18624                } //end catch
18625            } //end run
18626        });
18627    }
18628
18629    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18630        if (pkg.staticSharedLibName != null) {
18631            return pkg.manifestPackageName;
18632        }
18633        return pkg.packageName;
18634    }
18635
18636    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18637        // Handle renamed packages
18638        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18639        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18640
18641        // Is this a static library?
18642        SparseArray<SharedLibraryEntry> versionedLib =
18643                mStaticLibsByDeclaringPackage.get(packageName);
18644        if (versionedLib == null || versionedLib.size() <= 0) {
18645            return packageName;
18646        }
18647
18648        // Figure out which lib versions the caller can see
18649        SparseIntArray versionsCallerCanSee = null;
18650        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18651        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18652                && callingAppId != Process.ROOT_UID) {
18653            versionsCallerCanSee = new SparseIntArray();
18654            String libName = versionedLib.valueAt(0).info.getName();
18655            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18656            if (uidPackages != null) {
18657                for (String uidPackage : uidPackages) {
18658                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18659                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18660                    if (libIdx >= 0) {
18661                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18662                        versionsCallerCanSee.append(libVersion, libVersion);
18663                    }
18664                }
18665            }
18666        }
18667
18668        // Caller can see nothing - done
18669        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18670            return packageName;
18671        }
18672
18673        // Find the version the caller can see and the app version code
18674        SharedLibraryEntry highestVersion = null;
18675        final int versionCount = versionedLib.size();
18676        for (int i = 0; i < versionCount; i++) {
18677            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18678            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18679                    libEntry.info.getVersion()) < 0) {
18680                continue;
18681            }
18682            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18683            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18684                if (libVersionCode == versionCode) {
18685                    return libEntry.apk;
18686                }
18687            } else if (highestVersion == null) {
18688                highestVersion = libEntry;
18689            } else if (libVersionCode  > highestVersion.info
18690                    .getDeclaringPackage().getVersionCode()) {
18691                highestVersion = libEntry;
18692            }
18693        }
18694
18695        if (highestVersion != null) {
18696            return highestVersion.apk;
18697        }
18698
18699        return packageName;
18700    }
18701
18702    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18703        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18704              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18705            return true;
18706        }
18707        final int callingUserId = UserHandle.getUserId(callingUid);
18708        // If the caller installed the pkgName, then allow it to silently uninstall.
18709        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18710            return true;
18711        }
18712
18713        // Allow package verifier to silently uninstall.
18714        if (mRequiredVerifierPackage != null &&
18715                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18716            return true;
18717        }
18718
18719        // Allow package uninstaller to silently uninstall.
18720        if (mRequiredUninstallerPackage != null &&
18721                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18722            return true;
18723        }
18724
18725        // Allow storage manager to silently uninstall.
18726        if (mStorageManagerPackage != null &&
18727                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18728            return true;
18729        }
18730
18731        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18732        // uninstall for device owner provisioning.
18733        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18734                == PERMISSION_GRANTED) {
18735            return true;
18736        }
18737
18738        return false;
18739    }
18740
18741    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18742        int[] result = EMPTY_INT_ARRAY;
18743        for (int userId : userIds) {
18744            if (getBlockUninstallForUser(packageName, userId)) {
18745                result = ArrayUtils.appendInt(result, userId);
18746            }
18747        }
18748        return result;
18749    }
18750
18751    @Override
18752    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18753        final int callingUid = Binder.getCallingUid();
18754        if (getInstantAppPackageName(callingUid) != null
18755                && !isCallerSameApp(packageName, callingUid)) {
18756            return false;
18757        }
18758        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18759    }
18760
18761    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18762        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18763                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18764        try {
18765            if (dpm != null) {
18766                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18767                        /* callingUserOnly =*/ false);
18768                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18769                        : deviceOwnerComponentName.getPackageName();
18770                // Does the package contains the device owner?
18771                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18772                // this check is probably not needed, since DO should be registered as a device
18773                // admin on some user too. (Original bug for this: b/17657954)
18774                if (packageName.equals(deviceOwnerPackageName)) {
18775                    return true;
18776                }
18777                // Does it contain a device admin for any user?
18778                int[] users;
18779                if (userId == UserHandle.USER_ALL) {
18780                    users = sUserManager.getUserIds();
18781                } else {
18782                    users = new int[]{userId};
18783                }
18784                for (int i = 0; i < users.length; ++i) {
18785                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18786                        return true;
18787                    }
18788                }
18789            }
18790        } catch (RemoteException e) {
18791        }
18792        return false;
18793    }
18794
18795    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18796        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18797    }
18798
18799    /**
18800     *  This method is an internal method that could be get invoked either
18801     *  to delete an installed package or to clean up a failed installation.
18802     *  After deleting an installed package, a broadcast is sent to notify any
18803     *  listeners that the package has been removed. For cleaning up a failed
18804     *  installation, the broadcast is not necessary since the package's
18805     *  installation wouldn't have sent the initial broadcast either
18806     *  The key steps in deleting a package are
18807     *  deleting the package information in internal structures like mPackages,
18808     *  deleting the packages base directories through installd
18809     *  updating mSettings to reflect current status
18810     *  persisting settings for later use
18811     *  sending a broadcast if necessary
18812     */
18813    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18814        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18815        final boolean res;
18816
18817        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18818                ? UserHandle.USER_ALL : userId;
18819
18820        if (isPackageDeviceAdmin(packageName, removeUser)) {
18821            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18822            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18823        }
18824
18825        PackageSetting uninstalledPs = null;
18826        PackageParser.Package pkg = null;
18827
18828        // for the uninstall-updates case and restricted profiles, remember the per-
18829        // user handle installed state
18830        int[] allUsers;
18831        synchronized (mPackages) {
18832            uninstalledPs = mSettings.mPackages.get(packageName);
18833            if (uninstalledPs == null) {
18834                Slog.w(TAG, "Not removing non-existent package " + packageName);
18835                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18836            }
18837
18838            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18839                    && uninstalledPs.versionCode != versionCode) {
18840                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18841                        + uninstalledPs.versionCode + " != " + versionCode);
18842                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18843            }
18844
18845            // Static shared libs can be declared by any package, so let us not
18846            // allow removing a package if it provides a lib others depend on.
18847            pkg = mPackages.get(packageName);
18848
18849            allUsers = sUserManager.getUserIds();
18850
18851            if (pkg != null && pkg.staticSharedLibName != null) {
18852                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18853                        pkg.staticSharedLibVersion);
18854                if (libEntry != null) {
18855                    for (int currUserId : allUsers) {
18856                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18857                            continue;
18858                        }
18859                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18860                                libEntry.info, 0, currUserId);
18861                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18862                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18863                                    + " hosting lib " + libEntry.info.getName() + " version "
18864                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18865                                    + " for user " + currUserId);
18866                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18867                        }
18868                    }
18869                }
18870            }
18871
18872            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18873        }
18874
18875        final int freezeUser;
18876        if (isUpdatedSystemApp(uninstalledPs)
18877                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18878            // We're downgrading a system app, which will apply to all users, so
18879            // freeze them all during the downgrade
18880            freezeUser = UserHandle.USER_ALL;
18881        } else {
18882            freezeUser = removeUser;
18883        }
18884
18885        synchronized (mInstallLock) {
18886            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18887            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18888                    deleteFlags, "deletePackageX")) {
18889                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18890                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18891            }
18892            synchronized (mPackages) {
18893                if (res) {
18894                    if (pkg != null) {
18895                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18896                    }
18897                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18898                    updateInstantAppInstallerLocked(packageName);
18899                }
18900            }
18901        }
18902
18903        if (res) {
18904            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18905            info.sendPackageRemovedBroadcasts(killApp);
18906            info.sendSystemPackageUpdatedBroadcasts();
18907            info.sendSystemPackageAppearedBroadcasts();
18908        }
18909        // Force a gc here.
18910        Runtime.getRuntime().gc();
18911        // Delete the resources here after sending the broadcast to let
18912        // other processes clean up before deleting resources.
18913        if (info.args != null) {
18914            synchronized (mInstallLock) {
18915                info.args.doPostDeleteLI(true);
18916            }
18917        }
18918
18919        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18920    }
18921
18922    static class PackageRemovedInfo {
18923        final PackageSender packageSender;
18924        String removedPackage;
18925        String installerPackageName;
18926        int uid = -1;
18927        int removedAppId = -1;
18928        int[] origUsers;
18929        int[] removedUsers = null;
18930        int[] broadcastUsers = null;
18931        SparseArray<Integer> installReasons;
18932        boolean isRemovedPackageSystemUpdate = false;
18933        boolean isUpdate;
18934        boolean dataRemoved;
18935        boolean removedForAllUsers;
18936        boolean isStaticSharedLib;
18937        // Clean up resources deleted packages.
18938        InstallArgs args = null;
18939        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18940        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18941
18942        PackageRemovedInfo(PackageSender packageSender) {
18943            this.packageSender = packageSender;
18944        }
18945
18946        void sendPackageRemovedBroadcasts(boolean killApp) {
18947            sendPackageRemovedBroadcastInternal(killApp);
18948            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18949            for (int i = 0; i < childCount; i++) {
18950                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18951                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18952            }
18953        }
18954
18955        void sendSystemPackageUpdatedBroadcasts() {
18956            if (isRemovedPackageSystemUpdate) {
18957                sendSystemPackageUpdatedBroadcastsInternal();
18958                final int childCount = (removedChildPackages != null)
18959                        ? removedChildPackages.size() : 0;
18960                for (int i = 0; i < childCount; i++) {
18961                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18962                    if (childInfo.isRemovedPackageSystemUpdate) {
18963                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18964                    }
18965                }
18966            }
18967        }
18968
18969        void sendSystemPackageAppearedBroadcasts() {
18970            final int packageCount = (appearedChildPackages != null)
18971                    ? appearedChildPackages.size() : 0;
18972            for (int i = 0; i < packageCount; i++) {
18973                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18974                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18975                    true, UserHandle.getAppId(installedInfo.uid),
18976                    installedInfo.newUsers);
18977            }
18978        }
18979
18980        private void sendSystemPackageUpdatedBroadcastsInternal() {
18981            Bundle extras = new Bundle(2);
18982            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18983            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18984            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18985                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18986            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18987                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18988            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18989                null, null, 0, removedPackage, null, null);
18990            if (installerPackageName != null) {
18991                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18992                        removedPackage, extras, 0 /*flags*/,
18993                        installerPackageName, null, null);
18994                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18995                        removedPackage, extras, 0 /*flags*/,
18996                        installerPackageName, null, null);
18997            }
18998        }
18999
19000        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19001            // Don't send static shared library removal broadcasts as these
19002            // libs are visible only the the apps that depend on them an one
19003            // cannot remove the library if it has a dependency.
19004            if (isStaticSharedLib) {
19005                return;
19006            }
19007            Bundle extras = new Bundle(2);
19008            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19009            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19010            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19011            if (isUpdate || isRemovedPackageSystemUpdate) {
19012                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19013            }
19014            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19015            if (removedPackage != null) {
19016                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19017                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19018                if (installerPackageName != null) {
19019                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19020                            removedPackage, extras, 0 /*flags*/,
19021                            installerPackageName, null, broadcastUsers);
19022                }
19023                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19024                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19025                        removedPackage, extras,
19026                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19027                        null, null, broadcastUsers);
19028                }
19029            }
19030            if (removedAppId >= 0) {
19031                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19032                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19033                    null, null, broadcastUsers);
19034            }
19035        }
19036
19037        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19038            removedUsers = userIds;
19039            if (removedUsers == null) {
19040                broadcastUsers = null;
19041                return;
19042            }
19043
19044            broadcastUsers = EMPTY_INT_ARRAY;
19045            for (int i = userIds.length - 1; i >= 0; --i) {
19046                final int userId = userIds[i];
19047                if (deletedPackageSetting.getInstantApp(userId)) {
19048                    continue;
19049                }
19050                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19051            }
19052        }
19053    }
19054
19055    /*
19056     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19057     * flag is not set, the data directory is removed as well.
19058     * make sure this flag is set for partially installed apps. If not its meaningless to
19059     * delete a partially installed application.
19060     */
19061    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19062            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19063        String packageName = ps.name;
19064        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19065        // Retrieve object to delete permissions for shared user later on
19066        final PackageParser.Package deletedPkg;
19067        final PackageSetting deletedPs;
19068        // reader
19069        synchronized (mPackages) {
19070            deletedPkg = mPackages.get(packageName);
19071            deletedPs = mSettings.mPackages.get(packageName);
19072            if (outInfo != null) {
19073                outInfo.removedPackage = packageName;
19074                outInfo.installerPackageName = ps.installerPackageName;
19075                outInfo.isStaticSharedLib = deletedPkg != null
19076                        && deletedPkg.staticSharedLibName != null;
19077                outInfo.populateUsers(deletedPs == null ? null
19078                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19079            }
19080        }
19081
19082        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19083
19084        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19085            final PackageParser.Package resolvedPkg;
19086            if (deletedPkg != null) {
19087                resolvedPkg = deletedPkg;
19088            } else {
19089                // We don't have a parsed package when it lives on an ejected
19090                // adopted storage device, so fake something together
19091                resolvedPkg = new PackageParser.Package(ps.name);
19092                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19093            }
19094            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19095                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19096            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19097            if (outInfo != null) {
19098                outInfo.dataRemoved = true;
19099            }
19100            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19101        }
19102
19103        int removedAppId = -1;
19104
19105        // writer
19106        synchronized (mPackages) {
19107            boolean installedStateChanged = false;
19108            if (deletedPs != null) {
19109                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19110                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19111                    clearDefaultBrowserIfNeeded(packageName);
19112                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19113                    removedAppId = mSettings.removePackageLPw(packageName);
19114                    if (outInfo != null) {
19115                        outInfo.removedAppId = removedAppId;
19116                    }
19117                    updatePermissionsLPw(deletedPs.name, null, 0);
19118                    if (deletedPs.sharedUser != null) {
19119                        // Remove permissions associated with package. Since runtime
19120                        // permissions are per user we have to kill the removed package
19121                        // or packages running under the shared user of the removed
19122                        // package if revoking the permissions requested only by the removed
19123                        // package is successful and this causes a change in gids.
19124                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19125                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19126                                    userId);
19127                            if (userIdToKill == UserHandle.USER_ALL
19128                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19129                                // If gids changed for this user, kill all affected packages.
19130                                mHandler.post(new Runnable() {
19131                                    @Override
19132                                    public void run() {
19133                                        // This has to happen with no lock held.
19134                                        killApplication(deletedPs.name, deletedPs.appId,
19135                                                KILL_APP_REASON_GIDS_CHANGED);
19136                                    }
19137                                });
19138                                break;
19139                            }
19140                        }
19141                    }
19142                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19143                }
19144                // make sure to preserve per-user disabled state if this removal was just
19145                // a downgrade of a system app to the factory package
19146                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19147                    if (DEBUG_REMOVE) {
19148                        Slog.d(TAG, "Propagating install state across downgrade");
19149                    }
19150                    for (int userId : allUserHandles) {
19151                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19152                        if (DEBUG_REMOVE) {
19153                            Slog.d(TAG, "    user " + userId + " => " + installed);
19154                        }
19155                        if (installed != ps.getInstalled(userId)) {
19156                            installedStateChanged = true;
19157                        }
19158                        ps.setInstalled(installed, userId);
19159                    }
19160                }
19161            }
19162            // can downgrade to reader
19163            if (writeSettings) {
19164                // Save settings now
19165                mSettings.writeLPr();
19166            }
19167            if (installedStateChanged) {
19168                mSettings.writeKernelMappingLPr(ps);
19169            }
19170        }
19171        if (removedAppId != -1) {
19172            // A user ID was deleted here. Go through all users and remove it
19173            // from KeyStore.
19174            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19175        }
19176    }
19177
19178    static boolean locationIsPrivileged(File path) {
19179        try {
19180            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19181                    .getCanonicalPath();
19182            return path.getCanonicalPath().startsWith(privilegedAppDir);
19183        } catch (IOException e) {
19184            Slog.e(TAG, "Unable to access code path " + path);
19185        }
19186        return false;
19187    }
19188
19189    /*
19190     * Tries to delete system package.
19191     */
19192    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19193            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19194            boolean writeSettings) {
19195        if (deletedPs.parentPackageName != null) {
19196            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19197            return false;
19198        }
19199
19200        final boolean applyUserRestrictions
19201                = (allUserHandles != null) && (outInfo.origUsers != null);
19202        final PackageSetting disabledPs;
19203        // Confirm if the system package has been updated
19204        // An updated system app can be deleted. This will also have to restore
19205        // the system pkg from system partition
19206        // reader
19207        synchronized (mPackages) {
19208            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19209        }
19210
19211        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19212                + " disabledPs=" + disabledPs);
19213
19214        if (disabledPs == null) {
19215            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19216            return false;
19217        } else if (DEBUG_REMOVE) {
19218            Slog.d(TAG, "Deleting system pkg from data partition");
19219        }
19220
19221        if (DEBUG_REMOVE) {
19222            if (applyUserRestrictions) {
19223                Slog.d(TAG, "Remembering install states:");
19224                for (int userId : allUserHandles) {
19225                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19226                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19227                }
19228            }
19229        }
19230
19231        // Delete the updated package
19232        outInfo.isRemovedPackageSystemUpdate = true;
19233        if (outInfo.removedChildPackages != null) {
19234            final int childCount = (deletedPs.childPackageNames != null)
19235                    ? deletedPs.childPackageNames.size() : 0;
19236            for (int i = 0; i < childCount; i++) {
19237                String childPackageName = deletedPs.childPackageNames.get(i);
19238                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19239                        .contains(childPackageName)) {
19240                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19241                            childPackageName);
19242                    if (childInfo != null) {
19243                        childInfo.isRemovedPackageSystemUpdate = true;
19244                    }
19245                }
19246            }
19247        }
19248
19249        if (disabledPs.versionCode < deletedPs.versionCode) {
19250            // Delete data for downgrades
19251            flags &= ~PackageManager.DELETE_KEEP_DATA;
19252        } else {
19253            // Preserve data by setting flag
19254            flags |= PackageManager.DELETE_KEEP_DATA;
19255        }
19256
19257        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19258                outInfo, writeSettings, disabledPs.pkg);
19259        if (!ret) {
19260            return false;
19261        }
19262
19263        // writer
19264        synchronized (mPackages) {
19265            // Reinstate the old system package
19266            enableSystemPackageLPw(disabledPs.pkg);
19267            // Remove any native libraries from the upgraded package.
19268            removeNativeBinariesLI(deletedPs);
19269        }
19270
19271        // Install the system package
19272        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19273        int parseFlags = mDefParseFlags
19274                | PackageParser.PARSE_MUST_BE_APK
19275                | PackageParser.PARSE_IS_SYSTEM
19276                | PackageParser.PARSE_IS_SYSTEM_DIR;
19277        if (locationIsPrivileged(disabledPs.codePath)) {
19278            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19279        }
19280
19281        final PackageParser.Package newPkg;
19282        try {
19283            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19284                0 /* currentTime */, null);
19285        } catch (PackageManagerException e) {
19286            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19287                    + e.getMessage());
19288            return false;
19289        }
19290
19291        try {
19292            // update shared libraries for the newly re-installed system package
19293            updateSharedLibrariesLPr(newPkg, null);
19294        } catch (PackageManagerException e) {
19295            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19296        }
19297
19298        prepareAppDataAfterInstallLIF(newPkg);
19299
19300        // writer
19301        synchronized (mPackages) {
19302            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19303
19304            // Propagate the permissions state as we do not want to drop on the floor
19305            // runtime permissions. The update permissions method below will take
19306            // care of removing obsolete permissions and grant install permissions.
19307            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19308            updatePermissionsLPw(newPkg.packageName, newPkg,
19309                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19310
19311            if (applyUserRestrictions) {
19312                boolean installedStateChanged = false;
19313                if (DEBUG_REMOVE) {
19314                    Slog.d(TAG, "Propagating install state across reinstall");
19315                }
19316                for (int userId : allUserHandles) {
19317                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19318                    if (DEBUG_REMOVE) {
19319                        Slog.d(TAG, "    user " + userId + " => " + installed);
19320                    }
19321                    if (installed != ps.getInstalled(userId)) {
19322                        installedStateChanged = true;
19323                    }
19324                    ps.setInstalled(installed, userId);
19325
19326                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19327                }
19328                // Regardless of writeSettings we need to ensure that this restriction
19329                // state propagation is persisted
19330                mSettings.writeAllUsersPackageRestrictionsLPr();
19331                if (installedStateChanged) {
19332                    mSettings.writeKernelMappingLPr(ps);
19333                }
19334            }
19335            // can downgrade to reader here
19336            if (writeSettings) {
19337                mSettings.writeLPr();
19338            }
19339        }
19340        return true;
19341    }
19342
19343    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19344            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19345            PackageRemovedInfo outInfo, boolean writeSettings,
19346            PackageParser.Package replacingPackage) {
19347        synchronized (mPackages) {
19348            if (outInfo != null) {
19349                outInfo.uid = ps.appId;
19350            }
19351
19352            if (outInfo != null && outInfo.removedChildPackages != null) {
19353                final int childCount = (ps.childPackageNames != null)
19354                        ? ps.childPackageNames.size() : 0;
19355                for (int i = 0; i < childCount; i++) {
19356                    String childPackageName = ps.childPackageNames.get(i);
19357                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19358                    if (childPs == null) {
19359                        return false;
19360                    }
19361                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19362                            childPackageName);
19363                    if (childInfo != null) {
19364                        childInfo.uid = childPs.appId;
19365                    }
19366                }
19367            }
19368        }
19369
19370        // Delete package data from internal structures and also remove data if flag is set
19371        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19372
19373        // Delete the child packages data
19374        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19375        for (int i = 0; i < childCount; i++) {
19376            PackageSetting childPs;
19377            synchronized (mPackages) {
19378                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19379            }
19380            if (childPs != null) {
19381                PackageRemovedInfo childOutInfo = (outInfo != null
19382                        && outInfo.removedChildPackages != null)
19383                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19384                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19385                        && (replacingPackage != null
19386                        && !replacingPackage.hasChildPackage(childPs.name))
19387                        ? flags & ~DELETE_KEEP_DATA : flags;
19388                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19389                        deleteFlags, writeSettings);
19390            }
19391        }
19392
19393        // Delete application code and resources only for parent packages
19394        if (ps.parentPackageName == null) {
19395            if (deleteCodeAndResources && (outInfo != null)) {
19396                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19397                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19398                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19399            }
19400        }
19401
19402        return true;
19403    }
19404
19405    @Override
19406    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19407            int userId) {
19408        mContext.enforceCallingOrSelfPermission(
19409                android.Manifest.permission.DELETE_PACKAGES, null);
19410        synchronized (mPackages) {
19411            // Cannot block uninstall of static shared libs as they are
19412            // considered a part of the using app (emulating static linking).
19413            // Also static libs are installed always on internal storage.
19414            PackageParser.Package pkg = mPackages.get(packageName);
19415            if (pkg != null && pkg.staticSharedLibName != null) {
19416                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19417                        + " providing static shared library: " + pkg.staticSharedLibName);
19418                return false;
19419            }
19420            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19421            mSettings.writePackageRestrictionsLPr(userId);
19422        }
19423        return true;
19424    }
19425
19426    @Override
19427    public boolean getBlockUninstallForUser(String packageName, int userId) {
19428        synchronized (mPackages) {
19429            final PackageSetting ps = mSettings.mPackages.get(packageName);
19430            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19431                return false;
19432            }
19433            return mSettings.getBlockUninstallLPr(userId, packageName);
19434        }
19435    }
19436
19437    @Override
19438    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19439        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19440        synchronized (mPackages) {
19441            PackageSetting ps = mSettings.mPackages.get(packageName);
19442            if (ps == null) {
19443                Log.w(TAG, "Package doesn't exist: " + packageName);
19444                return false;
19445            }
19446            if (systemUserApp) {
19447                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19448            } else {
19449                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19450            }
19451            mSettings.writeLPr();
19452        }
19453        return true;
19454    }
19455
19456    /*
19457     * This method handles package deletion in general
19458     */
19459    private boolean deletePackageLIF(String packageName, UserHandle user,
19460            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19461            PackageRemovedInfo outInfo, boolean writeSettings,
19462            PackageParser.Package replacingPackage) {
19463        if (packageName == null) {
19464            Slog.w(TAG, "Attempt to delete null packageName.");
19465            return false;
19466        }
19467
19468        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19469
19470        PackageSetting ps;
19471        synchronized (mPackages) {
19472            ps = mSettings.mPackages.get(packageName);
19473            if (ps == null) {
19474                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19475                return false;
19476            }
19477
19478            if (ps.parentPackageName != null && (!isSystemApp(ps)
19479                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19480                if (DEBUG_REMOVE) {
19481                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19482                            + ((user == null) ? UserHandle.USER_ALL : user));
19483                }
19484                final int removedUserId = (user != null) ? user.getIdentifier()
19485                        : UserHandle.USER_ALL;
19486                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19487                    return false;
19488                }
19489                markPackageUninstalledForUserLPw(ps, user);
19490                scheduleWritePackageRestrictionsLocked(user);
19491                return true;
19492            }
19493        }
19494
19495        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19496                && user.getIdentifier() != UserHandle.USER_ALL)) {
19497            // The caller is asking that the package only be deleted for a single
19498            // user.  To do this, we just mark its uninstalled state and delete
19499            // its data. If this is a system app, we only allow this to happen if
19500            // they have set the special DELETE_SYSTEM_APP which requests different
19501            // semantics than normal for uninstalling system apps.
19502            markPackageUninstalledForUserLPw(ps, user);
19503
19504            if (!isSystemApp(ps)) {
19505                // Do not uninstall the APK if an app should be cached
19506                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19507                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19508                    // Other user still have this package installed, so all
19509                    // we need to do is clear this user's data and save that
19510                    // it is uninstalled.
19511                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19512                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19513                        return false;
19514                    }
19515                    scheduleWritePackageRestrictionsLocked(user);
19516                    return true;
19517                } else {
19518                    // We need to set it back to 'installed' so the uninstall
19519                    // broadcasts will be sent correctly.
19520                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19521                    ps.setInstalled(true, user.getIdentifier());
19522                    mSettings.writeKernelMappingLPr(ps);
19523                }
19524            } else {
19525                // This is a system app, so we assume that the
19526                // other users still have this package installed, so all
19527                // we need to do is clear this user's data and save that
19528                // it is uninstalled.
19529                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19530                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19531                    return false;
19532                }
19533                scheduleWritePackageRestrictionsLocked(user);
19534                return true;
19535            }
19536        }
19537
19538        // If we are deleting a composite package for all users, keep track
19539        // of result for each child.
19540        if (ps.childPackageNames != null && outInfo != null) {
19541            synchronized (mPackages) {
19542                final int childCount = ps.childPackageNames.size();
19543                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19544                for (int i = 0; i < childCount; i++) {
19545                    String childPackageName = ps.childPackageNames.get(i);
19546                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19547                    childInfo.removedPackage = childPackageName;
19548                    childInfo.installerPackageName = ps.installerPackageName;
19549                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19550                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19551                    if (childPs != null) {
19552                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19553                    }
19554                }
19555            }
19556        }
19557
19558        boolean ret = false;
19559        if (isSystemApp(ps)) {
19560            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19561            // When an updated system application is deleted we delete the existing resources
19562            // as well and fall back to existing code in system partition
19563            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19564        } else {
19565            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19566            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19567                    outInfo, writeSettings, replacingPackage);
19568        }
19569
19570        // Take a note whether we deleted the package for all users
19571        if (outInfo != null) {
19572            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19573            if (outInfo.removedChildPackages != null) {
19574                synchronized (mPackages) {
19575                    final int childCount = outInfo.removedChildPackages.size();
19576                    for (int i = 0; i < childCount; i++) {
19577                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19578                        if (childInfo != null) {
19579                            childInfo.removedForAllUsers = mPackages.get(
19580                                    childInfo.removedPackage) == null;
19581                        }
19582                    }
19583                }
19584            }
19585            // If we uninstalled an update to a system app there may be some
19586            // child packages that appeared as they are declared in the system
19587            // app but were not declared in the update.
19588            if (isSystemApp(ps)) {
19589                synchronized (mPackages) {
19590                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19591                    final int childCount = (updatedPs.childPackageNames != null)
19592                            ? updatedPs.childPackageNames.size() : 0;
19593                    for (int i = 0; i < childCount; i++) {
19594                        String childPackageName = updatedPs.childPackageNames.get(i);
19595                        if (outInfo.removedChildPackages == null
19596                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19597                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19598                            if (childPs == null) {
19599                                continue;
19600                            }
19601                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19602                            installRes.name = childPackageName;
19603                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19604                            installRes.pkg = mPackages.get(childPackageName);
19605                            installRes.uid = childPs.pkg.applicationInfo.uid;
19606                            if (outInfo.appearedChildPackages == null) {
19607                                outInfo.appearedChildPackages = new ArrayMap<>();
19608                            }
19609                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19610                        }
19611                    }
19612                }
19613            }
19614        }
19615
19616        return ret;
19617    }
19618
19619    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19620        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19621                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19622        for (int nextUserId : userIds) {
19623            if (DEBUG_REMOVE) {
19624                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19625            }
19626            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19627                    false /*installed*/,
19628                    true /*stopped*/,
19629                    true /*notLaunched*/,
19630                    false /*hidden*/,
19631                    false /*suspended*/,
19632                    false /*instantApp*/,
19633                    null /*lastDisableAppCaller*/,
19634                    null /*enabledComponents*/,
19635                    null /*disabledComponents*/,
19636                    ps.readUserState(nextUserId).domainVerificationStatus,
19637                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19638        }
19639        mSettings.writeKernelMappingLPr(ps);
19640    }
19641
19642    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19643            PackageRemovedInfo outInfo) {
19644        final PackageParser.Package pkg;
19645        synchronized (mPackages) {
19646            pkg = mPackages.get(ps.name);
19647        }
19648
19649        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19650                : new int[] {userId};
19651        for (int nextUserId : userIds) {
19652            if (DEBUG_REMOVE) {
19653                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19654                        + nextUserId);
19655            }
19656
19657            destroyAppDataLIF(pkg, userId,
19658                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19659            destroyAppProfilesLIF(pkg, userId);
19660            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19661            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19662            schedulePackageCleaning(ps.name, nextUserId, false);
19663            synchronized (mPackages) {
19664                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19665                    scheduleWritePackageRestrictionsLocked(nextUserId);
19666                }
19667                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19668            }
19669        }
19670
19671        if (outInfo != null) {
19672            outInfo.removedPackage = ps.name;
19673            outInfo.installerPackageName = ps.installerPackageName;
19674            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19675            outInfo.removedAppId = ps.appId;
19676            outInfo.removedUsers = userIds;
19677            outInfo.broadcastUsers = userIds;
19678        }
19679
19680        return true;
19681    }
19682
19683    private final class ClearStorageConnection implements ServiceConnection {
19684        IMediaContainerService mContainerService;
19685
19686        @Override
19687        public void onServiceConnected(ComponentName name, IBinder service) {
19688            synchronized (this) {
19689                mContainerService = IMediaContainerService.Stub
19690                        .asInterface(Binder.allowBlocking(service));
19691                notifyAll();
19692            }
19693        }
19694
19695        @Override
19696        public void onServiceDisconnected(ComponentName name) {
19697        }
19698    }
19699
19700    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19701        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19702
19703        final boolean mounted;
19704        if (Environment.isExternalStorageEmulated()) {
19705            mounted = true;
19706        } else {
19707            final String status = Environment.getExternalStorageState();
19708
19709            mounted = status.equals(Environment.MEDIA_MOUNTED)
19710                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19711        }
19712
19713        if (!mounted) {
19714            return;
19715        }
19716
19717        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19718        int[] users;
19719        if (userId == UserHandle.USER_ALL) {
19720            users = sUserManager.getUserIds();
19721        } else {
19722            users = new int[] { userId };
19723        }
19724        final ClearStorageConnection conn = new ClearStorageConnection();
19725        if (mContext.bindServiceAsUser(
19726                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19727            try {
19728                for (int curUser : users) {
19729                    long timeout = SystemClock.uptimeMillis() + 5000;
19730                    synchronized (conn) {
19731                        long now;
19732                        while (conn.mContainerService == null &&
19733                                (now = SystemClock.uptimeMillis()) < timeout) {
19734                            try {
19735                                conn.wait(timeout - now);
19736                            } catch (InterruptedException e) {
19737                            }
19738                        }
19739                    }
19740                    if (conn.mContainerService == null) {
19741                        return;
19742                    }
19743
19744                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19745                    clearDirectory(conn.mContainerService,
19746                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19747                    if (allData) {
19748                        clearDirectory(conn.mContainerService,
19749                                userEnv.buildExternalStorageAppDataDirs(packageName));
19750                        clearDirectory(conn.mContainerService,
19751                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19752                    }
19753                }
19754            } finally {
19755                mContext.unbindService(conn);
19756            }
19757        }
19758    }
19759
19760    @Override
19761    public void clearApplicationProfileData(String packageName) {
19762        enforceSystemOrRoot("Only the system can clear all profile data");
19763
19764        final PackageParser.Package pkg;
19765        synchronized (mPackages) {
19766            pkg = mPackages.get(packageName);
19767        }
19768
19769        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19770            synchronized (mInstallLock) {
19771                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19772            }
19773        }
19774    }
19775
19776    @Override
19777    public void clearApplicationUserData(final String packageName,
19778            final IPackageDataObserver observer, final int userId) {
19779        mContext.enforceCallingOrSelfPermission(
19780                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19781
19782        final int callingUid = Binder.getCallingUid();
19783        enforceCrossUserPermission(callingUid, userId,
19784                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19785
19786        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19787        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19788            return;
19789        }
19790        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19791            throw new SecurityException("Cannot clear data for a protected package: "
19792                    + packageName);
19793        }
19794        // Queue up an async operation since the package deletion may take a little while.
19795        mHandler.post(new Runnable() {
19796            public void run() {
19797                mHandler.removeCallbacks(this);
19798                final boolean succeeded;
19799                try (PackageFreezer freezer = freezePackage(packageName,
19800                        "clearApplicationUserData")) {
19801                    synchronized (mInstallLock) {
19802                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19803                    }
19804                    clearExternalStorageDataSync(packageName, userId, true);
19805                    synchronized (mPackages) {
19806                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19807                                packageName, userId);
19808                    }
19809                }
19810                if (succeeded) {
19811                    // invoke DeviceStorageMonitor's update method to clear any notifications
19812                    DeviceStorageMonitorInternal dsm = LocalServices
19813                            .getService(DeviceStorageMonitorInternal.class);
19814                    if (dsm != null) {
19815                        dsm.checkMemory();
19816                    }
19817                }
19818                if(observer != null) {
19819                    try {
19820                        observer.onRemoveCompleted(packageName, succeeded);
19821                    } catch (RemoteException e) {
19822                        Log.i(TAG, "Observer no longer exists.");
19823                    }
19824                } //end if observer
19825            } //end run
19826        });
19827    }
19828
19829    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19830        if (packageName == null) {
19831            Slog.w(TAG, "Attempt to delete null packageName.");
19832            return false;
19833        }
19834
19835        // Try finding details about the requested package
19836        PackageParser.Package pkg;
19837        synchronized (mPackages) {
19838            pkg = mPackages.get(packageName);
19839            if (pkg == null) {
19840                final PackageSetting ps = mSettings.mPackages.get(packageName);
19841                if (ps != null) {
19842                    pkg = ps.pkg;
19843                }
19844            }
19845
19846            if (pkg == null) {
19847                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19848                return false;
19849            }
19850
19851            PackageSetting ps = (PackageSetting) pkg.mExtras;
19852            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19853        }
19854
19855        clearAppDataLIF(pkg, userId,
19856                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19857
19858        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19859        removeKeystoreDataIfNeeded(userId, appId);
19860
19861        UserManagerInternal umInternal = getUserManagerInternal();
19862        final int flags;
19863        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19864            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19865        } else if (umInternal.isUserRunning(userId)) {
19866            flags = StorageManager.FLAG_STORAGE_DE;
19867        } else {
19868            flags = 0;
19869        }
19870        prepareAppDataContentsLIF(pkg, userId, flags);
19871
19872        return true;
19873    }
19874
19875    /**
19876     * Reverts user permission state changes (permissions and flags) in
19877     * all packages for a given user.
19878     *
19879     * @param userId The device user for which to do a reset.
19880     */
19881    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19882        final int packageCount = mPackages.size();
19883        for (int i = 0; i < packageCount; i++) {
19884            PackageParser.Package pkg = mPackages.valueAt(i);
19885            PackageSetting ps = (PackageSetting) pkg.mExtras;
19886            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19887        }
19888    }
19889
19890    private void resetNetworkPolicies(int userId) {
19891        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19892    }
19893
19894    /**
19895     * Reverts user permission state changes (permissions and flags).
19896     *
19897     * @param ps The package for which to reset.
19898     * @param userId The device user for which to do a reset.
19899     */
19900    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19901            final PackageSetting ps, final int userId) {
19902        if (ps.pkg == null) {
19903            return;
19904        }
19905
19906        // These are flags that can change base on user actions.
19907        final int userSettableMask = FLAG_PERMISSION_USER_SET
19908                | FLAG_PERMISSION_USER_FIXED
19909                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19910                | FLAG_PERMISSION_REVIEW_REQUIRED;
19911
19912        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19913                | FLAG_PERMISSION_POLICY_FIXED;
19914
19915        boolean writeInstallPermissions = false;
19916        boolean writeRuntimePermissions = false;
19917
19918        final int permissionCount = ps.pkg.requestedPermissions.size();
19919        for (int i = 0; i < permissionCount; i++) {
19920            String permission = ps.pkg.requestedPermissions.get(i);
19921
19922            BasePermission bp = mSettings.mPermissions.get(permission);
19923            if (bp == null) {
19924                continue;
19925            }
19926
19927            // If shared user we just reset the state to which only this app contributed.
19928            if (ps.sharedUser != null) {
19929                boolean used = false;
19930                final int packageCount = ps.sharedUser.packages.size();
19931                for (int j = 0; j < packageCount; j++) {
19932                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19933                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19934                            && pkg.pkg.requestedPermissions.contains(permission)) {
19935                        used = true;
19936                        break;
19937                    }
19938                }
19939                if (used) {
19940                    continue;
19941                }
19942            }
19943
19944            PermissionsState permissionsState = ps.getPermissionsState();
19945
19946            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19947
19948            // Always clear the user settable flags.
19949            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19950                    bp.name) != null;
19951            // If permission review is enabled and this is a legacy app, mark the
19952            // permission as requiring a review as this is the initial state.
19953            int flags = 0;
19954            if (mPermissionReviewRequired
19955                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19956                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19957            }
19958            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19959                if (hasInstallState) {
19960                    writeInstallPermissions = true;
19961                } else {
19962                    writeRuntimePermissions = true;
19963                }
19964            }
19965
19966            // Below is only runtime permission handling.
19967            if (!bp.isRuntime()) {
19968                continue;
19969            }
19970
19971            // Never clobber system or policy.
19972            if ((oldFlags & policyOrSystemFlags) != 0) {
19973                continue;
19974            }
19975
19976            // If this permission was granted by default, make sure it is.
19977            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19978                if (permissionsState.grantRuntimePermission(bp, userId)
19979                        != PERMISSION_OPERATION_FAILURE) {
19980                    writeRuntimePermissions = true;
19981                }
19982            // If permission review is enabled the permissions for a legacy apps
19983            // are represented as constantly granted runtime ones, so don't revoke.
19984            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19985                // Otherwise, reset the permission.
19986                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19987                switch (revokeResult) {
19988                    case PERMISSION_OPERATION_SUCCESS:
19989                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19990                        writeRuntimePermissions = true;
19991                        final int appId = ps.appId;
19992                        mHandler.post(new Runnable() {
19993                            @Override
19994                            public void run() {
19995                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19996                            }
19997                        });
19998                    } break;
19999                }
20000            }
20001        }
20002
20003        // Synchronously write as we are taking permissions away.
20004        if (writeRuntimePermissions) {
20005            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20006        }
20007
20008        // Synchronously write as we are taking permissions away.
20009        if (writeInstallPermissions) {
20010            mSettings.writeLPr();
20011        }
20012    }
20013
20014    /**
20015     * Remove entries from the keystore daemon. Will only remove it if the
20016     * {@code appId} is valid.
20017     */
20018    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20019        if (appId < 0) {
20020            return;
20021        }
20022
20023        final KeyStore keyStore = KeyStore.getInstance();
20024        if (keyStore != null) {
20025            if (userId == UserHandle.USER_ALL) {
20026                for (final int individual : sUserManager.getUserIds()) {
20027                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20028                }
20029            } else {
20030                keyStore.clearUid(UserHandle.getUid(userId, appId));
20031            }
20032        } else {
20033            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20034        }
20035    }
20036
20037    @Override
20038    public void deleteApplicationCacheFiles(final String packageName,
20039            final IPackageDataObserver observer) {
20040        final int userId = UserHandle.getCallingUserId();
20041        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20042    }
20043
20044    @Override
20045    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20046            final IPackageDataObserver observer) {
20047        final int callingUid = Binder.getCallingUid();
20048        mContext.enforceCallingOrSelfPermission(
20049                android.Manifest.permission.DELETE_CACHE_FILES, null);
20050        enforceCrossUserPermission(callingUid, userId,
20051                /* requireFullPermission= */ true, /* checkShell= */ false,
20052                "delete application cache files");
20053        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20054                android.Manifest.permission.ACCESS_INSTANT_APPS);
20055
20056        final PackageParser.Package pkg;
20057        synchronized (mPackages) {
20058            pkg = mPackages.get(packageName);
20059        }
20060
20061        // Queue up an async operation since the package deletion may take a little while.
20062        mHandler.post(new Runnable() {
20063            public void run() {
20064                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20065                boolean doClearData = true;
20066                if (ps != null) {
20067                    final boolean targetIsInstantApp =
20068                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20069                    doClearData = !targetIsInstantApp
20070                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20071                }
20072                if (doClearData) {
20073                    synchronized (mInstallLock) {
20074                        final int flags = StorageManager.FLAG_STORAGE_DE
20075                                | StorageManager.FLAG_STORAGE_CE;
20076                        // We're only clearing cache files, so we don't care if the
20077                        // app is unfrozen and still able to run
20078                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20079                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20080                    }
20081                    clearExternalStorageDataSync(packageName, userId, false);
20082                }
20083                if (observer != null) {
20084                    try {
20085                        observer.onRemoveCompleted(packageName, true);
20086                    } catch (RemoteException e) {
20087                        Log.i(TAG, "Observer no longer exists.");
20088                    }
20089                }
20090            }
20091        });
20092    }
20093
20094    @Override
20095    public void getPackageSizeInfo(final String packageName, int userHandle,
20096            final IPackageStatsObserver observer) {
20097        throw new UnsupportedOperationException(
20098                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20099    }
20100
20101    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20102        final PackageSetting ps;
20103        synchronized (mPackages) {
20104            ps = mSettings.mPackages.get(packageName);
20105            if (ps == null) {
20106                Slog.w(TAG, "Failed to find settings for " + packageName);
20107                return false;
20108            }
20109        }
20110
20111        final String[] packageNames = { packageName };
20112        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20113        final String[] codePaths = { ps.codePathString };
20114
20115        try {
20116            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20117                    ps.appId, ceDataInodes, codePaths, stats);
20118
20119            // For now, ignore code size of packages on system partition
20120            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20121                stats.codeSize = 0;
20122            }
20123
20124            // External clients expect these to be tracked separately
20125            stats.dataSize -= stats.cacheSize;
20126
20127        } catch (InstallerException e) {
20128            Slog.w(TAG, String.valueOf(e));
20129            return false;
20130        }
20131
20132        return true;
20133    }
20134
20135    private int getUidTargetSdkVersionLockedLPr(int uid) {
20136        Object obj = mSettings.getUserIdLPr(uid);
20137        if (obj instanceof SharedUserSetting) {
20138            final SharedUserSetting sus = (SharedUserSetting) obj;
20139            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20140            final Iterator<PackageSetting> it = sus.packages.iterator();
20141            while (it.hasNext()) {
20142                final PackageSetting ps = it.next();
20143                if (ps.pkg != null) {
20144                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20145                    if (v < vers) vers = v;
20146                }
20147            }
20148            return vers;
20149        } else if (obj instanceof PackageSetting) {
20150            final PackageSetting ps = (PackageSetting) obj;
20151            if (ps.pkg != null) {
20152                return ps.pkg.applicationInfo.targetSdkVersion;
20153            }
20154        }
20155        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20156    }
20157
20158    @Override
20159    public void addPreferredActivity(IntentFilter filter, int match,
20160            ComponentName[] set, ComponentName activity, int userId) {
20161        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20162                "Adding preferred");
20163    }
20164
20165    private void addPreferredActivityInternal(IntentFilter filter, int match,
20166            ComponentName[] set, ComponentName activity, boolean always, int userId,
20167            String opname) {
20168        // writer
20169        int callingUid = Binder.getCallingUid();
20170        enforceCrossUserPermission(callingUid, userId,
20171                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20172        if (filter.countActions() == 0) {
20173            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20174            return;
20175        }
20176        synchronized (mPackages) {
20177            if (mContext.checkCallingOrSelfPermission(
20178                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20179                    != PackageManager.PERMISSION_GRANTED) {
20180                if (getUidTargetSdkVersionLockedLPr(callingUid)
20181                        < Build.VERSION_CODES.FROYO) {
20182                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20183                            + callingUid);
20184                    return;
20185                }
20186                mContext.enforceCallingOrSelfPermission(
20187                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20188            }
20189
20190            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20191            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20192                    + userId + ":");
20193            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20194            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20195            scheduleWritePackageRestrictionsLocked(userId);
20196            postPreferredActivityChangedBroadcast(userId);
20197        }
20198    }
20199
20200    private void postPreferredActivityChangedBroadcast(int userId) {
20201        mHandler.post(() -> {
20202            final IActivityManager am = ActivityManager.getService();
20203            if (am == null) {
20204                return;
20205            }
20206
20207            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20208            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20209            try {
20210                am.broadcastIntent(null, intent, null, null,
20211                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20212                        null, false, false, userId);
20213            } catch (RemoteException e) {
20214            }
20215        });
20216    }
20217
20218    @Override
20219    public void replacePreferredActivity(IntentFilter filter, int match,
20220            ComponentName[] set, ComponentName activity, int userId) {
20221        if (filter.countActions() != 1) {
20222            throw new IllegalArgumentException(
20223                    "replacePreferredActivity expects filter to have only 1 action.");
20224        }
20225        if (filter.countDataAuthorities() != 0
20226                || filter.countDataPaths() != 0
20227                || filter.countDataSchemes() > 1
20228                || filter.countDataTypes() != 0) {
20229            throw new IllegalArgumentException(
20230                    "replacePreferredActivity expects filter to have no data authorities, " +
20231                    "paths, or types; and at most one scheme.");
20232        }
20233
20234        final int callingUid = Binder.getCallingUid();
20235        enforceCrossUserPermission(callingUid, userId,
20236                true /* requireFullPermission */, false /* checkShell */,
20237                "replace preferred activity");
20238        synchronized (mPackages) {
20239            if (mContext.checkCallingOrSelfPermission(
20240                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20241                    != PackageManager.PERMISSION_GRANTED) {
20242                if (getUidTargetSdkVersionLockedLPr(callingUid)
20243                        < Build.VERSION_CODES.FROYO) {
20244                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20245                            + Binder.getCallingUid());
20246                    return;
20247                }
20248                mContext.enforceCallingOrSelfPermission(
20249                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20250            }
20251
20252            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20253            if (pir != null) {
20254                // Get all of the existing entries that exactly match this filter.
20255                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20256                if (existing != null && existing.size() == 1) {
20257                    PreferredActivity cur = existing.get(0);
20258                    if (DEBUG_PREFERRED) {
20259                        Slog.i(TAG, "Checking replace of preferred:");
20260                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20261                        if (!cur.mPref.mAlways) {
20262                            Slog.i(TAG, "  -- CUR; not mAlways!");
20263                        } else {
20264                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20265                            Slog.i(TAG, "  -- CUR: mSet="
20266                                    + Arrays.toString(cur.mPref.mSetComponents));
20267                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20268                            Slog.i(TAG, "  -- NEW: mMatch="
20269                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20270                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20271                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20272                        }
20273                    }
20274                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20275                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20276                            && cur.mPref.sameSet(set)) {
20277                        // Setting the preferred activity to what it happens to be already
20278                        if (DEBUG_PREFERRED) {
20279                            Slog.i(TAG, "Replacing with same preferred activity "
20280                                    + cur.mPref.mShortComponent + " for user "
20281                                    + userId + ":");
20282                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20283                        }
20284                        return;
20285                    }
20286                }
20287
20288                if (existing != null) {
20289                    if (DEBUG_PREFERRED) {
20290                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20291                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20292                    }
20293                    for (int i = 0; i < existing.size(); i++) {
20294                        PreferredActivity pa = existing.get(i);
20295                        if (DEBUG_PREFERRED) {
20296                            Slog.i(TAG, "Removing existing preferred activity "
20297                                    + pa.mPref.mComponent + ":");
20298                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20299                        }
20300                        pir.removeFilter(pa);
20301                    }
20302                }
20303            }
20304            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20305                    "Replacing preferred");
20306        }
20307    }
20308
20309    @Override
20310    public void clearPackagePreferredActivities(String packageName) {
20311        final int callingUid = Binder.getCallingUid();
20312        if (getInstantAppPackageName(callingUid) != null) {
20313            return;
20314        }
20315        // writer
20316        synchronized (mPackages) {
20317            PackageParser.Package pkg = mPackages.get(packageName);
20318            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20319                if (mContext.checkCallingOrSelfPermission(
20320                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20321                        != PackageManager.PERMISSION_GRANTED) {
20322                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20323                            < Build.VERSION_CODES.FROYO) {
20324                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20325                                + callingUid);
20326                        return;
20327                    }
20328                    mContext.enforceCallingOrSelfPermission(
20329                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20330                }
20331            }
20332            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20333            if (ps != null
20334                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20335                return;
20336            }
20337            int user = UserHandle.getCallingUserId();
20338            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20339                scheduleWritePackageRestrictionsLocked(user);
20340            }
20341        }
20342    }
20343
20344    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20345    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20346        ArrayList<PreferredActivity> removed = null;
20347        boolean changed = false;
20348        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20349            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20350            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20351            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20352                continue;
20353            }
20354            Iterator<PreferredActivity> it = pir.filterIterator();
20355            while (it.hasNext()) {
20356                PreferredActivity pa = it.next();
20357                // Mark entry for removal only if it matches the package name
20358                // and the entry is of type "always".
20359                if (packageName == null ||
20360                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20361                                && pa.mPref.mAlways)) {
20362                    if (removed == null) {
20363                        removed = new ArrayList<PreferredActivity>();
20364                    }
20365                    removed.add(pa);
20366                }
20367            }
20368            if (removed != null) {
20369                for (int j=0; j<removed.size(); j++) {
20370                    PreferredActivity pa = removed.get(j);
20371                    pir.removeFilter(pa);
20372                }
20373                changed = true;
20374            }
20375        }
20376        if (changed) {
20377            postPreferredActivityChangedBroadcast(userId);
20378        }
20379        return changed;
20380    }
20381
20382    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20383    private void clearIntentFilterVerificationsLPw(int userId) {
20384        final int packageCount = mPackages.size();
20385        for (int i = 0; i < packageCount; i++) {
20386            PackageParser.Package pkg = mPackages.valueAt(i);
20387            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20388        }
20389    }
20390
20391    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20392    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20393        if (userId == UserHandle.USER_ALL) {
20394            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20395                    sUserManager.getUserIds())) {
20396                for (int oneUserId : sUserManager.getUserIds()) {
20397                    scheduleWritePackageRestrictionsLocked(oneUserId);
20398                }
20399            }
20400        } else {
20401            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20402                scheduleWritePackageRestrictionsLocked(userId);
20403            }
20404        }
20405    }
20406
20407    /** Clears state for all users, and touches intent filter verification policy */
20408    void clearDefaultBrowserIfNeeded(String packageName) {
20409        for (int oneUserId : sUserManager.getUserIds()) {
20410            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20411        }
20412    }
20413
20414    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20415        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20416        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20417            if (packageName.equals(defaultBrowserPackageName)) {
20418                setDefaultBrowserPackageName(null, userId);
20419            }
20420        }
20421    }
20422
20423    @Override
20424    public void resetApplicationPreferences(int userId) {
20425        mContext.enforceCallingOrSelfPermission(
20426                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20427        final long identity = Binder.clearCallingIdentity();
20428        // writer
20429        try {
20430            synchronized (mPackages) {
20431                clearPackagePreferredActivitiesLPw(null, userId);
20432                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20433                // TODO: We have to reset the default SMS and Phone. This requires
20434                // significant refactoring to keep all default apps in the package
20435                // manager (cleaner but more work) or have the services provide
20436                // callbacks to the package manager to request a default app reset.
20437                applyFactoryDefaultBrowserLPw(userId);
20438                clearIntentFilterVerificationsLPw(userId);
20439                primeDomainVerificationsLPw(userId);
20440                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20441                scheduleWritePackageRestrictionsLocked(userId);
20442            }
20443            resetNetworkPolicies(userId);
20444        } finally {
20445            Binder.restoreCallingIdentity(identity);
20446        }
20447    }
20448
20449    @Override
20450    public int getPreferredActivities(List<IntentFilter> outFilters,
20451            List<ComponentName> outActivities, String packageName) {
20452        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20453            return 0;
20454        }
20455        int num = 0;
20456        final int userId = UserHandle.getCallingUserId();
20457        // reader
20458        synchronized (mPackages) {
20459            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20460            if (pir != null) {
20461                final Iterator<PreferredActivity> it = pir.filterIterator();
20462                while (it.hasNext()) {
20463                    final PreferredActivity pa = it.next();
20464                    if (packageName == null
20465                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20466                                    && pa.mPref.mAlways)) {
20467                        if (outFilters != null) {
20468                            outFilters.add(new IntentFilter(pa));
20469                        }
20470                        if (outActivities != null) {
20471                            outActivities.add(pa.mPref.mComponent);
20472                        }
20473                    }
20474                }
20475            }
20476        }
20477
20478        return num;
20479    }
20480
20481    @Override
20482    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20483            int userId) {
20484        int callingUid = Binder.getCallingUid();
20485        if (callingUid != Process.SYSTEM_UID) {
20486            throw new SecurityException(
20487                    "addPersistentPreferredActivity can only be run by the system");
20488        }
20489        if (filter.countActions() == 0) {
20490            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20491            return;
20492        }
20493        synchronized (mPackages) {
20494            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20495                    ":");
20496            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20497            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20498                    new PersistentPreferredActivity(filter, activity));
20499            scheduleWritePackageRestrictionsLocked(userId);
20500            postPreferredActivityChangedBroadcast(userId);
20501        }
20502    }
20503
20504    @Override
20505    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20506        int callingUid = Binder.getCallingUid();
20507        if (callingUid != Process.SYSTEM_UID) {
20508            throw new SecurityException(
20509                    "clearPackagePersistentPreferredActivities can only be run by the system");
20510        }
20511        ArrayList<PersistentPreferredActivity> removed = null;
20512        boolean changed = false;
20513        synchronized (mPackages) {
20514            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20515                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20516                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20517                        .valueAt(i);
20518                if (userId != thisUserId) {
20519                    continue;
20520                }
20521                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20522                while (it.hasNext()) {
20523                    PersistentPreferredActivity ppa = it.next();
20524                    // Mark entry for removal only if it matches the package name.
20525                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20526                        if (removed == null) {
20527                            removed = new ArrayList<PersistentPreferredActivity>();
20528                        }
20529                        removed.add(ppa);
20530                    }
20531                }
20532                if (removed != null) {
20533                    for (int j=0; j<removed.size(); j++) {
20534                        PersistentPreferredActivity ppa = removed.get(j);
20535                        ppir.removeFilter(ppa);
20536                    }
20537                    changed = true;
20538                }
20539            }
20540
20541            if (changed) {
20542                scheduleWritePackageRestrictionsLocked(userId);
20543                postPreferredActivityChangedBroadcast(userId);
20544            }
20545        }
20546    }
20547
20548    /**
20549     * Common machinery for picking apart a restored XML blob and passing
20550     * it to a caller-supplied functor to be applied to the running system.
20551     */
20552    private void restoreFromXml(XmlPullParser parser, int userId,
20553            String expectedStartTag, BlobXmlRestorer functor)
20554            throws IOException, XmlPullParserException {
20555        int type;
20556        while ((type = parser.next()) != XmlPullParser.START_TAG
20557                && type != XmlPullParser.END_DOCUMENT) {
20558        }
20559        if (type != XmlPullParser.START_TAG) {
20560            // oops didn't find a start tag?!
20561            if (DEBUG_BACKUP) {
20562                Slog.e(TAG, "Didn't find start tag during restore");
20563            }
20564            return;
20565        }
20566Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20567        // this is supposed to be TAG_PREFERRED_BACKUP
20568        if (!expectedStartTag.equals(parser.getName())) {
20569            if (DEBUG_BACKUP) {
20570                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20571            }
20572            return;
20573        }
20574
20575        // skip interfering stuff, then we're aligned with the backing implementation
20576        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20577Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20578        functor.apply(parser, userId);
20579    }
20580
20581    private interface BlobXmlRestorer {
20582        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20583    }
20584
20585    /**
20586     * Non-Binder method, support for the backup/restore mechanism: write the
20587     * full set of preferred activities in its canonical XML format.  Returns the
20588     * XML output as a byte array, or null if there is none.
20589     */
20590    @Override
20591    public byte[] getPreferredActivityBackup(int userId) {
20592        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20593            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20594        }
20595
20596        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20597        try {
20598            final XmlSerializer serializer = new FastXmlSerializer();
20599            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20600            serializer.startDocument(null, true);
20601            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20602
20603            synchronized (mPackages) {
20604                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20605            }
20606
20607            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20608            serializer.endDocument();
20609            serializer.flush();
20610        } catch (Exception e) {
20611            if (DEBUG_BACKUP) {
20612                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20613            }
20614            return null;
20615        }
20616
20617        return dataStream.toByteArray();
20618    }
20619
20620    @Override
20621    public void restorePreferredActivities(byte[] backup, int userId) {
20622        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20623            throw new SecurityException("Only the system may call restorePreferredActivities()");
20624        }
20625
20626        try {
20627            final XmlPullParser parser = Xml.newPullParser();
20628            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20629            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20630                    new BlobXmlRestorer() {
20631                        @Override
20632                        public void apply(XmlPullParser parser, int userId)
20633                                throws XmlPullParserException, IOException {
20634                            synchronized (mPackages) {
20635                                mSettings.readPreferredActivitiesLPw(parser, userId);
20636                            }
20637                        }
20638                    } );
20639        } catch (Exception e) {
20640            if (DEBUG_BACKUP) {
20641                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20642            }
20643        }
20644    }
20645
20646    /**
20647     * Non-Binder method, support for the backup/restore mechanism: write the
20648     * default browser (etc) settings in its canonical XML format.  Returns the default
20649     * browser XML representation as a byte array, or null if there is none.
20650     */
20651    @Override
20652    public byte[] getDefaultAppsBackup(int userId) {
20653        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20654            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20655        }
20656
20657        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20658        try {
20659            final XmlSerializer serializer = new FastXmlSerializer();
20660            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20661            serializer.startDocument(null, true);
20662            serializer.startTag(null, TAG_DEFAULT_APPS);
20663
20664            synchronized (mPackages) {
20665                mSettings.writeDefaultAppsLPr(serializer, userId);
20666            }
20667
20668            serializer.endTag(null, TAG_DEFAULT_APPS);
20669            serializer.endDocument();
20670            serializer.flush();
20671        } catch (Exception e) {
20672            if (DEBUG_BACKUP) {
20673                Slog.e(TAG, "Unable to write default apps for backup", e);
20674            }
20675            return null;
20676        }
20677
20678        return dataStream.toByteArray();
20679    }
20680
20681    @Override
20682    public void restoreDefaultApps(byte[] backup, int userId) {
20683        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20684            throw new SecurityException("Only the system may call restoreDefaultApps()");
20685        }
20686
20687        try {
20688            final XmlPullParser parser = Xml.newPullParser();
20689            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20690            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20691                    new BlobXmlRestorer() {
20692                        @Override
20693                        public void apply(XmlPullParser parser, int userId)
20694                                throws XmlPullParserException, IOException {
20695                            synchronized (mPackages) {
20696                                mSettings.readDefaultAppsLPw(parser, userId);
20697                            }
20698                        }
20699                    } );
20700        } catch (Exception e) {
20701            if (DEBUG_BACKUP) {
20702                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20703            }
20704        }
20705    }
20706
20707    @Override
20708    public byte[] getIntentFilterVerificationBackup(int userId) {
20709        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20710            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20711        }
20712
20713        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20714        try {
20715            final XmlSerializer serializer = new FastXmlSerializer();
20716            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20717            serializer.startDocument(null, true);
20718            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20719
20720            synchronized (mPackages) {
20721                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20722            }
20723
20724            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20725            serializer.endDocument();
20726            serializer.flush();
20727        } catch (Exception e) {
20728            if (DEBUG_BACKUP) {
20729                Slog.e(TAG, "Unable to write default apps for backup", e);
20730            }
20731            return null;
20732        }
20733
20734        return dataStream.toByteArray();
20735    }
20736
20737    @Override
20738    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20739        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20740            throw new SecurityException("Only the system may call restorePreferredActivities()");
20741        }
20742
20743        try {
20744            final XmlPullParser parser = Xml.newPullParser();
20745            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20746            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20747                    new BlobXmlRestorer() {
20748                        @Override
20749                        public void apply(XmlPullParser parser, int userId)
20750                                throws XmlPullParserException, IOException {
20751                            synchronized (mPackages) {
20752                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20753                                mSettings.writeLPr();
20754                            }
20755                        }
20756                    } );
20757        } catch (Exception e) {
20758            if (DEBUG_BACKUP) {
20759                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20760            }
20761        }
20762    }
20763
20764    @Override
20765    public byte[] getPermissionGrantBackup(int userId) {
20766        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20767            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20768        }
20769
20770        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20771        try {
20772            final XmlSerializer serializer = new FastXmlSerializer();
20773            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20774            serializer.startDocument(null, true);
20775            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20776
20777            synchronized (mPackages) {
20778                serializeRuntimePermissionGrantsLPr(serializer, userId);
20779            }
20780
20781            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20782            serializer.endDocument();
20783            serializer.flush();
20784        } catch (Exception e) {
20785            if (DEBUG_BACKUP) {
20786                Slog.e(TAG, "Unable to write default apps for backup", e);
20787            }
20788            return null;
20789        }
20790
20791        return dataStream.toByteArray();
20792    }
20793
20794    @Override
20795    public void restorePermissionGrants(byte[] backup, int userId) {
20796        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20797            throw new SecurityException("Only the system may call restorePermissionGrants()");
20798        }
20799
20800        try {
20801            final XmlPullParser parser = Xml.newPullParser();
20802            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20803            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20804                    new BlobXmlRestorer() {
20805                        @Override
20806                        public void apply(XmlPullParser parser, int userId)
20807                                throws XmlPullParserException, IOException {
20808                            synchronized (mPackages) {
20809                                processRestoredPermissionGrantsLPr(parser, userId);
20810                            }
20811                        }
20812                    } );
20813        } catch (Exception e) {
20814            if (DEBUG_BACKUP) {
20815                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20816            }
20817        }
20818    }
20819
20820    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20821            throws IOException {
20822        serializer.startTag(null, TAG_ALL_GRANTS);
20823
20824        final int N = mSettings.mPackages.size();
20825        for (int i = 0; i < N; i++) {
20826            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20827            boolean pkgGrantsKnown = false;
20828
20829            PermissionsState packagePerms = ps.getPermissionsState();
20830
20831            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20832                final int grantFlags = state.getFlags();
20833                // only look at grants that are not system/policy fixed
20834                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20835                    final boolean isGranted = state.isGranted();
20836                    // And only back up the user-twiddled state bits
20837                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20838                        final String packageName = mSettings.mPackages.keyAt(i);
20839                        if (!pkgGrantsKnown) {
20840                            serializer.startTag(null, TAG_GRANT);
20841                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20842                            pkgGrantsKnown = true;
20843                        }
20844
20845                        final boolean userSet =
20846                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20847                        final boolean userFixed =
20848                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20849                        final boolean revoke =
20850                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20851
20852                        serializer.startTag(null, TAG_PERMISSION);
20853                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20854                        if (isGranted) {
20855                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20856                        }
20857                        if (userSet) {
20858                            serializer.attribute(null, ATTR_USER_SET, "true");
20859                        }
20860                        if (userFixed) {
20861                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20862                        }
20863                        if (revoke) {
20864                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20865                        }
20866                        serializer.endTag(null, TAG_PERMISSION);
20867                    }
20868                }
20869            }
20870
20871            if (pkgGrantsKnown) {
20872                serializer.endTag(null, TAG_GRANT);
20873            }
20874        }
20875
20876        serializer.endTag(null, TAG_ALL_GRANTS);
20877    }
20878
20879    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20880            throws XmlPullParserException, IOException {
20881        String pkgName = null;
20882        int outerDepth = parser.getDepth();
20883        int type;
20884        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20885                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20886            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20887                continue;
20888            }
20889
20890            final String tagName = parser.getName();
20891            if (tagName.equals(TAG_GRANT)) {
20892                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20893                if (DEBUG_BACKUP) {
20894                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20895                }
20896            } else if (tagName.equals(TAG_PERMISSION)) {
20897
20898                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20899                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20900
20901                int newFlagSet = 0;
20902                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20903                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20904                }
20905                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20906                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20907                }
20908                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20909                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20910                }
20911                if (DEBUG_BACKUP) {
20912                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20913                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20914                }
20915                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20916                if (ps != null) {
20917                    // Already installed so we apply the grant immediately
20918                    if (DEBUG_BACKUP) {
20919                        Slog.v(TAG, "        + already installed; applying");
20920                    }
20921                    PermissionsState perms = ps.getPermissionsState();
20922                    BasePermission bp = mSettings.mPermissions.get(permName);
20923                    if (bp != null) {
20924                        if (isGranted) {
20925                            perms.grantRuntimePermission(bp, userId);
20926                        }
20927                        if (newFlagSet != 0) {
20928                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20929                        }
20930                    }
20931                } else {
20932                    // Need to wait for post-restore install to apply the grant
20933                    if (DEBUG_BACKUP) {
20934                        Slog.v(TAG, "        - not yet installed; saving for later");
20935                    }
20936                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20937                            isGranted, newFlagSet, userId);
20938                }
20939            } else {
20940                PackageManagerService.reportSettingsProblem(Log.WARN,
20941                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20942                XmlUtils.skipCurrentTag(parser);
20943            }
20944        }
20945
20946        scheduleWriteSettingsLocked();
20947        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20948    }
20949
20950    @Override
20951    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20952            int sourceUserId, int targetUserId, int flags) {
20953        mContext.enforceCallingOrSelfPermission(
20954                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20955        int callingUid = Binder.getCallingUid();
20956        enforceOwnerRights(ownerPackage, callingUid);
20957        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20958        if (intentFilter.countActions() == 0) {
20959            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20960            return;
20961        }
20962        synchronized (mPackages) {
20963            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20964                    ownerPackage, targetUserId, flags);
20965            CrossProfileIntentResolver resolver =
20966                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20967            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20968            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20969            if (existing != null) {
20970                int size = existing.size();
20971                for (int i = 0; i < size; i++) {
20972                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20973                        return;
20974                    }
20975                }
20976            }
20977            resolver.addFilter(newFilter);
20978            scheduleWritePackageRestrictionsLocked(sourceUserId);
20979        }
20980    }
20981
20982    @Override
20983    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20984        mContext.enforceCallingOrSelfPermission(
20985                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20986        final int callingUid = Binder.getCallingUid();
20987        enforceOwnerRights(ownerPackage, callingUid);
20988        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20989        synchronized (mPackages) {
20990            CrossProfileIntentResolver resolver =
20991                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20992            ArraySet<CrossProfileIntentFilter> set =
20993                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20994            for (CrossProfileIntentFilter filter : set) {
20995                if (filter.getOwnerPackage().equals(ownerPackage)) {
20996                    resolver.removeFilter(filter);
20997                }
20998            }
20999            scheduleWritePackageRestrictionsLocked(sourceUserId);
21000        }
21001    }
21002
21003    // Enforcing that callingUid is owning pkg on userId
21004    private void enforceOwnerRights(String pkg, int callingUid) {
21005        // The system owns everything.
21006        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21007            return;
21008        }
21009        final int callingUserId = UserHandle.getUserId(callingUid);
21010        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21011        if (pi == null) {
21012            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21013                    + callingUserId);
21014        }
21015        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21016            throw new SecurityException("Calling uid " + callingUid
21017                    + " does not own package " + pkg);
21018        }
21019    }
21020
21021    @Override
21022    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21023        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21024            return null;
21025        }
21026        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21027    }
21028
21029    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21030        UserManagerService ums = UserManagerService.getInstance();
21031        if (ums != null) {
21032            final UserInfo parent = ums.getProfileParent(userId);
21033            final int launcherUid = (parent != null) ? parent.id : userId;
21034            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21035            if (launcherComponent != null) {
21036                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21037                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21038                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21039                        .setPackage(launcherComponent.getPackageName());
21040                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21041            }
21042        }
21043    }
21044
21045    /**
21046     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21047     * then reports the most likely home activity or null if there are more than one.
21048     */
21049    private ComponentName getDefaultHomeActivity(int userId) {
21050        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21051        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21052        if (cn != null) {
21053            return cn;
21054        }
21055
21056        // Find the launcher with the highest priority and return that component if there are no
21057        // other home activity with the same priority.
21058        int lastPriority = Integer.MIN_VALUE;
21059        ComponentName lastComponent = null;
21060        final int size = allHomeCandidates.size();
21061        for (int i = 0; i < size; i++) {
21062            final ResolveInfo ri = allHomeCandidates.get(i);
21063            if (ri.priority > lastPriority) {
21064                lastComponent = ri.activityInfo.getComponentName();
21065                lastPriority = ri.priority;
21066            } else if (ri.priority == lastPriority) {
21067                // Two components found with same priority.
21068                lastComponent = null;
21069            }
21070        }
21071        return lastComponent;
21072    }
21073
21074    private Intent getHomeIntent() {
21075        Intent intent = new Intent(Intent.ACTION_MAIN);
21076        intent.addCategory(Intent.CATEGORY_HOME);
21077        intent.addCategory(Intent.CATEGORY_DEFAULT);
21078        return intent;
21079    }
21080
21081    private IntentFilter getHomeFilter() {
21082        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21083        filter.addCategory(Intent.CATEGORY_HOME);
21084        filter.addCategory(Intent.CATEGORY_DEFAULT);
21085        return filter;
21086    }
21087
21088    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21089            int userId) {
21090        Intent intent  = getHomeIntent();
21091        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21092                PackageManager.GET_META_DATA, userId);
21093        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21094                true, false, false, userId);
21095
21096        allHomeCandidates.clear();
21097        if (list != null) {
21098            for (ResolveInfo ri : list) {
21099                allHomeCandidates.add(ri);
21100            }
21101        }
21102        return (preferred == null || preferred.activityInfo == null)
21103                ? null
21104                : new ComponentName(preferred.activityInfo.packageName,
21105                        preferred.activityInfo.name);
21106    }
21107
21108    @Override
21109    public void setHomeActivity(ComponentName comp, int userId) {
21110        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21111            return;
21112        }
21113        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21114        getHomeActivitiesAsUser(homeActivities, userId);
21115
21116        boolean found = false;
21117
21118        final int size = homeActivities.size();
21119        final ComponentName[] set = new ComponentName[size];
21120        for (int i = 0; i < size; i++) {
21121            final ResolveInfo candidate = homeActivities.get(i);
21122            final ActivityInfo info = candidate.activityInfo;
21123            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21124            set[i] = activityName;
21125            if (!found && activityName.equals(comp)) {
21126                found = true;
21127            }
21128        }
21129        if (!found) {
21130            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21131                    + userId);
21132        }
21133        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21134                set, comp, userId);
21135    }
21136
21137    private @Nullable String getSetupWizardPackageName() {
21138        final Intent intent = new Intent(Intent.ACTION_MAIN);
21139        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21140
21141        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21142                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21143                        | MATCH_DISABLED_COMPONENTS,
21144                UserHandle.myUserId());
21145        if (matches.size() == 1) {
21146            return matches.get(0).getComponentInfo().packageName;
21147        } else {
21148            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21149                    + ": matches=" + matches);
21150            return null;
21151        }
21152    }
21153
21154    private @Nullable String getStorageManagerPackageName() {
21155        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21156
21157        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21158                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21159                        | MATCH_DISABLED_COMPONENTS,
21160                UserHandle.myUserId());
21161        if (matches.size() == 1) {
21162            return matches.get(0).getComponentInfo().packageName;
21163        } else {
21164            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21165                    + matches.size() + ": matches=" + matches);
21166            return null;
21167        }
21168    }
21169
21170    @Override
21171    public void setApplicationEnabledSetting(String appPackageName,
21172            int newState, int flags, int userId, String callingPackage) {
21173        if (!sUserManager.exists(userId)) return;
21174        if (callingPackage == null) {
21175            callingPackage = Integer.toString(Binder.getCallingUid());
21176        }
21177        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21178    }
21179
21180    @Override
21181    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21182        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21183        synchronized (mPackages) {
21184            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21185            if (pkgSetting != null) {
21186                pkgSetting.setUpdateAvailable(updateAvailable);
21187            }
21188        }
21189    }
21190
21191    @Override
21192    public void setComponentEnabledSetting(ComponentName componentName,
21193            int newState, int flags, int userId) {
21194        if (!sUserManager.exists(userId)) return;
21195        setEnabledSetting(componentName.getPackageName(),
21196                componentName.getClassName(), newState, flags, userId, null);
21197    }
21198
21199    private void setEnabledSetting(final String packageName, String className, int newState,
21200            final int flags, int userId, String callingPackage) {
21201        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21202              || newState == COMPONENT_ENABLED_STATE_ENABLED
21203              || newState == COMPONENT_ENABLED_STATE_DISABLED
21204              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21205              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21206            throw new IllegalArgumentException("Invalid new component state: "
21207                    + newState);
21208        }
21209        PackageSetting pkgSetting;
21210        final int callingUid = Binder.getCallingUid();
21211        final int permission;
21212        if (callingUid == Process.SYSTEM_UID) {
21213            permission = PackageManager.PERMISSION_GRANTED;
21214        } else {
21215            permission = mContext.checkCallingOrSelfPermission(
21216                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21217        }
21218        enforceCrossUserPermission(callingUid, userId,
21219                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21220        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21221        boolean sendNow = false;
21222        boolean isApp = (className == null);
21223        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21224        String componentName = isApp ? packageName : className;
21225        int packageUid = -1;
21226        ArrayList<String> components;
21227
21228        // reader
21229        synchronized (mPackages) {
21230            pkgSetting = mSettings.mPackages.get(packageName);
21231            if (pkgSetting == null) {
21232                if (!isCallerInstantApp) {
21233                    if (className == null) {
21234                        throw new IllegalArgumentException("Unknown package: " + packageName);
21235                    }
21236                    throw new IllegalArgumentException(
21237                            "Unknown component: " + packageName + "/" + className);
21238                } else {
21239                    // throw SecurityException to prevent leaking package information
21240                    throw new SecurityException(
21241                            "Attempt to change component state; "
21242                            + "pid=" + Binder.getCallingPid()
21243                            + ", uid=" + callingUid
21244                            + (className == null
21245                                    ? ", package=" + packageName
21246                                    : ", component=" + packageName + "/" + className));
21247                }
21248            }
21249        }
21250
21251        // Limit who can change which apps
21252        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21253            // Don't allow apps that don't have permission to modify other apps
21254            if (!allowedByPermission
21255                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21256                throw new SecurityException(
21257                        "Attempt to change component state; "
21258                        + "pid=" + Binder.getCallingPid()
21259                        + ", uid=" + callingUid
21260                        + (className == null
21261                                ? ", package=" + packageName
21262                                : ", component=" + packageName + "/" + className));
21263            }
21264            // Don't allow changing protected packages.
21265            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21266                throw new SecurityException("Cannot disable a protected package: " + packageName);
21267            }
21268        }
21269
21270        synchronized (mPackages) {
21271            if (callingUid == Process.SHELL_UID
21272                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21273                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21274                // unless it is a test package.
21275                int oldState = pkgSetting.getEnabled(userId);
21276                if (className == null
21277                    &&
21278                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21279                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21280                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21281                    &&
21282                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21283                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21284                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21285                    // ok
21286                } else {
21287                    throw new SecurityException(
21288                            "Shell cannot change component state for " + packageName + "/"
21289                            + className + " to " + newState);
21290                }
21291            }
21292            if (className == null) {
21293                // We're dealing with an application/package level state change
21294                if (pkgSetting.getEnabled(userId) == newState) {
21295                    // Nothing to do
21296                    return;
21297                }
21298                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21299                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21300                    // Don't care about who enables an app.
21301                    callingPackage = null;
21302                }
21303                pkgSetting.setEnabled(newState, userId, callingPackage);
21304                // pkgSetting.pkg.mSetEnabled = newState;
21305            } else {
21306                // We're dealing with a component level state change
21307                // First, verify that this is a valid class name.
21308                PackageParser.Package pkg = pkgSetting.pkg;
21309                if (pkg == null || !pkg.hasComponentClassName(className)) {
21310                    if (pkg != null &&
21311                            pkg.applicationInfo.targetSdkVersion >=
21312                                    Build.VERSION_CODES.JELLY_BEAN) {
21313                        throw new IllegalArgumentException("Component class " + className
21314                                + " does not exist in " + packageName);
21315                    } else {
21316                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21317                                + className + " does not exist in " + packageName);
21318                    }
21319                }
21320                switch (newState) {
21321                case COMPONENT_ENABLED_STATE_ENABLED:
21322                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21323                        return;
21324                    }
21325                    break;
21326                case COMPONENT_ENABLED_STATE_DISABLED:
21327                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21328                        return;
21329                    }
21330                    break;
21331                case COMPONENT_ENABLED_STATE_DEFAULT:
21332                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21333                        return;
21334                    }
21335                    break;
21336                default:
21337                    Slog.e(TAG, "Invalid new component state: " + newState);
21338                    return;
21339                }
21340            }
21341            scheduleWritePackageRestrictionsLocked(userId);
21342            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21343            final long callingId = Binder.clearCallingIdentity();
21344            try {
21345                updateInstantAppInstallerLocked(packageName);
21346            } finally {
21347                Binder.restoreCallingIdentity(callingId);
21348            }
21349            components = mPendingBroadcasts.get(userId, packageName);
21350            final boolean newPackage = components == null;
21351            if (newPackage) {
21352                components = new ArrayList<String>();
21353            }
21354            if (!components.contains(componentName)) {
21355                components.add(componentName);
21356            }
21357            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21358                sendNow = true;
21359                // Purge entry from pending broadcast list if another one exists already
21360                // since we are sending one right away.
21361                mPendingBroadcasts.remove(userId, packageName);
21362            } else {
21363                if (newPackage) {
21364                    mPendingBroadcasts.put(userId, packageName, components);
21365                }
21366                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21367                    // Schedule a message
21368                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21369                }
21370            }
21371        }
21372
21373        long callingId = Binder.clearCallingIdentity();
21374        try {
21375            if (sendNow) {
21376                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21377                sendPackageChangedBroadcast(packageName,
21378                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21379            }
21380        } finally {
21381            Binder.restoreCallingIdentity(callingId);
21382        }
21383    }
21384
21385    @Override
21386    public void flushPackageRestrictionsAsUser(int userId) {
21387        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21388            return;
21389        }
21390        if (!sUserManager.exists(userId)) {
21391            return;
21392        }
21393        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21394                false /* checkShell */, "flushPackageRestrictions");
21395        synchronized (mPackages) {
21396            mSettings.writePackageRestrictionsLPr(userId);
21397            mDirtyUsers.remove(userId);
21398            if (mDirtyUsers.isEmpty()) {
21399                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21400            }
21401        }
21402    }
21403
21404    private void sendPackageChangedBroadcast(String packageName,
21405            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21406        if (DEBUG_INSTALL)
21407            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21408                    + componentNames);
21409        Bundle extras = new Bundle(4);
21410        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21411        String nameList[] = new String[componentNames.size()];
21412        componentNames.toArray(nameList);
21413        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21414        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21415        extras.putInt(Intent.EXTRA_UID, packageUid);
21416        // If this is not reporting a change of the overall package, then only send it
21417        // to registered receivers.  We don't want to launch a swath of apps for every
21418        // little component state change.
21419        final int flags = !componentNames.contains(packageName)
21420                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21421        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21422                new int[] {UserHandle.getUserId(packageUid)});
21423    }
21424
21425    @Override
21426    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21427        if (!sUserManager.exists(userId)) return;
21428        final int callingUid = Binder.getCallingUid();
21429        if (getInstantAppPackageName(callingUid) != null) {
21430            return;
21431        }
21432        final int permission = mContext.checkCallingOrSelfPermission(
21433                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21434        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21435        enforceCrossUserPermission(callingUid, userId,
21436                true /* requireFullPermission */, true /* checkShell */, "stop package");
21437        // writer
21438        synchronized (mPackages) {
21439            final PackageSetting ps = mSettings.mPackages.get(packageName);
21440            if (!filterAppAccessLPr(ps, callingUid, userId)
21441                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21442                            allowedByPermission, callingUid, userId)) {
21443                scheduleWritePackageRestrictionsLocked(userId);
21444            }
21445        }
21446    }
21447
21448    @Override
21449    public String getInstallerPackageName(String packageName) {
21450        final int callingUid = Binder.getCallingUid();
21451        if (getInstantAppPackageName(callingUid) != null) {
21452            return null;
21453        }
21454        // reader
21455        synchronized (mPackages) {
21456            final PackageSetting ps = mSettings.mPackages.get(packageName);
21457            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21458                return null;
21459            }
21460            return mSettings.getInstallerPackageNameLPr(packageName);
21461        }
21462    }
21463
21464    public boolean isOrphaned(String packageName) {
21465        // reader
21466        synchronized (mPackages) {
21467            return mSettings.isOrphaned(packageName);
21468        }
21469    }
21470
21471    @Override
21472    public int getApplicationEnabledSetting(String packageName, int userId) {
21473        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21474        int callingUid = Binder.getCallingUid();
21475        enforceCrossUserPermission(callingUid, userId,
21476                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21477        // reader
21478        synchronized (mPackages) {
21479            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21480                return COMPONENT_ENABLED_STATE_DISABLED;
21481            }
21482            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21483        }
21484    }
21485
21486    @Override
21487    public int getComponentEnabledSetting(ComponentName component, int userId) {
21488        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21489        int callingUid = Binder.getCallingUid();
21490        enforceCrossUserPermission(callingUid, userId,
21491                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21492        synchronized (mPackages) {
21493            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21494                    component, TYPE_UNKNOWN, userId)) {
21495                return COMPONENT_ENABLED_STATE_DISABLED;
21496            }
21497            return mSettings.getComponentEnabledSettingLPr(component, userId);
21498        }
21499    }
21500
21501    @Override
21502    public void enterSafeMode() {
21503        enforceSystemOrRoot("Only the system can request entering safe mode");
21504
21505        if (!mSystemReady) {
21506            mSafeMode = true;
21507        }
21508    }
21509
21510    @Override
21511    public void systemReady() {
21512        enforceSystemOrRoot("Only the system can claim the system is ready");
21513
21514        mSystemReady = true;
21515        final ContentResolver resolver = mContext.getContentResolver();
21516        ContentObserver co = new ContentObserver(mHandler) {
21517            @Override
21518            public void onChange(boolean selfChange) {
21519                mEphemeralAppsDisabled =
21520                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21521                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21522            }
21523        };
21524        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21525                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21526                false, co, UserHandle.USER_SYSTEM);
21527        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21528                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21529        co.onChange(true);
21530
21531        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21532        // disabled after already being started.
21533        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21534                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21535
21536        // Read the compatibilty setting when the system is ready.
21537        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21538                mContext.getContentResolver(),
21539                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21540        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21541        if (DEBUG_SETTINGS) {
21542            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21543        }
21544
21545        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21546
21547        synchronized (mPackages) {
21548            // Verify that all of the preferred activity components actually
21549            // exist.  It is possible for applications to be updated and at
21550            // that point remove a previously declared activity component that
21551            // had been set as a preferred activity.  We try to clean this up
21552            // the next time we encounter that preferred activity, but it is
21553            // possible for the user flow to never be able to return to that
21554            // situation so here we do a sanity check to make sure we haven't
21555            // left any junk around.
21556            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21557            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21558                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21559                removed.clear();
21560                for (PreferredActivity pa : pir.filterSet()) {
21561                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21562                        removed.add(pa);
21563                    }
21564                }
21565                if (removed.size() > 0) {
21566                    for (int r=0; r<removed.size(); r++) {
21567                        PreferredActivity pa = removed.get(r);
21568                        Slog.w(TAG, "Removing dangling preferred activity: "
21569                                + pa.mPref.mComponent);
21570                        pir.removeFilter(pa);
21571                    }
21572                    mSettings.writePackageRestrictionsLPr(
21573                            mSettings.mPreferredActivities.keyAt(i));
21574                }
21575            }
21576
21577            for (int userId : UserManagerService.getInstance().getUserIds()) {
21578                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21579                    grantPermissionsUserIds = ArrayUtils.appendInt(
21580                            grantPermissionsUserIds, userId);
21581                }
21582            }
21583        }
21584        sUserManager.systemReady();
21585
21586        // If we upgraded grant all default permissions before kicking off.
21587        for (int userId : grantPermissionsUserIds) {
21588            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21589        }
21590
21591        // If we did not grant default permissions, we preload from this the
21592        // default permission exceptions lazily to ensure we don't hit the
21593        // disk on a new user creation.
21594        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21595            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21596        }
21597
21598        // Kick off any messages waiting for system ready
21599        if (mPostSystemReadyMessages != null) {
21600            for (Message msg : mPostSystemReadyMessages) {
21601                msg.sendToTarget();
21602            }
21603            mPostSystemReadyMessages = null;
21604        }
21605
21606        // Watch for external volumes that come and go over time
21607        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21608        storage.registerListener(mStorageListener);
21609
21610        mInstallerService.systemReady();
21611        mPackageDexOptimizer.systemReady();
21612
21613        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21614                StorageManagerInternal.class);
21615        StorageManagerInternal.addExternalStoragePolicy(
21616                new StorageManagerInternal.ExternalStorageMountPolicy() {
21617            @Override
21618            public int getMountMode(int uid, String packageName) {
21619                if (Process.isIsolated(uid)) {
21620                    return Zygote.MOUNT_EXTERNAL_NONE;
21621                }
21622                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21623                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21624                }
21625                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21626                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21627                }
21628                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21629                    return Zygote.MOUNT_EXTERNAL_READ;
21630                }
21631                return Zygote.MOUNT_EXTERNAL_WRITE;
21632            }
21633
21634            @Override
21635            public boolean hasExternalStorage(int uid, String packageName) {
21636                return true;
21637            }
21638        });
21639
21640        // Now that we're mostly running, clean up stale users and apps
21641        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21642        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21643
21644        if (mPrivappPermissionsViolations != null) {
21645            Slog.wtf(TAG,"Signature|privileged permissions not in "
21646                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21647            mPrivappPermissionsViolations = null;
21648        }
21649    }
21650
21651    public void waitForAppDataPrepared() {
21652        if (mPrepareAppDataFuture == null) {
21653            return;
21654        }
21655        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21656        mPrepareAppDataFuture = null;
21657    }
21658
21659    @Override
21660    public boolean isSafeMode() {
21661        // allow instant applications
21662        return mSafeMode;
21663    }
21664
21665    @Override
21666    public boolean hasSystemUidErrors() {
21667        // allow instant applications
21668        return mHasSystemUidErrors;
21669    }
21670
21671    static String arrayToString(int[] array) {
21672        StringBuffer buf = new StringBuffer(128);
21673        buf.append('[');
21674        if (array != null) {
21675            for (int i=0; i<array.length; i++) {
21676                if (i > 0) buf.append(", ");
21677                buf.append(array[i]);
21678            }
21679        }
21680        buf.append(']');
21681        return buf.toString();
21682    }
21683
21684    static class DumpState {
21685        public static final int DUMP_LIBS = 1 << 0;
21686        public static final int DUMP_FEATURES = 1 << 1;
21687        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21688        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21689        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21690        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21691        public static final int DUMP_PERMISSIONS = 1 << 6;
21692        public static final int DUMP_PACKAGES = 1 << 7;
21693        public static final int DUMP_SHARED_USERS = 1 << 8;
21694        public static final int DUMP_MESSAGES = 1 << 9;
21695        public static final int DUMP_PROVIDERS = 1 << 10;
21696        public static final int DUMP_VERIFIERS = 1 << 11;
21697        public static final int DUMP_PREFERRED = 1 << 12;
21698        public static final int DUMP_PREFERRED_XML = 1 << 13;
21699        public static final int DUMP_KEYSETS = 1 << 14;
21700        public static final int DUMP_VERSION = 1 << 15;
21701        public static final int DUMP_INSTALLS = 1 << 16;
21702        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21703        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21704        public static final int DUMP_FROZEN = 1 << 19;
21705        public static final int DUMP_DEXOPT = 1 << 20;
21706        public static final int DUMP_COMPILER_STATS = 1 << 21;
21707        public static final int DUMP_CHANGES = 1 << 22;
21708        public static final int DUMP_VOLUMES = 1 << 23;
21709
21710        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21711
21712        private int mTypes;
21713
21714        private int mOptions;
21715
21716        private boolean mTitlePrinted;
21717
21718        private SharedUserSetting mSharedUser;
21719
21720        public boolean isDumping(int type) {
21721            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21722                return true;
21723            }
21724
21725            return (mTypes & type) != 0;
21726        }
21727
21728        public void setDump(int type) {
21729            mTypes |= type;
21730        }
21731
21732        public boolean isOptionEnabled(int option) {
21733            return (mOptions & option) != 0;
21734        }
21735
21736        public void setOptionEnabled(int option) {
21737            mOptions |= option;
21738        }
21739
21740        public boolean onTitlePrinted() {
21741            final boolean printed = mTitlePrinted;
21742            mTitlePrinted = true;
21743            return printed;
21744        }
21745
21746        public boolean getTitlePrinted() {
21747            return mTitlePrinted;
21748        }
21749
21750        public void setTitlePrinted(boolean enabled) {
21751            mTitlePrinted = enabled;
21752        }
21753
21754        public SharedUserSetting getSharedUser() {
21755            return mSharedUser;
21756        }
21757
21758        public void setSharedUser(SharedUserSetting user) {
21759            mSharedUser = user;
21760        }
21761    }
21762
21763    @Override
21764    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21765            FileDescriptor err, String[] args, ShellCallback callback,
21766            ResultReceiver resultReceiver) {
21767        (new PackageManagerShellCommand(this)).exec(
21768                this, in, out, err, args, callback, resultReceiver);
21769    }
21770
21771    @Override
21772    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21773        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21774
21775        DumpState dumpState = new DumpState();
21776        boolean fullPreferred = false;
21777        boolean checkin = false;
21778
21779        String packageName = null;
21780        ArraySet<String> permissionNames = null;
21781
21782        int opti = 0;
21783        while (opti < args.length) {
21784            String opt = args[opti];
21785            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21786                break;
21787            }
21788            opti++;
21789
21790            if ("-a".equals(opt)) {
21791                // Right now we only know how to print all.
21792            } else if ("-h".equals(opt)) {
21793                pw.println("Package manager dump options:");
21794                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21795                pw.println("    --checkin: dump for a checkin");
21796                pw.println("    -f: print details of intent filters");
21797                pw.println("    -h: print this help");
21798                pw.println("  cmd may be one of:");
21799                pw.println("    l[ibraries]: list known shared libraries");
21800                pw.println("    f[eatures]: list device features");
21801                pw.println("    k[eysets]: print known keysets");
21802                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21803                pw.println("    perm[issions]: dump permissions");
21804                pw.println("    permission [name ...]: dump declaration and use of given permission");
21805                pw.println("    pref[erred]: print preferred package settings");
21806                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21807                pw.println("    prov[iders]: dump content providers");
21808                pw.println("    p[ackages]: dump installed packages");
21809                pw.println("    s[hared-users]: dump shared user IDs");
21810                pw.println("    m[essages]: print collected runtime messages");
21811                pw.println("    v[erifiers]: print package verifier info");
21812                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21813                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21814                pw.println("    version: print database version info");
21815                pw.println("    write: write current settings now");
21816                pw.println("    installs: details about install sessions");
21817                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21818                pw.println("    dexopt: dump dexopt state");
21819                pw.println("    compiler-stats: dump compiler statistics");
21820                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21821                pw.println("    <package.name>: info about given package");
21822                return;
21823            } else if ("--checkin".equals(opt)) {
21824                checkin = true;
21825            } else if ("-f".equals(opt)) {
21826                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21827            } else if ("--proto".equals(opt)) {
21828                dumpProto(fd);
21829                return;
21830            } else {
21831                pw.println("Unknown argument: " + opt + "; use -h for help");
21832            }
21833        }
21834
21835        // Is the caller requesting to dump a particular piece of data?
21836        if (opti < args.length) {
21837            String cmd = args[opti];
21838            opti++;
21839            // Is this a package name?
21840            if ("android".equals(cmd) || cmd.contains(".")) {
21841                packageName = cmd;
21842                // When dumping a single package, we always dump all of its
21843                // filter information since the amount of data will be reasonable.
21844                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21845            } else if ("check-permission".equals(cmd)) {
21846                if (opti >= args.length) {
21847                    pw.println("Error: check-permission missing permission argument");
21848                    return;
21849                }
21850                String perm = args[opti];
21851                opti++;
21852                if (opti >= args.length) {
21853                    pw.println("Error: check-permission missing package argument");
21854                    return;
21855                }
21856
21857                String pkg = args[opti];
21858                opti++;
21859                int user = UserHandle.getUserId(Binder.getCallingUid());
21860                if (opti < args.length) {
21861                    try {
21862                        user = Integer.parseInt(args[opti]);
21863                    } catch (NumberFormatException e) {
21864                        pw.println("Error: check-permission user argument is not a number: "
21865                                + args[opti]);
21866                        return;
21867                    }
21868                }
21869
21870                // Normalize package name to handle renamed packages and static libs
21871                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21872
21873                pw.println(checkPermission(perm, pkg, user));
21874                return;
21875            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21876                dumpState.setDump(DumpState.DUMP_LIBS);
21877            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21878                dumpState.setDump(DumpState.DUMP_FEATURES);
21879            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21880                if (opti >= args.length) {
21881                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21882                            | DumpState.DUMP_SERVICE_RESOLVERS
21883                            | DumpState.DUMP_RECEIVER_RESOLVERS
21884                            | DumpState.DUMP_CONTENT_RESOLVERS);
21885                } else {
21886                    while (opti < args.length) {
21887                        String name = args[opti];
21888                        if ("a".equals(name) || "activity".equals(name)) {
21889                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21890                        } else if ("s".equals(name) || "service".equals(name)) {
21891                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21892                        } else if ("r".equals(name) || "receiver".equals(name)) {
21893                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21894                        } else if ("c".equals(name) || "content".equals(name)) {
21895                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21896                        } else {
21897                            pw.println("Error: unknown resolver table type: " + name);
21898                            return;
21899                        }
21900                        opti++;
21901                    }
21902                }
21903            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21904                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21905            } else if ("permission".equals(cmd)) {
21906                if (opti >= args.length) {
21907                    pw.println("Error: permission requires permission name");
21908                    return;
21909                }
21910                permissionNames = new ArraySet<>();
21911                while (opti < args.length) {
21912                    permissionNames.add(args[opti]);
21913                    opti++;
21914                }
21915                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21916                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21917            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21918                dumpState.setDump(DumpState.DUMP_PREFERRED);
21919            } else if ("preferred-xml".equals(cmd)) {
21920                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21921                if (opti < args.length && "--full".equals(args[opti])) {
21922                    fullPreferred = true;
21923                    opti++;
21924                }
21925            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21926                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21927            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21928                dumpState.setDump(DumpState.DUMP_PACKAGES);
21929            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21930                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21931            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21932                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21933            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21934                dumpState.setDump(DumpState.DUMP_MESSAGES);
21935            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21936                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21937            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21938                    || "intent-filter-verifiers".equals(cmd)) {
21939                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21940            } else if ("version".equals(cmd)) {
21941                dumpState.setDump(DumpState.DUMP_VERSION);
21942            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21943                dumpState.setDump(DumpState.DUMP_KEYSETS);
21944            } else if ("installs".equals(cmd)) {
21945                dumpState.setDump(DumpState.DUMP_INSTALLS);
21946            } else if ("frozen".equals(cmd)) {
21947                dumpState.setDump(DumpState.DUMP_FROZEN);
21948            } else if ("volumes".equals(cmd)) {
21949                dumpState.setDump(DumpState.DUMP_VOLUMES);
21950            } else if ("dexopt".equals(cmd)) {
21951                dumpState.setDump(DumpState.DUMP_DEXOPT);
21952            } else if ("compiler-stats".equals(cmd)) {
21953                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21954            } else if ("changes".equals(cmd)) {
21955                dumpState.setDump(DumpState.DUMP_CHANGES);
21956            } else if ("write".equals(cmd)) {
21957                synchronized (mPackages) {
21958                    mSettings.writeLPr();
21959                    pw.println("Settings written.");
21960                    return;
21961                }
21962            }
21963        }
21964
21965        if (checkin) {
21966            pw.println("vers,1");
21967        }
21968
21969        // reader
21970        synchronized (mPackages) {
21971            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21972                if (!checkin) {
21973                    if (dumpState.onTitlePrinted())
21974                        pw.println();
21975                    pw.println("Database versions:");
21976                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21977                }
21978            }
21979
21980            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21981                if (!checkin) {
21982                    if (dumpState.onTitlePrinted())
21983                        pw.println();
21984                    pw.println("Verifiers:");
21985                    pw.print("  Required: ");
21986                    pw.print(mRequiredVerifierPackage);
21987                    pw.print(" (uid=");
21988                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21989                            UserHandle.USER_SYSTEM));
21990                    pw.println(")");
21991                } else if (mRequiredVerifierPackage != null) {
21992                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21993                    pw.print(",");
21994                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21995                            UserHandle.USER_SYSTEM));
21996                }
21997            }
21998
21999            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22000                    packageName == null) {
22001                if (mIntentFilterVerifierComponent != null) {
22002                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22003                    if (!checkin) {
22004                        if (dumpState.onTitlePrinted())
22005                            pw.println();
22006                        pw.println("Intent Filter Verifier:");
22007                        pw.print("  Using: ");
22008                        pw.print(verifierPackageName);
22009                        pw.print(" (uid=");
22010                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22011                                UserHandle.USER_SYSTEM));
22012                        pw.println(")");
22013                    } else if (verifierPackageName != null) {
22014                        pw.print("ifv,"); pw.print(verifierPackageName);
22015                        pw.print(",");
22016                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22017                                UserHandle.USER_SYSTEM));
22018                    }
22019                } else {
22020                    pw.println();
22021                    pw.println("No Intent Filter Verifier available!");
22022                }
22023            }
22024
22025            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22026                boolean printedHeader = false;
22027                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22028                while (it.hasNext()) {
22029                    String libName = it.next();
22030                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22031                    if (versionedLib == null) {
22032                        continue;
22033                    }
22034                    final int versionCount = versionedLib.size();
22035                    for (int i = 0; i < versionCount; i++) {
22036                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22037                        if (!checkin) {
22038                            if (!printedHeader) {
22039                                if (dumpState.onTitlePrinted())
22040                                    pw.println();
22041                                pw.println("Libraries:");
22042                                printedHeader = true;
22043                            }
22044                            pw.print("  ");
22045                        } else {
22046                            pw.print("lib,");
22047                        }
22048                        pw.print(libEntry.info.getName());
22049                        if (libEntry.info.isStatic()) {
22050                            pw.print(" version=" + libEntry.info.getVersion());
22051                        }
22052                        if (!checkin) {
22053                            pw.print(" -> ");
22054                        }
22055                        if (libEntry.path != null) {
22056                            pw.print(" (jar) ");
22057                            pw.print(libEntry.path);
22058                        } else {
22059                            pw.print(" (apk) ");
22060                            pw.print(libEntry.apk);
22061                        }
22062                        pw.println();
22063                    }
22064                }
22065            }
22066
22067            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22068                if (dumpState.onTitlePrinted())
22069                    pw.println();
22070                if (!checkin) {
22071                    pw.println("Features:");
22072                }
22073
22074                synchronized (mAvailableFeatures) {
22075                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22076                        if (checkin) {
22077                            pw.print("feat,");
22078                            pw.print(feat.name);
22079                            pw.print(",");
22080                            pw.println(feat.version);
22081                        } else {
22082                            pw.print("  ");
22083                            pw.print(feat.name);
22084                            if (feat.version > 0) {
22085                                pw.print(" version=");
22086                                pw.print(feat.version);
22087                            }
22088                            pw.println();
22089                        }
22090                    }
22091                }
22092            }
22093
22094            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22095                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22096                        : "Activity Resolver Table:", "  ", packageName,
22097                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22098                    dumpState.setTitlePrinted(true);
22099                }
22100            }
22101            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22102                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22103                        : "Receiver Resolver Table:", "  ", packageName,
22104                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22105                    dumpState.setTitlePrinted(true);
22106                }
22107            }
22108            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22109                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22110                        : "Service Resolver Table:", "  ", packageName,
22111                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22112                    dumpState.setTitlePrinted(true);
22113                }
22114            }
22115            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22116                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22117                        : "Provider Resolver Table:", "  ", packageName,
22118                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22119                    dumpState.setTitlePrinted(true);
22120                }
22121            }
22122
22123            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22124                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22125                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22126                    int user = mSettings.mPreferredActivities.keyAt(i);
22127                    if (pir.dump(pw,
22128                            dumpState.getTitlePrinted()
22129                                ? "\nPreferred Activities User " + user + ":"
22130                                : "Preferred Activities User " + user + ":", "  ",
22131                            packageName, true, false)) {
22132                        dumpState.setTitlePrinted(true);
22133                    }
22134                }
22135            }
22136
22137            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22138                pw.flush();
22139                FileOutputStream fout = new FileOutputStream(fd);
22140                BufferedOutputStream str = new BufferedOutputStream(fout);
22141                XmlSerializer serializer = new FastXmlSerializer();
22142                try {
22143                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22144                    serializer.startDocument(null, true);
22145                    serializer.setFeature(
22146                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22147                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22148                    serializer.endDocument();
22149                    serializer.flush();
22150                } catch (IllegalArgumentException e) {
22151                    pw.println("Failed writing: " + e);
22152                } catch (IllegalStateException e) {
22153                    pw.println("Failed writing: " + e);
22154                } catch (IOException e) {
22155                    pw.println("Failed writing: " + e);
22156                }
22157            }
22158
22159            if (!checkin
22160                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22161                    && packageName == null) {
22162                pw.println();
22163                int count = mSettings.mPackages.size();
22164                if (count == 0) {
22165                    pw.println("No applications!");
22166                    pw.println();
22167                } else {
22168                    final String prefix = "  ";
22169                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22170                    if (allPackageSettings.size() == 0) {
22171                        pw.println("No domain preferred apps!");
22172                        pw.println();
22173                    } else {
22174                        pw.println("App verification status:");
22175                        pw.println();
22176                        count = 0;
22177                        for (PackageSetting ps : allPackageSettings) {
22178                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22179                            if (ivi == null || ivi.getPackageName() == null) continue;
22180                            pw.println(prefix + "Package: " + ivi.getPackageName());
22181                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22182                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22183                            pw.println();
22184                            count++;
22185                        }
22186                        if (count == 0) {
22187                            pw.println(prefix + "No app verification established.");
22188                            pw.println();
22189                        }
22190                        for (int userId : sUserManager.getUserIds()) {
22191                            pw.println("App linkages for user " + userId + ":");
22192                            pw.println();
22193                            count = 0;
22194                            for (PackageSetting ps : allPackageSettings) {
22195                                final long status = ps.getDomainVerificationStatusForUser(userId);
22196                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22197                                        && !DEBUG_DOMAIN_VERIFICATION) {
22198                                    continue;
22199                                }
22200                                pw.println(prefix + "Package: " + ps.name);
22201                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22202                                String statusStr = IntentFilterVerificationInfo.
22203                                        getStatusStringFromValue(status);
22204                                pw.println(prefix + "Status:  " + statusStr);
22205                                pw.println();
22206                                count++;
22207                            }
22208                            if (count == 0) {
22209                                pw.println(prefix + "No configured app linkages.");
22210                                pw.println();
22211                            }
22212                        }
22213                    }
22214                }
22215            }
22216
22217            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22218                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22219                if (packageName == null && permissionNames == null) {
22220                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22221                        if (iperm == 0) {
22222                            if (dumpState.onTitlePrinted())
22223                                pw.println();
22224                            pw.println("AppOp Permissions:");
22225                        }
22226                        pw.print("  AppOp Permission ");
22227                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22228                        pw.println(":");
22229                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22230                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22231                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22232                        }
22233                    }
22234                }
22235            }
22236
22237            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22238                boolean printedSomething = false;
22239                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22240                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22241                        continue;
22242                    }
22243                    if (!printedSomething) {
22244                        if (dumpState.onTitlePrinted())
22245                            pw.println();
22246                        pw.println("Registered ContentProviders:");
22247                        printedSomething = true;
22248                    }
22249                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22250                    pw.print("    "); pw.println(p.toString());
22251                }
22252                printedSomething = false;
22253                for (Map.Entry<String, PackageParser.Provider> entry :
22254                        mProvidersByAuthority.entrySet()) {
22255                    PackageParser.Provider p = entry.getValue();
22256                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22257                        continue;
22258                    }
22259                    if (!printedSomething) {
22260                        if (dumpState.onTitlePrinted())
22261                            pw.println();
22262                        pw.println("ContentProvider Authorities:");
22263                        printedSomething = true;
22264                    }
22265                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22266                    pw.print("    "); pw.println(p.toString());
22267                    if (p.info != null && p.info.applicationInfo != null) {
22268                        final String appInfo = p.info.applicationInfo.toString();
22269                        pw.print("      applicationInfo="); pw.println(appInfo);
22270                    }
22271                }
22272            }
22273
22274            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22275                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22276            }
22277
22278            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22279                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22280            }
22281
22282            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22283                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22284            }
22285
22286            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22287                if (dumpState.onTitlePrinted()) pw.println();
22288                pw.println("Package Changes:");
22289                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22290                final int K = mChangedPackages.size();
22291                for (int i = 0; i < K; i++) {
22292                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22293                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22294                    final int N = changes.size();
22295                    if (N == 0) {
22296                        pw.print("    "); pw.println("No packages changed");
22297                    } else {
22298                        for (int j = 0; j < N; j++) {
22299                            final String pkgName = changes.valueAt(j);
22300                            final int sequenceNumber = changes.keyAt(j);
22301                            pw.print("    ");
22302                            pw.print("seq=");
22303                            pw.print(sequenceNumber);
22304                            pw.print(", package=");
22305                            pw.println(pkgName);
22306                        }
22307                    }
22308                }
22309            }
22310
22311            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22312                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22313            }
22314
22315            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22316                // XXX should handle packageName != null by dumping only install data that
22317                // the given package is involved with.
22318                if (dumpState.onTitlePrinted()) pw.println();
22319
22320                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22321                ipw.println();
22322                ipw.println("Frozen packages:");
22323                ipw.increaseIndent();
22324                if (mFrozenPackages.size() == 0) {
22325                    ipw.println("(none)");
22326                } else {
22327                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22328                        ipw.println(mFrozenPackages.valueAt(i));
22329                    }
22330                }
22331                ipw.decreaseIndent();
22332            }
22333
22334            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22335                if (dumpState.onTitlePrinted()) pw.println();
22336
22337                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22338                ipw.println();
22339                ipw.println("Loaded volumes:");
22340                ipw.increaseIndent();
22341                if (mLoadedVolumes.size() == 0) {
22342                    ipw.println("(none)");
22343                } else {
22344                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22345                        ipw.println(mLoadedVolumes.valueAt(i));
22346                    }
22347                }
22348                ipw.decreaseIndent();
22349            }
22350
22351            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22352                if (dumpState.onTitlePrinted()) pw.println();
22353                dumpDexoptStateLPr(pw, packageName);
22354            }
22355
22356            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22357                if (dumpState.onTitlePrinted()) pw.println();
22358                dumpCompilerStatsLPr(pw, packageName);
22359            }
22360
22361            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22362                if (dumpState.onTitlePrinted()) pw.println();
22363                mSettings.dumpReadMessagesLPr(pw, dumpState);
22364
22365                pw.println();
22366                pw.println("Package warning messages:");
22367                BufferedReader in = null;
22368                String line = null;
22369                try {
22370                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22371                    while ((line = in.readLine()) != null) {
22372                        if (line.contains("ignored: updated version")) continue;
22373                        pw.println(line);
22374                    }
22375                } catch (IOException ignored) {
22376                } finally {
22377                    IoUtils.closeQuietly(in);
22378                }
22379            }
22380
22381            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22382                BufferedReader in = null;
22383                String line = null;
22384                try {
22385                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22386                    while ((line = in.readLine()) != null) {
22387                        if (line.contains("ignored: updated version")) continue;
22388                        pw.print("msg,");
22389                        pw.println(line);
22390                    }
22391                } catch (IOException ignored) {
22392                } finally {
22393                    IoUtils.closeQuietly(in);
22394                }
22395            }
22396        }
22397
22398        // PackageInstaller should be called outside of mPackages lock
22399        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22400            // XXX should handle packageName != null by dumping only install data that
22401            // the given package is involved with.
22402            if (dumpState.onTitlePrinted()) pw.println();
22403            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22404        }
22405    }
22406
22407    private void dumpProto(FileDescriptor fd) {
22408        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22409
22410        synchronized (mPackages) {
22411            final long requiredVerifierPackageToken =
22412                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22413            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22414            proto.write(
22415                    PackageServiceDumpProto.PackageShortProto.UID,
22416                    getPackageUid(
22417                            mRequiredVerifierPackage,
22418                            MATCH_DEBUG_TRIAGED_MISSING,
22419                            UserHandle.USER_SYSTEM));
22420            proto.end(requiredVerifierPackageToken);
22421
22422            if (mIntentFilterVerifierComponent != null) {
22423                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22424                final long verifierPackageToken =
22425                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22426                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22427                proto.write(
22428                        PackageServiceDumpProto.PackageShortProto.UID,
22429                        getPackageUid(
22430                                verifierPackageName,
22431                                MATCH_DEBUG_TRIAGED_MISSING,
22432                                UserHandle.USER_SYSTEM));
22433                proto.end(verifierPackageToken);
22434            }
22435
22436            dumpSharedLibrariesProto(proto);
22437            dumpFeaturesProto(proto);
22438            mSettings.dumpPackagesProto(proto);
22439            mSettings.dumpSharedUsersProto(proto);
22440            dumpMessagesProto(proto);
22441        }
22442        proto.flush();
22443    }
22444
22445    private void dumpMessagesProto(ProtoOutputStream proto) {
22446        BufferedReader in = null;
22447        String line = null;
22448        try {
22449            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22450            while ((line = in.readLine()) != null) {
22451                if (line.contains("ignored: updated version")) continue;
22452                proto.write(PackageServiceDumpProto.MESSAGES, line);
22453            }
22454        } catch (IOException ignored) {
22455        } finally {
22456            IoUtils.closeQuietly(in);
22457        }
22458    }
22459
22460    private void dumpFeaturesProto(ProtoOutputStream proto) {
22461        synchronized (mAvailableFeatures) {
22462            final int count = mAvailableFeatures.size();
22463            for (int i = 0; i < count; i++) {
22464                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22465                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22466                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22467                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22468                proto.end(featureToken);
22469            }
22470        }
22471    }
22472
22473    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22474        final int count = mSharedLibraries.size();
22475        for (int i = 0; i < count; i++) {
22476            final String libName = mSharedLibraries.keyAt(i);
22477            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22478            if (versionedLib == null) {
22479                continue;
22480            }
22481            final int versionCount = versionedLib.size();
22482            for (int j = 0; j < versionCount; j++) {
22483                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22484                final long sharedLibraryToken =
22485                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22486                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22487                final boolean isJar = (libEntry.path != null);
22488                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22489                if (isJar) {
22490                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22491                } else {
22492                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22493                }
22494                proto.end(sharedLibraryToken);
22495            }
22496        }
22497    }
22498
22499    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22500        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22501        ipw.println();
22502        ipw.println("Dexopt state:");
22503        ipw.increaseIndent();
22504        Collection<PackageParser.Package> packages = null;
22505        if (packageName != null) {
22506            PackageParser.Package targetPackage = mPackages.get(packageName);
22507            if (targetPackage != null) {
22508                packages = Collections.singletonList(targetPackage);
22509            } else {
22510                ipw.println("Unable to find package: " + packageName);
22511                return;
22512            }
22513        } else {
22514            packages = mPackages.values();
22515        }
22516
22517        for (PackageParser.Package pkg : packages) {
22518            ipw.println("[" + pkg.packageName + "]");
22519            ipw.increaseIndent();
22520            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22521            ipw.decreaseIndent();
22522        }
22523    }
22524
22525    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22526        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22527        ipw.println();
22528        ipw.println("Compiler stats:");
22529        ipw.increaseIndent();
22530        Collection<PackageParser.Package> packages = null;
22531        if (packageName != null) {
22532            PackageParser.Package targetPackage = mPackages.get(packageName);
22533            if (targetPackage != null) {
22534                packages = Collections.singletonList(targetPackage);
22535            } else {
22536                ipw.println("Unable to find package: " + packageName);
22537                return;
22538            }
22539        } else {
22540            packages = mPackages.values();
22541        }
22542
22543        for (PackageParser.Package pkg : packages) {
22544            ipw.println("[" + pkg.packageName + "]");
22545            ipw.increaseIndent();
22546
22547            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22548            if (stats == null) {
22549                ipw.println("(No recorded stats)");
22550            } else {
22551                stats.dump(ipw);
22552            }
22553            ipw.decreaseIndent();
22554        }
22555    }
22556
22557    private String dumpDomainString(String packageName) {
22558        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22559                .getList();
22560        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22561
22562        ArraySet<String> result = new ArraySet<>();
22563        if (iviList.size() > 0) {
22564            for (IntentFilterVerificationInfo ivi : iviList) {
22565                for (String host : ivi.getDomains()) {
22566                    result.add(host);
22567                }
22568            }
22569        }
22570        if (filters != null && filters.size() > 0) {
22571            for (IntentFilter filter : filters) {
22572                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22573                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22574                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22575                    result.addAll(filter.getHostsList());
22576                }
22577            }
22578        }
22579
22580        StringBuilder sb = new StringBuilder(result.size() * 16);
22581        for (String domain : result) {
22582            if (sb.length() > 0) sb.append(" ");
22583            sb.append(domain);
22584        }
22585        return sb.toString();
22586    }
22587
22588    // ------- apps on sdcard specific code -------
22589    static final boolean DEBUG_SD_INSTALL = false;
22590
22591    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22592
22593    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22594
22595    private boolean mMediaMounted = false;
22596
22597    static String getEncryptKey() {
22598        try {
22599            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22600                    SD_ENCRYPTION_KEYSTORE_NAME);
22601            if (sdEncKey == null) {
22602                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22603                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22604                if (sdEncKey == null) {
22605                    Slog.e(TAG, "Failed to create encryption keys");
22606                    return null;
22607                }
22608            }
22609            return sdEncKey;
22610        } catch (NoSuchAlgorithmException nsae) {
22611            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22612            return null;
22613        } catch (IOException ioe) {
22614            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22615            return null;
22616        }
22617    }
22618
22619    /*
22620     * Update media status on PackageManager.
22621     */
22622    @Override
22623    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22624        enforceSystemOrRoot("Media status can only be updated by the system");
22625        // reader; this apparently protects mMediaMounted, but should probably
22626        // be a different lock in that case.
22627        synchronized (mPackages) {
22628            Log.i(TAG, "Updating external media status from "
22629                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22630                    + (mediaStatus ? "mounted" : "unmounted"));
22631            if (DEBUG_SD_INSTALL)
22632                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22633                        + ", mMediaMounted=" + mMediaMounted);
22634            if (mediaStatus == mMediaMounted) {
22635                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22636                        : 0, -1);
22637                mHandler.sendMessage(msg);
22638                return;
22639            }
22640            mMediaMounted = mediaStatus;
22641        }
22642        // Queue up an async operation since the package installation may take a
22643        // little while.
22644        mHandler.post(new Runnable() {
22645            public void run() {
22646                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22647            }
22648        });
22649    }
22650
22651    /**
22652     * Called by StorageManagerService when the initial ASECs to scan are available.
22653     * Should block until all the ASEC containers are finished being scanned.
22654     */
22655    public void scanAvailableAsecs() {
22656        updateExternalMediaStatusInner(true, false, false);
22657    }
22658
22659    /*
22660     * Collect information of applications on external media, map them against
22661     * existing containers and update information based on current mount status.
22662     * Please note that we always have to report status if reportStatus has been
22663     * set to true especially when unloading packages.
22664     */
22665    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22666            boolean externalStorage) {
22667        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22668        int[] uidArr = EmptyArray.INT;
22669
22670        final String[] list = PackageHelper.getSecureContainerList();
22671        if (ArrayUtils.isEmpty(list)) {
22672            Log.i(TAG, "No secure containers found");
22673        } else {
22674            // Process list of secure containers and categorize them
22675            // as active or stale based on their package internal state.
22676
22677            // reader
22678            synchronized (mPackages) {
22679                for (String cid : list) {
22680                    // Leave stages untouched for now; installer service owns them
22681                    if (PackageInstallerService.isStageName(cid)) continue;
22682
22683                    if (DEBUG_SD_INSTALL)
22684                        Log.i(TAG, "Processing container " + cid);
22685                    String pkgName = getAsecPackageName(cid);
22686                    if (pkgName == null) {
22687                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22688                        continue;
22689                    }
22690                    if (DEBUG_SD_INSTALL)
22691                        Log.i(TAG, "Looking for pkg : " + pkgName);
22692
22693                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22694                    if (ps == null) {
22695                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22696                        continue;
22697                    }
22698
22699                    /*
22700                     * Skip packages that are not external if we're unmounting
22701                     * external storage.
22702                     */
22703                    if (externalStorage && !isMounted && !isExternal(ps)) {
22704                        continue;
22705                    }
22706
22707                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22708                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22709                    // The package status is changed only if the code path
22710                    // matches between settings and the container id.
22711                    if (ps.codePathString != null
22712                            && ps.codePathString.startsWith(args.getCodePath())) {
22713                        if (DEBUG_SD_INSTALL) {
22714                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22715                                    + " at code path: " + ps.codePathString);
22716                        }
22717
22718                        // We do have a valid package installed on sdcard
22719                        processCids.put(args, ps.codePathString);
22720                        final int uid = ps.appId;
22721                        if (uid != -1) {
22722                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22723                        }
22724                    } else {
22725                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22726                                + ps.codePathString);
22727                    }
22728                }
22729            }
22730
22731            Arrays.sort(uidArr);
22732        }
22733
22734        // Process packages with valid entries.
22735        if (isMounted) {
22736            if (DEBUG_SD_INSTALL)
22737                Log.i(TAG, "Loading packages");
22738            loadMediaPackages(processCids, uidArr, externalStorage);
22739            startCleaningPackages();
22740            mInstallerService.onSecureContainersAvailable();
22741        } else {
22742            if (DEBUG_SD_INSTALL)
22743                Log.i(TAG, "Unloading packages");
22744            unloadMediaPackages(processCids, uidArr, reportStatus);
22745        }
22746    }
22747
22748    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22749            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22750        final int size = infos.size();
22751        final String[] packageNames = new String[size];
22752        final int[] packageUids = new int[size];
22753        for (int i = 0; i < size; i++) {
22754            final ApplicationInfo info = infos.get(i);
22755            packageNames[i] = info.packageName;
22756            packageUids[i] = info.uid;
22757        }
22758        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22759                finishedReceiver);
22760    }
22761
22762    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22763            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22764        sendResourcesChangedBroadcast(mediaStatus, replacing,
22765                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22766    }
22767
22768    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22769            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22770        int size = pkgList.length;
22771        if (size > 0) {
22772            // Send broadcasts here
22773            Bundle extras = new Bundle();
22774            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22775            if (uidArr != null) {
22776                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22777            }
22778            if (replacing) {
22779                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22780            }
22781            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22782                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22783            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22784        }
22785    }
22786
22787   /*
22788     * Look at potentially valid container ids from processCids If package
22789     * information doesn't match the one on record or package scanning fails,
22790     * the cid is added to list of removeCids. We currently don't delete stale
22791     * containers.
22792     */
22793    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22794            boolean externalStorage) {
22795        ArrayList<String> pkgList = new ArrayList<String>();
22796        Set<AsecInstallArgs> keys = processCids.keySet();
22797
22798        for (AsecInstallArgs args : keys) {
22799            String codePath = processCids.get(args);
22800            if (DEBUG_SD_INSTALL)
22801                Log.i(TAG, "Loading container : " + args.cid);
22802            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22803            try {
22804                // Make sure there are no container errors first.
22805                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22806                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22807                            + " when installing from sdcard");
22808                    continue;
22809                }
22810                // Check code path here.
22811                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22812                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22813                            + " does not match one in settings " + codePath);
22814                    continue;
22815                }
22816                // Parse package
22817                int parseFlags = mDefParseFlags;
22818                if (args.isExternalAsec()) {
22819                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22820                }
22821                if (args.isFwdLocked()) {
22822                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22823                }
22824
22825                synchronized (mInstallLock) {
22826                    PackageParser.Package pkg = null;
22827                    try {
22828                        // Sadly we don't know the package name yet to freeze it
22829                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22830                                SCAN_IGNORE_FROZEN, 0, null);
22831                    } catch (PackageManagerException e) {
22832                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22833                    }
22834                    // Scan the package
22835                    if (pkg != null) {
22836                        /*
22837                         * TODO why is the lock being held? doPostInstall is
22838                         * called in other places without the lock. This needs
22839                         * to be straightened out.
22840                         */
22841                        // writer
22842                        synchronized (mPackages) {
22843                            retCode = PackageManager.INSTALL_SUCCEEDED;
22844                            pkgList.add(pkg.packageName);
22845                            // Post process args
22846                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22847                                    pkg.applicationInfo.uid);
22848                        }
22849                    } else {
22850                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22851                    }
22852                }
22853
22854            } finally {
22855                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22856                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22857                }
22858            }
22859        }
22860        // writer
22861        synchronized (mPackages) {
22862            // If the platform SDK has changed since the last time we booted,
22863            // we need to re-grant app permission to catch any new ones that
22864            // appear. This is really a hack, and means that apps can in some
22865            // cases get permissions that the user didn't initially explicitly
22866            // allow... it would be nice to have some better way to handle
22867            // this situation.
22868            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22869                    : mSettings.getInternalVersion();
22870            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22871                    : StorageManager.UUID_PRIVATE_INTERNAL;
22872
22873            int updateFlags = UPDATE_PERMISSIONS_ALL;
22874            if (ver.sdkVersion != mSdkVersion) {
22875                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22876                        + mSdkVersion + "; regranting permissions for external");
22877                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22878            }
22879            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22880
22881            // Yay, everything is now upgraded
22882            ver.forceCurrent();
22883
22884            // can downgrade to reader
22885            // Persist settings
22886            mSettings.writeLPr();
22887        }
22888        // Send a broadcast to let everyone know we are done processing
22889        if (pkgList.size() > 0) {
22890            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22891        }
22892    }
22893
22894   /*
22895     * Utility method to unload a list of specified containers
22896     */
22897    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22898        // Just unmount all valid containers.
22899        for (AsecInstallArgs arg : cidArgs) {
22900            synchronized (mInstallLock) {
22901                arg.doPostDeleteLI(false);
22902           }
22903       }
22904   }
22905
22906    /*
22907     * Unload packages mounted on external media. This involves deleting package
22908     * data from internal structures, sending broadcasts about disabled packages,
22909     * gc'ing to free up references, unmounting all secure containers
22910     * corresponding to packages on external media, and posting a
22911     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22912     * that we always have to post this message if status has been requested no
22913     * matter what.
22914     */
22915    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22916            final boolean reportStatus) {
22917        if (DEBUG_SD_INSTALL)
22918            Log.i(TAG, "unloading media packages");
22919        ArrayList<String> pkgList = new ArrayList<String>();
22920        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22921        final Set<AsecInstallArgs> keys = processCids.keySet();
22922        for (AsecInstallArgs args : keys) {
22923            String pkgName = args.getPackageName();
22924            if (DEBUG_SD_INSTALL)
22925                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22926            // Delete package internally
22927            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22928            synchronized (mInstallLock) {
22929                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22930                final boolean res;
22931                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22932                        "unloadMediaPackages")) {
22933                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22934                            null);
22935                }
22936                if (res) {
22937                    pkgList.add(pkgName);
22938                } else {
22939                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22940                    failedList.add(args);
22941                }
22942            }
22943        }
22944
22945        // reader
22946        synchronized (mPackages) {
22947            // We didn't update the settings after removing each package;
22948            // write them now for all packages.
22949            mSettings.writeLPr();
22950        }
22951
22952        // We have to absolutely send UPDATED_MEDIA_STATUS only
22953        // after confirming that all the receivers processed the ordered
22954        // broadcast when packages get disabled, force a gc to clean things up.
22955        // and unload all the containers.
22956        if (pkgList.size() > 0) {
22957            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22958                    new IIntentReceiver.Stub() {
22959                public void performReceive(Intent intent, int resultCode, String data,
22960                        Bundle extras, boolean ordered, boolean sticky,
22961                        int sendingUser) throws RemoteException {
22962                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22963                            reportStatus ? 1 : 0, 1, keys);
22964                    mHandler.sendMessage(msg);
22965                }
22966            });
22967        } else {
22968            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22969                    keys);
22970            mHandler.sendMessage(msg);
22971        }
22972    }
22973
22974    private void loadPrivatePackages(final VolumeInfo vol) {
22975        mHandler.post(new Runnable() {
22976            @Override
22977            public void run() {
22978                loadPrivatePackagesInner(vol);
22979            }
22980        });
22981    }
22982
22983    private void loadPrivatePackagesInner(VolumeInfo vol) {
22984        final String volumeUuid = vol.fsUuid;
22985        if (TextUtils.isEmpty(volumeUuid)) {
22986            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22987            return;
22988        }
22989
22990        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22991        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22992        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22993
22994        final VersionInfo ver;
22995        final List<PackageSetting> packages;
22996        synchronized (mPackages) {
22997            ver = mSettings.findOrCreateVersion(volumeUuid);
22998            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22999        }
23000
23001        for (PackageSetting ps : packages) {
23002            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23003            synchronized (mInstallLock) {
23004                final PackageParser.Package pkg;
23005                try {
23006                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23007                    loaded.add(pkg.applicationInfo);
23008
23009                } catch (PackageManagerException e) {
23010                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23011                }
23012
23013                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23014                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23015                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23016                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23017                }
23018            }
23019        }
23020
23021        // Reconcile app data for all started/unlocked users
23022        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23023        final UserManager um = mContext.getSystemService(UserManager.class);
23024        UserManagerInternal umInternal = getUserManagerInternal();
23025        for (UserInfo user : um.getUsers()) {
23026            final int flags;
23027            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23028                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23029            } else if (umInternal.isUserRunning(user.id)) {
23030                flags = StorageManager.FLAG_STORAGE_DE;
23031            } else {
23032                continue;
23033            }
23034
23035            try {
23036                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23037                synchronized (mInstallLock) {
23038                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23039                }
23040            } catch (IllegalStateException e) {
23041                // Device was probably ejected, and we'll process that event momentarily
23042                Slog.w(TAG, "Failed to prepare storage: " + e);
23043            }
23044        }
23045
23046        synchronized (mPackages) {
23047            int updateFlags = UPDATE_PERMISSIONS_ALL;
23048            if (ver.sdkVersion != mSdkVersion) {
23049                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23050                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23051                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23052            }
23053            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23054
23055            // Yay, everything is now upgraded
23056            ver.forceCurrent();
23057
23058            mSettings.writeLPr();
23059        }
23060
23061        for (PackageFreezer freezer : freezers) {
23062            freezer.close();
23063        }
23064
23065        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23066        sendResourcesChangedBroadcast(true, false, loaded, null);
23067        mLoadedVolumes.add(vol.getId());
23068    }
23069
23070    private void unloadPrivatePackages(final VolumeInfo vol) {
23071        mHandler.post(new Runnable() {
23072            @Override
23073            public void run() {
23074                unloadPrivatePackagesInner(vol);
23075            }
23076        });
23077    }
23078
23079    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23080        final String volumeUuid = vol.fsUuid;
23081        if (TextUtils.isEmpty(volumeUuid)) {
23082            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23083            return;
23084        }
23085
23086        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23087        synchronized (mInstallLock) {
23088        synchronized (mPackages) {
23089            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23090            for (PackageSetting ps : packages) {
23091                if (ps.pkg == null) continue;
23092
23093                final ApplicationInfo info = ps.pkg.applicationInfo;
23094                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23095                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23096
23097                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23098                        "unloadPrivatePackagesInner")) {
23099                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23100                            false, null)) {
23101                        unloaded.add(info);
23102                    } else {
23103                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23104                    }
23105                }
23106
23107                // Try very hard to release any references to this package
23108                // so we don't risk the system server being killed due to
23109                // open FDs
23110                AttributeCache.instance().removePackage(ps.name);
23111            }
23112
23113            mSettings.writeLPr();
23114        }
23115        }
23116
23117        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23118        sendResourcesChangedBroadcast(false, false, unloaded, null);
23119        mLoadedVolumes.remove(vol.getId());
23120
23121        // Try very hard to release any references to this path so we don't risk
23122        // the system server being killed due to open FDs
23123        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23124
23125        for (int i = 0; i < 3; i++) {
23126            System.gc();
23127            System.runFinalization();
23128        }
23129    }
23130
23131    private void assertPackageKnown(String volumeUuid, String packageName)
23132            throws PackageManagerException {
23133        synchronized (mPackages) {
23134            // Normalize package name to handle renamed packages
23135            packageName = normalizePackageNameLPr(packageName);
23136
23137            final PackageSetting ps = mSettings.mPackages.get(packageName);
23138            if (ps == null) {
23139                throw new PackageManagerException("Package " + packageName + " is unknown");
23140            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23141                throw new PackageManagerException(
23142                        "Package " + packageName + " found on unknown volume " + volumeUuid
23143                                + "; expected volume " + ps.volumeUuid);
23144            }
23145        }
23146    }
23147
23148    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23149            throws PackageManagerException {
23150        synchronized (mPackages) {
23151            // Normalize package name to handle renamed packages
23152            packageName = normalizePackageNameLPr(packageName);
23153
23154            final PackageSetting ps = mSettings.mPackages.get(packageName);
23155            if (ps == null) {
23156                throw new PackageManagerException("Package " + packageName + " is unknown");
23157            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23158                throw new PackageManagerException(
23159                        "Package " + packageName + " found on unknown volume " + volumeUuid
23160                                + "; expected volume " + ps.volumeUuid);
23161            } else if (!ps.getInstalled(userId)) {
23162                throw new PackageManagerException(
23163                        "Package " + packageName + " not installed for user " + userId);
23164            }
23165        }
23166    }
23167
23168    private List<String> collectAbsoluteCodePaths() {
23169        synchronized (mPackages) {
23170            List<String> codePaths = new ArrayList<>();
23171            final int packageCount = mSettings.mPackages.size();
23172            for (int i = 0; i < packageCount; i++) {
23173                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23174                codePaths.add(ps.codePath.getAbsolutePath());
23175            }
23176            return codePaths;
23177        }
23178    }
23179
23180    /**
23181     * Examine all apps present on given mounted volume, and destroy apps that
23182     * aren't expected, either due to uninstallation or reinstallation on
23183     * another volume.
23184     */
23185    private void reconcileApps(String volumeUuid) {
23186        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23187        List<File> filesToDelete = null;
23188
23189        final File[] files = FileUtils.listFilesOrEmpty(
23190                Environment.getDataAppDirectory(volumeUuid));
23191        for (File file : files) {
23192            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23193                    && !PackageInstallerService.isStageName(file.getName());
23194            if (!isPackage) {
23195                // Ignore entries which are not packages
23196                continue;
23197            }
23198
23199            String absolutePath = file.getAbsolutePath();
23200
23201            boolean pathValid = false;
23202            final int absoluteCodePathCount = absoluteCodePaths.size();
23203            for (int i = 0; i < absoluteCodePathCount; i++) {
23204                String absoluteCodePath = absoluteCodePaths.get(i);
23205                if (absolutePath.startsWith(absoluteCodePath)) {
23206                    pathValid = true;
23207                    break;
23208                }
23209            }
23210
23211            if (!pathValid) {
23212                if (filesToDelete == null) {
23213                    filesToDelete = new ArrayList<>();
23214                }
23215                filesToDelete.add(file);
23216            }
23217        }
23218
23219        if (filesToDelete != null) {
23220            final int fileToDeleteCount = filesToDelete.size();
23221            for (int i = 0; i < fileToDeleteCount; i++) {
23222                File fileToDelete = filesToDelete.get(i);
23223                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23224                synchronized (mInstallLock) {
23225                    removeCodePathLI(fileToDelete);
23226                }
23227            }
23228        }
23229    }
23230
23231    /**
23232     * Reconcile all app data for the given user.
23233     * <p>
23234     * Verifies that directories exist and that ownership and labeling is
23235     * correct for all installed apps on all mounted volumes.
23236     */
23237    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23238        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23239        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23240            final String volumeUuid = vol.getFsUuid();
23241            synchronized (mInstallLock) {
23242                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23243            }
23244        }
23245    }
23246
23247    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23248            boolean migrateAppData) {
23249        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23250    }
23251
23252    /**
23253     * Reconcile all app data on given mounted volume.
23254     * <p>
23255     * Destroys app data that isn't expected, either due to uninstallation or
23256     * reinstallation on another volume.
23257     * <p>
23258     * Verifies that directories exist and that ownership and labeling is
23259     * correct for all installed apps.
23260     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23261     */
23262    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23263            boolean migrateAppData, boolean onlyCoreApps) {
23264        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23265                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23266        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23267
23268        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23269        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23270
23271        // First look for stale data that doesn't belong, and check if things
23272        // have changed since we did our last restorecon
23273        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23274            if (StorageManager.isFileEncryptedNativeOrEmulated()
23275                    && !StorageManager.isUserKeyUnlocked(userId)) {
23276                throw new RuntimeException(
23277                        "Yikes, someone asked us to reconcile CE storage while " + userId
23278                                + " was still locked; this would have caused massive data loss!");
23279            }
23280
23281            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23282            for (File file : files) {
23283                final String packageName = file.getName();
23284                try {
23285                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23286                } catch (PackageManagerException e) {
23287                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23288                    try {
23289                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23290                                StorageManager.FLAG_STORAGE_CE, 0);
23291                    } catch (InstallerException e2) {
23292                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23293                    }
23294                }
23295            }
23296        }
23297        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23298            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23299            for (File file : files) {
23300                final String packageName = file.getName();
23301                try {
23302                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23303                } catch (PackageManagerException e) {
23304                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23305                    try {
23306                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23307                                StorageManager.FLAG_STORAGE_DE, 0);
23308                    } catch (InstallerException e2) {
23309                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23310                    }
23311                }
23312            }
23313        }
23314
23315        // Ensure that data directories are ready to roll for all packages
23316        // installed for this volume and user
23317        final List<PackageSetting> packages;
23318        synchronized (mPackages) {
23319            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23320        }
23321        int preparedCount = 0;
23322        for (PackageSetting ps : packages) {
23323            final String packageName = ps.name;
23324            if (ps.pkg == null) {
23325                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23326                // TODO: might be due to legacy ASEC apps; we should circle back
23327                // and reconcile again once they're scanned
23328                continue;
23329            }
23330            // Skip non-core apps if requested
23331            if (onlyCoreApps && !ps.pkg.coreApp) {
23332                result.add(packageName);
23333                continue;
23334            }
23335
23336            if (ps.getInstalled(userId)) {
23337                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23338                preparedCount++;
23339            }
23340        }
23341
23342        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23343        return result;
23344    }
23345
23346    /**
23347     * Prepare app data for the given app just after it was installed or
23348     * upgraded. This method carefully only touches users that it's installed
23349     * for, and it forces a restorecon to handle any seinfo changes.
23350     * <p>
23351     * Verifies that directories exist and that ownership and labeling is
23352     * correct for all installed apps. If there is an ownership mismatch, it
23353     * will try recovering system apps by wiping data; third-party app data is
23354     * left intact.
23355     * <p>
23356     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23357     */
23358    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23359        final PackageSetting ps;
23360        synchronized (mPackages) {
23361            ps = mSettings.mPackages.get(pkg.packageName);
23362            mSettings.writeKernelMappingLPr(ps);
23363        }
23364
23365        final UserManager um = mContext.getSystemService(UserManager.class);
23366        UserManagerInternal umInternal = getUserManagerInternal();
23367        for (UserInfo user : um.getUsers()) {
23368            final int flags;
23369            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23370                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23371            } else if (umInternal.isUserRunning(user.id)) {
23372                flags = StorageManager.FLAG_STORAGE_DE;
23373            } else {
23374                continue;
23375            }
23376
23377            if (ps.getInstalled(user.id)) {
23378                // TODO: when user data is locked, mark that we're still dirty
23379                prepareAppDataLIF(pkg, user.id, flags);
23380            }
23381        }
23382    }
23383
23384    /**
23385     * Prepare app data for the given app.
23386     * <p>
23387     * Verifies that directories exist and that ownership and labeling is
23388     * correct for all installed apps. If there is an ownership mismatch, this
23389     * will try recovering system apps by wiping data; third-party app data is
23390     * left intact.
23391     */
23392    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23393        if (pkg == null) {
23394            Slog.wtf(TAG, "Package was null!", new Throwable());
23395            return;
23396        }
23397        prepareAppDataLeafLIF(pkg, userId, flags);
23398        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23399        for (int i = 0; i < childCount; i++) {
23400            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23401        }
23402    }
23403
23404    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23405            boolean maybeMigrateAppData) {
23406        prepareAppDataLIF(pkg, userId, flags);
23407
23408        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23409            // We may have just shuffled around app data directories, so
23410            // prepare them one more time
23411            prepareAppDataLIF(pkg, userId, flags);
23412        }
23413    }
23414
23415    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23416        if (DEBUG_APP_DATA) {
23417            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23418                    + Integer.toHexString(flags));
23419        }
23420
23421        final String volumeUuid = pkg.volumeUuid;
23422        final String packageName = pkg.packageName;
23423        final ApplicationInfo app = pkg.applicationInfo;
23424        final int appId = UserHandle.getAppId(app.uid);
23425
23426        Preconditions.checkNotNull(app.seInfo);
23427
23428        long ceDataInode = -1;
23429        try {
23430            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23431                    appId, app.seInfo, app.targetSdkVersion);
23432        } catch (InstallerException e) {
23433            if (app.isSystemApp()) {
23434                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23435                        + ", but trying to recover: " + e);
23436                destroyAppDataLeafLIF(pkg, userId, flags);
23437                try {
23438                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23439                            appId, app.seInfo, app.targetSdkVersion);
23440                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23441                } catch (InstallerException e2) {
23442                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23443                }
23444            } else {
23445                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23446            }
23447        }
23448
23449        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23450            // TODO: mark this structure as dirty so we persist it!
23451            synchronized (mPackages) {
23452                final PackageSetting ps = mSettings.mPackages.get(packageName);
23453                if (ps != null) {
23454                    ps.setCeDataInode(ceDataInode, userId);
23455                }
23456            }
23457        }
23458
23459        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23460    }
23461
23462    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23463        if (pkg == null) {
23464            Slog.wtf(TAG, "Package was null!", new Throwable());
23465            return;
23466        }
23467        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23468        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23469        for (int i = 0; i < childCount; i++) {
23470            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23471        }
23472    }
23473
23474    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23475        final String volumeUuid = pkg.volumeUuid;
23476        final String packageName = pkg.packageName;
23477        final ApplicationInfo app = pkg.applicationInfo;
23478
23479        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23480            // Create a native library symlink only if we have native libraries
23481            // and if the native libraries are 32 bit libraries. We do not provide
23482            // this symlink for 64 bit libraries.
23483            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23484                final String nativeLibPath = app.nativeLibraryDir;
23485                try {
23486                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23487                            nativeLibPath, userId);
23488                } catch (InstallerException e) {
23489                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23490                }
23491            }
23492        }
23493    }
23494
23495    /**
23496     * For system apps on non-FBE devices, this method migrates any existing
23497     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23498     * requested by the app.
23499     */
23500    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23501        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23502                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23503            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23504                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23505            try {
23506                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23507                        storageTarget);
23508            } catch (InstallerException e) {
23509                logCriticalInfo(Log.WARN,
23510                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23511            }
23512            return true;
23513        } else {
23514            return false;
23515        }
23516    }
23517
23518    public PackageFreezer freezePackage(String packageName, String killReason) {
23519        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23520    }
23521
23522    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23523        return new PackageFreezer(packageName, userId, killReason);
23524    }
23525
23526    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23527            String killReason) {
23528        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23529    }
23530
23531    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23532            String killReason) {
23533        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23534            return new PackageFreezer();
23535        } else {
23536            return freezePackage(packageName, userId, killReason);
23537        }
23538    }
23539
23540    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23541            String killReason) {
23542        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23543    }
23544
23545    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23546            String killReason) {
23547        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23548            return new PackageFreezer();
23549        } else {
23550            return freezePackage(packageName, userId, killReason);
23551        }
23552    }
23553
23554    /**
23555     * Class that freezes and kills the given package upon creation, and
23556     * unfreezes it upon closing. This is typically used when doing surgery on
23557     * app code/data to prevent the app from running while you're working.
23558     */
23559    private class PackageFreezer implements AutoCloseable {
23560        private final String mPackageName;
23561        private final PackageFreezer[] mChildren;
23562
23563        private final boolean mWeFroze;
23564
23565        private final AtomicBoolean mClosed = new AtomicBoolean();
23566        private final CloseGuard mCloseGuard = CloseGuard.get();
23567
23568        /**
23569         * Create and return a stub freezer that doesn't actually do anything,
23570         * typically used when someone requested
23571         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23572         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23573         */
23574        public PackageFreezer() {
23575            mPackageName = null;
23576            mChildren = null;
23577            mWeFroze = false;
23578            mCloseGuard.open("close");
23579        }
23580
23581        public PackageFreezer(String packageName, int userId, String killReason) {
23582            synchronized (mPackages) {
23583                mPackageName = packageName;
23584                mWeFroze = mFrozenPackages.add(mPackageName);
23585
23586                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23587                if (ps != null) {
23588                    killApplication(ps.name, ps.appId, userId, killReason);
23589                }
23590
23591                final PackageParser.Package p = mPackages.get(packageName);
23592                if (p != null && p.childPackages != null) {
23593                    final int N = p.childPackages.size();
23594                    mChildren = new PackageFreezer[N];
23595                    for (int i = 0; i < N; i++) {
23596                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23597                                userId, killReason);
23598                    }
23599                } else {
23600                    mChildren = null;
23601                }
23602            }
23603            mCloseGuard.open("close");
23604        }
23605
23606        @Override
23607        protected void finalize() throws Throwable {
23608            try {
23609                if (mCloseGuard != null) {
23610                    mCloseGuard.warnIfOpen();
23611                }
23612
23613                close();
23614            } finally {
23615                super.finalize();
23616            }
23617        }
23618
23619        @Override
23620        public void close() {
23621            mCloseGuard.close();
23622            if (mClosed.compareAndSet(false, true)) {
23623                synchronized (mPackages) {
23624                    if (mWeFroze) {
23625                        mFrozenPackages.remove(mPackageName);
23626                    }
23627
23628                    if (mChildren != null) {
23629                        for (PackageFreezer freezer : mChildren) {
23630                            freezer.close();
23631                        }
23632                    }
23633                }
23634            }
23635        }
23636    }
23637
23638    /**
23639     * Verify that given package is currently frozen.
23640     */
23641    private void checkPackageFrozen(String packageName) {
23642        synchronized (mPackages) {
23643            if (!mFrozenPackages.contains(packageName)) {
23644                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23645            }
23646        }
23647    }
23648
23649    @Override
23650    public int movePackage(final String packageName, final String volumeUuid) {
23651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23652
23653        final int callingUid = Binder.getCallingUid();
23654        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23655        final int moveId = mNextMoveId.getAndIncrement();
23656        mHandler.post(new Runnable() {
23657            @Override
23658            public void run() {
23659                try {
23660                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23661                } catch (PackageManagerException e) {
23662                    Slog.w(TAG, "Failed to move " + packageName, e);
23663                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23664                }
23665            }
23666        });
23667        return moveId;
23668    }
23669
23670    private void movePackageInternal(final String packageName, final String volumeUuid,
23671            final int moveId, final int callingUid, UserHandle user)
23672                    throws PackageManagerException {
23673        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23674        final PackageManager pm = mContext.getPackageManager();
23675
23676        final boolean currentAsec;
23677        final String currentVolumeUuid;
23678        final File codeFile;
23679        final String installerPackageName;
23680        final String packageAbiOverride;
23681        final int appId;
23682        final String seinfo;
23683        final String label;
23684        final int targetSdkVersion;
23685        final PackageFreezer freezer;
23686        final int[] installedUserIds;
23687
23688        // reader
23689        synchronized (mPackages) {
23690            final PackageParser.Package pkg = mPackages.get(packageName);
23691            final PackageSetting ps = mSettings.mPackages.get(packageName);
23692            if (pkg == null
23693                    || ps == null
23694                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23695                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23696            }
23697            if (pkg.applicationInfo.isSystemApp()) {
23698                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23699                        "Cannot move system application");
23700            }
23701
23702            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23703            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23704                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23705            if (isInternalStorage && !allow3rdPartyOnInternal) {
23706                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23707                        "3rd party apps are not allowed on internal storage");
23708            }
23709
23710            if (pkg.applicationInfo.isExternalAsec()) {
23711                currentAsec = true;
23712                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23713            } else if (pkg.applicationInfo.isForwardLocked()) {
23714                currentAsec = true;
23715                currentVolumeUuid = "forward_locked";
23716            } else {
23717                currentAsec = false;
23718                currentVolumeUuid = ps.volumeUuid;
23719
23720                final File probe = new File(pkg.codePath);
23721                final File probeOat = new File(probe, "oat");
23722                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23723                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23724                            "Move only supported for modern cluster style installs");
23725                }
23726            }
23727
23728            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23729                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23730                        "Package already moved to " + volumeUuid);
23731            }
23732            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23733                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23734                        "Device admin cannot be moved");
23735            }
23736
23737            if (mFrozenPackages.contains(packageName)) {
23738                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23739                        "Failed to move already frozen package");
23740            }
23741
23742            codeFile = new File(pkg.codePath);
23743            installerPackageName = ps.installerPackageName;
23744            packageAbiOverride = ps.cpuAbiOverrideString;
23745            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23746            seinfo = pkg.applicationInfo.seInfo;
23747            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23748            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23749            freezer = freezePackage(packageName, "movePackageInternal");
23750            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23751        }
23752
23753        final Bundle extras = new Bundle();
23754        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23755        extras.putString(Intent.EXTRA_TITLE, label);
23756        mMoveCallbacks.notifyCreated(moveId, extras);
23757
23758        int installFlags;
23759        final boolean moveCompleteApp;
23760        final File measurePath;
23761
23762        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23763            installFlags = INSTALL_INTERNAL;
23764            moveCompleteApp = !currentAsec;
23765            measurePath = Environment.getDataAppDirectory(volumeUuid);
23766        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23767            installFlags = INSTALL_EXTERNAL;
23768            moveCompleteApp = false;
23769            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23770        } else {
23771            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23772            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23773                    || !volume.isMountedWritable()) {
23774                freezer.close();
23775                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23776                        "Move location not mounted private volume");
23777            }
23778
23779            Preconditions.checkState(!currentAsec);
23780
23781            installFlags = INSTALL_INTERNAL;
23782            moveCompleteApp = true;
23783            measurePath = Environment.getDataAppDirectory(volumeUuid);
23784        }
23785
23786        // If we're moving app data around, we need all the users unlocked
23787        if (moveCompleteApp) {
23788            for (int userId : installedUserIds) {
23789                if (StorageManager.isFileEncryptedNativeOrEmulated()
23790                        && !StorageManager.isUserKeyUnlocked(userId)) {
23791                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23792                            "User " + userId + " must be unlocked");
23793                }
23794            }
23795        }
23796
23797        final PackageStats stats = new PackageStats(null, -1);
23798        synchronized (mInstaller) {
23799            for (int userId : installedUserIds) {
23800                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23801                    freezer.close();
23802                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23803                            "Failed to measure package size");
23804                }
23805            }
23806        }
23807
23808        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23809                + stats.dataSize);
23810
23811        final long startFreeBytes = measurePath.getUsableSpace();
23812        final long sizeBytes;
23813        if (moveCompleteApp) {
23814            sizeBytes = stats.codeSize + stats.dataSize;
23815        } else {
23816            sizeBytes = stats.codeSize;
23817        }
23818
23819        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23820            freezer.close();
23821            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23822                    "Not enough free space to move");
23823        }
23824
23825        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23826
23827        final CountDownLatch installedLatch = new CountDownLatch(1);
23828        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23829            @Override
23830            public void onUserActionRequired(Intent intent) throws RemoteException {
23831                throw new IllegalStateException();
23832            }
23833
23834            @Override
23835            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23836                    Bundle extras) throws RemoteException {
23837                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23838                        + PackageManager.installStatusToString(returnCode, msg));
23839
23840                installedLatch.countDown();
23841                freezer.close();
23842
23843                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23844                switch (status) {
23845                    case PackageInstaller.STATUS_SUCCESS:
23846                        mMoveCallbacks.notifyStatusChanged(moveId,
23847                                PackageManager.MOVE_SUCCEEDED);
23848                        break;
23849                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23850                        mMoveCallbacks.notifyStatusChanged(moveId,
23851                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23852                        break;
23853                    default:
23854                        mMoveCallbacks.notifyStatusChanged(moveId,
23855                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23856                        break;
23857                }
23858            }
23859        };
23860
23861        final MoveInfo move;
23862        if (moveCompleteApp) {
23863            // Kick off a thread to report progress estimates
23864            new Thread() {
23865                @Override
23866                public void run() {
23867                    while (true) {
23868                        try {
23869                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23870                                break;
23871                            }
23872                        } catch (InterruptedException ignored) {
23873                        }
23874
23875                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23876                        final int progress = 10 + (int) MathUtils.constrain(
23877                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23878                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23879                    }
23880                }
23881            }.start();
23882
23883            final String dataAppName = codeFile.getName();
23884            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23885                    dataAppName, appId, seinfo, targetSdkVersion);
23886        } else {
23887            move = null;
23888        }
23889
23890        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23891
23892        final Message msg = mHandler.obtainMessage(INIT_COPY);
23893        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23894        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23895                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23896                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23897                PackageManager.INSTALL_REASON_UNKNOWN);
23898        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23899        msg.obj = params;
23900
23901        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23902                System.identityHashCode(msg.obj));
23903        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23904                System.identityHashCode(msg.obj));
23905
23906        mHandler.sendMessage(msg);
23907    }
23908
23909    @Override
23910    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23911        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23912
23913        final int realMoveId = mNextMoveId.getAndIncrement();
23914        final Bundle extras = new Bundle();
23915        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23916        mMoveCallbacks.notifyCreated(realMoveId, extras);
23917
23918        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23919            @Override
23920            public void onCreated(int moveId, Bundle extras) {
23921                // Ignored
23922            }
23923
23924            @Override
23925            public void onStatusChanged(int moveId, int status, long estMillis) {
23926                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23927            }
23928        };
23929
23930        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23931        storage.setPrimaryStorageUuid(volumeUuid, callback);
23932        return realMoveId;
23933    }
23934
23935    @Override
23936    public int getMoveStatus(int moveId) {
23937        mContext.enforceCallingOrSelfPermission(
23938                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23939        return mMoveCallbacks.mLastStatus.get(moveId);
23940    }
23941
23942    @Override
23943    public void registerMoveCallback(IPackageMoveObserver callback) {
23944        mContext.enforceCallingOrSelfPermission(
23945                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23946        mMoveCallbacks.register(callback);
23947    }
23948
23949    @Override
23950    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23951        mContext.enforceCallingOrSelfPermission(
23952                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23953        mMoveCallbacks.unregister(callback);
23954    }
23955
23956    @Override
23957    public boolean setInstallLocation(int loc) {
23958        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23959                null);
23960        if (getInstallLocation() == loc) {
23961            return true;
23962        }
23963        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23964                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23965            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23966                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23967            return true;
23968        }
23969        return false;
23970   }
23971
23972    @Override
23973    public int getInstallLocation() {
23974        // allow instant app access
23975        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23976                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23977                PackageHelper.APP_INSTALL_AUTO);
23978    }
23979
23980    /** Called by UserManagerService */
23981    void cleanUpUser(UserManagerService userManager, int userHandle) {
23982        synchronized (mPackages) {
23983            mDirtyUsers.remove(userHandle);
23984            mUserNeedsBadging.delete(userHandle);
23985            mSettings.removeUserLPw(userHandle);
23986            mPendingBroadcasts.remove(userHandle);
23987            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23988            removeUnusedPackagesLPw(userManager, userHandle);
23989        }
23990    }
23991
23992    /**
23993     * We're removing userHandle and would like to remove any downloaded packages
23994     * that are no longer in use by any other user.
23995     * @param userHandle the user being removed
23996     */
23997    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23998        final boolean DEBUG_CLEAN_APKS = false;
23999        int [] users = userManager.getUserIds();
24000        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24001        while (psit.hasNext()) {
24002            PackageSetting ps = psit.next();
24003            if (ps.pkg == null) {
24004                continue;
24005            }
24006            final String packageName = ps.pkg.packageName;
24007            // Skip over if system app
24008            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24009                continue;
24010            }
24011            if (DEBUG_CLEAN_APKS) {
24012                Slog.i(TAG, "Checking package " + packageName);
24013            }
24014            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24015            if (keep) {
24016                if (DEBUG_CLEAN_APKS) {
24017                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24018                }
24019            } else {
24020                for (int i = 0; i < users.length; i++) {
24021                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24022                        keep = true;
24023                        if (DEBUG_CLEAN_APKS) {
24024                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24025                                    + users[i]);
24026                        }
24027                        break;
24028                    }
24029                }
24030            }
24031            if (!keep) {
24032                if (DEBUG_CLEAN_APKS) {
24033                    Slog.i(TAG, "  Removing package " + packageName);
24034                }
24035                mHandler.post(new Runnable() {
24036                    public void run() {
24037                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24038                                userHandle, 0);
24039                    } //end run
24040                });
24041            }
24042        }
24043    }
24044
24045    /** Called by UserManagerService */
24046    void createNewUser(int userId, String[] disallowedPackages) {
24047        synchronized (mInstallLock) {
24048            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24049        }
24050        synchronized (mPackages) {
24051            scheduleWritePackageRestrictionsLocked(userId);
24052            scheduleWritePackageListLocked(userId);
24053            applyFactoryDefaultBrowserLPw(userId);
24054            primeDomainVerificationsLPw(userId);
24055        }
24056    }
24057
24058    void onNewUserCreated(final int userId) {
24059        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24060        // If permission review for legacy apps is required, we represent
24061        // dagerous permissions for such apps as always granted runtime
24062        // permissions to keep per user flag state whether review is needed.
24063        // Hence, if a new user is added we have to propagate dangerous
24064        // permission grants for these legacy apps.
24065        if (mPermissionReviewRequired) {
24066            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24067                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24068        }
24069    }
24070
24071    @Override
24072    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24073        mContext.enforceCallingOrSelfPermission(
24074                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24075                "Only package verification agents can read the verifier device identity");
24076
24077        synchronized (mPackages) {
24078            return mSettings.getVerifierDeviceIdentityLPw();
24079        }
24080    }
24081
24082    @Override
24083    public void setPermissionEnforced(String permission, boolean enforced) {
24084        // TODO: Now that we no longer change GID for storage, this should to away.
24085        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24086                "setPermissionEnforced");
24087        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24088            synchronized (mPackages) {
24089                if (mSettings.mReadExternalStorageEnforced == null
24090                        || mSettings.mReadExternalStorageEnforced != enforced) {
24091                    mSettings.mReadExternalStorageEnforced = enforced;
24092                    mSettings.writeLPr();
24093                }
24094            }
24095            // kill any non-foreground processes so we restart them and
24096            // grant/revoke the GID.
24097            final IActivityManager am = ActivityManager.getService();
24098            if (am != null) {
24099                final long token = Binder.clearCallingIdentity();
24100                try {
24101                    am.killProcessesBelowForeground("setPermissionEnforcement");
24102                } catch (RemoteException e) {
24103                } finally {
24104                    Binder.restoreCallingIdentity(token);
24105                }
24106            }
24107        } else {
24108            throw new IllegalArgumentException("No selective enforcement for " + permission);
24109        }
24110    }
24111
24112    @Override
24113    @Deprecated
24114    public boolean isPermissionEnforced(String permission) {
24115        // allow instant applications
24116        return true;
24117    }
24118
24119    @Override
24120    public boolean isStorageLow() {
24121        // allow instant applications
24122        final long token = Binder.clearCallingIdentity();
24123        try {
24124            final DeviceStorageMonitorInternal
24125                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24126            if (dsm != null) {
24127                return dsm.isMemoryLow();
24128            } else {
24129                return false;
24130            }
24131        } finally {
24132            Binder.restoreCallingIdentity(token);
24133        }
24134    }
24135
24136    @Override
24137    public IPackageInstaller getPackageInstaller() {
24138        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24139            return null;
24140        }
24141        return mInstallerService;
24142    }
24143
24144    private boolean userNeedsBadging(int userId) {
24145        int index = mUserNeedsBadging.indexOfKey(userId);
24146        if (index < 0) {
24147            final UserInfo userInfo;
24148            final long token = Binder.clearCallingIdentity();
24149            try {
24150                userInfo = sUserManager.getUserInfo(userId);
24151            } finally {
24152                Binder.restoreCallingIdentity(token);
24153            }
24154            final boolean b;
24155            if (userInfo != null && userInfo.isManagedProfile()) {
24156                b = true;
24157            } else {
24158                b = false;
24159            }
24160            mUserNeedsBadging.put(userId, b);
24161            return b;
24162        }
24163        return mUserNeedsBadging.valueAt(index);
24164    }
24165
24166    @Override
24167    public KeySet getKeySetByAlias(String packageName, String alias) {
24168        if (packageName == null || alias == null) {
24169            return null;
24170        }
24171        synchronized(mPackages) {
24172            final PackageParser.Package pkg = mPackages.get(packageName);
24173            if (pkg == null) {
24174                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24175                throw new IllegalArgumentException("Unknown package: " + packageName);
24176            }
24177            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24178            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24179                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24180                throw new IllegalArgumentException("Unknown package: " + packageName);
24181            }
24182            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24183            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24184        }
24185    }
24186
24187    @Override
24188    public KeySet getSigningKeySet(String packageName) {
24189        if (packageName == null) {
24190            return null;
24191        }
24192        synchronized(mPackages) {
24193            final int callingUid = Binder.getCallingUid();
24194            final int callingUserId = UserHandle.getUserId(callingUid);
24195            final PackageParser.Package pkg = mPackages.get(packageName);
24196            if (pkg == null) {
24197                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24198                throw new IllegalArgumentException("Unknown package: " + packageName);
24199            }
24200            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24201            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24202                // filter and pretend the package doesn't exist
24203                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24204                        + ", uid:" + callingUid);
24205                throw new IllegalArgumentException("Unknown package: " + packageName);
24206            }
24207            if (pkg.applicationInfo.uid != callingUid
24208                    && Process.SYSTEM_UID != callingUid) {
24209                throw new SecurityException("May not access signing KeySet of other apps.");
24210            }
24211            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24212            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24213        }
24214    }
24215
24216    @Override
24217    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24218        final int callingUid = Binder.getCallingUid();
24219        if (getInstantAppPackageName(callingUid) != null) {
24220            return false;
24221        }
24222        if (packageName == null || ks == null) {
24223            return false;
24224        }
24225        synchronized(mPackages) {
24226            final PackageParser.Package pkg = mPackages.get(packageName);
24227            if (pkg == null
24228                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24229                            UserHandle.getUserId(callingUid))) {
24230                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24231                throw new IllegalArgumentException("Unknown package: " + packageName);
24232            }
24233            IBinder ksh = ks.getToken();
24234            if (ksh instanceof KeySetHandle) {
24235                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24236                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24237            }
24238            return false;
24239        }
24240    }
24241
24242    @Override
24243    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24244        final int callingUid = Binder.getCallingUid();
24245        if (getInstantAppPackageName(callingUid) != null) {
24246            return false;
24247        }
24248        if (packageName == null || ks == null) {
24249            return false;
24250        }
24251        synchronized(mPackages) {
24252            final PackageParser.Package pkg = mPackages.get(packageName);
24253            if (pkg == null
24254                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24255                            UserHandle.getUserId(callingUid))) {
24256                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24257                throw new IllegalArgumentException("Unknown package: " + packageName);
24258            }
24259            IBinder ksh = ks.getToken();
24260            if (ksh instanceof KeySetHandle) {
24261                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24262                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24263            }
24264            return false;
24265        }
24266    }
24267
24268    private void deletePackageIfUnusedLPr(final String packageName) {
24269        PackageSetting ps = mSettings.mPackages.get(packageName);
24270        if (ps == null) {
24271            return;
24272        }
24273        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24274            // TODO Implement atomic delete if package is unused
24275            // It is currently possible that the package will be deleted even if it is installed
24276            // after this method returns.
24277            mHandler.post(new Runnable() {
24278                public void run() {
24279                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24280                            0, PackageManager.DELETE_ALL_USERS);
24281                }
24282            });
24283        }
24284    }
24285
24286    /**
24287     * Check and throw if the given before/after packages would be considered a
24288     * downgrade.
24289     */
24290    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24291            throws PackageManagerException {
24292        if (after.versionCode < before.mVersionCode) {
24293            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24294                    "Update version code " + after.versionCode + " is older than current "
24295                    + before.mVersionCode);
24296        } else if (after.versionCode == before.mVersionCode) {
24297            if (after.baseRevisionCode < before.baseRevisionCode) {
24298                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24299                        "Update base revision code " + after.baseRevisionCode
24300                        + " is older than current " + before.baseRevisionCode);
24301            }
24302
24303            if (!ArrayUtils.isEmpty(after.splitNames)) {
24304                for (int i = 0; i < after.splitNames.length; i++) {
24305                    final String splitName = after.splitNames[i];
24306                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24307                    if (j != -1) {
24308                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24309                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24310                                    "Update split " + splitName + " revision code "
24311                                    + after.splitRevisionCodes[i] + " is older than current "
24312                                    + before.splitRevisionCodes[j]);
24313                        }
24314                    }
24315                }
24316            }
24317        }
24318    }
24319
24320    private static class MoveCallbacks extends Handler {
24321        private static final int MSG_CREATED = 1;
24322        private static final int MSG_STATUS_CHANGED = 2;
24323
24324        private final RemoteCallbackList<IPackageMoveObserver>
24325                mCallbacks = new RemoteCallbackList<>();
24326
24327        private final SparseIntArray mLastStatus = new SparseIntArray();
24328
24329        public MoveCallbacks(Looper looper) {
24330            super(looper);
24331        }
24332
24333        public void register(IPackageMoveObserver callback) {
24334            mCallbacks.register(callback);
24335        }
24336
24337        public void unregister(IPackageMoveObserver callback) {
24338            mCallbacks.unregister(callback);
24339        }
24340
24341        @Override
24342        public void handleMessage(Message msg) {
24343            final SomeArgs args = (SomeArgs) msg.obj;
24344            final int n = mCallbacks.beginBroadcast();
24345            for (int i = 0; i < n; i++) {
24346                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24347                try {
24348                    invokeCallback(callback, msg.what, args);
24349                } catch (RemoteException ignored) {
24350                }
24351            }
24352            mCallbacks.finishBroadcast();
24353            args.recycle();
24354        }
24355
24356        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24357                throws RemoteException {
24358            switch (what) {
24359                case MSG_CREATED: {
24360                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24361                    break;
24362                }
24363                case MSG_STATUS_CHANGED: {
24364                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24365                    break;
24366                }
24367            }
24368        }
24369
24370        private void notifyCreated(int moveId, Bundle extras) {
24371            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24372
24373            final SomeArgs args = SomeArgs.obtain();
24374            args.argi1 = moveId;
24375            args.arg2 = extras;
24376            obtainMessage(MSG_CREATED, args).sendToTarget();
24377        }
24378
24379        private void notifyStatusChanged(int moveId, int status) {
24380            notifyStatusChanged(moveId, status, -1);
24381        }
24382
24383        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24384            Slog.v(TAG, "Move " + moveId + " status " + status);
24385
24386            final SomeArgs args = SomeArgs.obtain();
24387            args.argi1 = moveId;
24388            args.argi2 = status;
24389            args.arg3 = estMillis;
24390            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24391
24392            synchronized (mLastStatus) {
24393                mLastStatus.put(moveId, status);
24394            }
24395        }
24396    }
24397
24398    private final static class OnPermissionChangeListeners extends Handler {
24399        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24400
24401        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24402                new RemoteCallbackList<>();
24403
24404        public OnPermissionChangeListeners(Looper looper) {
24405            super(looper);
24406        }
24407
24408        @Override
24409        public void handleMessage(Message msg) {
24410            switch (msg.what) {
24411                case MSG_ON_PERMISSIONS_CHANGED: {
24412                    final int uid = msg.arg1;
24413                    handleOnPermissionsChanged(uid);
24414                } break;
24415            }
24416        }
24417
24418        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24419            mPermissionListeners.register(listener);
24420
24421        }
24422
24423        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24424            mPermissionListeners.unregister(listener);
24425        }
24426
24427        public void onPermissionsChanged(int uid) {
24428            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24429                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24430            }
24431        }
24432
24433        private void handleOnPermissionsChanged(int uid) {
24434            final int count = mPermissionListeners.beginBroadcast();
24435            try {
24436                for (int i = 0; i < count; i++) {
24437                    IOnPermissionsChangeListener callback = mPermissionListeners
24438                            .getBroadcastItem(i);
24439                    try {
24440                        callback.onPermissionsChanged(uid);
24441                    } catch (RemoteException e) {
24442                        Log.e(TAG, "Permission listener is dead", e);
24443                    }
24444                }
24445            } finally {
24446                mPermissionListeners.finishBroadcast();
24447            }
24448        }
24449    }
24450
24451    private class PackageManagerInternalImpl extends PackageManagerInternal {
24452        @Override
24453        public void setLocationPackagesProvider(PackagesProvider provider) {
24454            synchronized (mPackages) {
24455                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24456            }
24457        }
24458
24459        @Override
24460        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24461            synchronized (mPackages) {
24462                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24463            }
24464        }
24465
24466        @Override
24467        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24468            synchronized (mPackages) {
24469                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24470            }
24471        }
24472
24473        @Override
24474        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24475            synchronized (mPackages) {
24476                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24477            }
24478        }
24479
24480        @Override
24481        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24482            synchronized (mPackages) {
24483                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24484            }
24485        }
24486
24487        @Override
24488        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24489            synchronized (mPackages) {
24490                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24491            }
24492        }
24493
24494        @Override
24495        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24496            synchronized (mPackages) {
24497                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24498                        packageName, userId);
24499            }
24500        }
24501
24502        @Override
24503        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24504            synchronized (mPackages) {
24505                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24506                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24507                        packageName, userId);
24508            }
24509        }
24510
24511        @Override
24512        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24513            synchronized (mPackages) {
24514                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24515                        packageName, userId);
24516            }
24517        }
24518
24519        @Override
24520        public void setKeepUninstalledPackages(final List<String> packageList) {
24521            Preconditions.checkNotNull(packageList);
24522            List<String> removedFromList = null;
24523            synchronized (mPackages) {
24524                if (mKeepUninstalledPackages != null) {
24525                    final int packagesCount = mKeepUninstalledPackages.size();
24526                    for (int i = 0; i < packagesCount; i++) {
24527                        String oldPackage = mKeepUninstalledPackages.get(i);
24528                        if (packageList != null && packageList.contains(oldPackage)) {
24529                            continue;
24530                        }
24531                        if (removedFromList == null) {
24532                            removedFromList = new ArrayList<>();
24533                        }
24534                        removedFromList.add(oldPackage);
24535                    }
24536                }
24537                mKeepUninstalledPackages = new ArrayList<>(packageList);
24538                if (removedFromList != null) {
24539                    final int removedCount = removedFromList.size();
24540                    for (int i = 0; i < removedCount; i++) {
24541                        deletePackageIfUnusedLPr(removedFromList.get(i));
24542                    }
24543                }
24544            }
24545        }
24546
24547        @Override
24548        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24549            synchronized (mPackages) {
24550                // If we do not support permission review, done.
24551                if (!mPermissionReviewRequired) {
24552                    return false;
24553                }
24554
24555                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24556                if (packageSetting == null) {
24557                    return false;
24558                }
24559
24560                // Permission review applies only to apps not supporting the new permission model.
24561                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24562                    return false;
24563                }
24564
24565                // Legacy apps have the permission and get user consent on launch.
24566                PermissionsState permissionsState = packageSetting.getPermissionsState();
24567                return permissionsState.isPermissionReviewRequired(userId);
24568            }
24569        }
24570
24571        @Override
24572        public PackageInfo getPackageInfo(
24573                String packageName, int flags, int filterCallingUid, int userId) {
24574            return PackageManagerService.this
24575                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24576                            flags, filterCallingUid, userId);
24577        }
24578
24579        @Override
24580        public ApplicationInfo getApplicationInfo(
24581                String packageName, int flags, int filterCallingUid, int userId) {
24582            return PackageManagerService.this
24583                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24584        }
24585
24586        @Override
24587        public ActivityInfo getActivityInfo(
24588                ComponentName component, int flags, int filterCallingUid, int userId) {
24589            return PackageManagerService.this
24590                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24591        }
24592
24593        @Override
24594        public List<ResolveInfo> queryIntentActivities(
24595                Intent intent, int flags, int filterCallingUid, int userId) {
24596            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24597            return PackageManagerService.this
24598                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24599                            userId, false /*resolveForStart*/);
24600        }
24601
24602        @Override
24603        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24604                int userId) {
24605            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24606        }
24607
24608        @Override
24609        public void setDeviceAndProfileOwnerPackages(
24610                int deviceOwnerUserId, String deviceOwnerPackage,
24611                SparseArray<String> profileOwnerPackages) {
24612            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24613                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24614        }
24615
24616        @Override
24617        public boolean isPackageDataProtected(int userId, String packageName) {
24618            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24619        }
24620
24621        @Override
24622        public boolean isPackageEphemeral(int userId, String packageName) {
24623            synchronized (mPackages) {
24624                final PackageSetting ps = mSettings.mPackages.get(packageName);
24625                return ps != null ? ps.getInstantApp(userId) : false;
24626            }
24627        }
24628
24629        @Override
24630        public boolean wasPackageEverLaunched(String packageName, int userId) {
24631            synchronized (mPackages) {
24632                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24633            }
24634        }
24635
24636        @Override
24637        public void grantRuntimePermission(String packageName, String name, int userId,
24638                boolean overridePolicy) {
24639            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24640                    overridePolicy);
24641        }
24642
24643        @Override
24644        public void revokeRuntimePermission(String packageName, String name, int userId,
24645                boolean overridePolicy) {
24646            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24647                    overridePolicy);
24648        }
24649
24650        @Override
24651        public String getNameForUid(int uid) {
24652            return PackageManagerService.this.getNameForUid(uid);
24653        }
24654
24655        @Override
24656        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24657                Intent origIntent, String resolvedType, String callingPackage,
24658                Bundle verificationBundle, int userId) {
24659            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24660                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24661                    userId);
24662        }
24663
24664        @Override
24665        public void grantEphemeralAccess(int userId, Intent intent,
24666                int targetAppId, int ephemeralAppId) {
24667            synchronized (mPackages) {
24668                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24669                        targetAppId, ephemeralAppId);
24670            }
24671        }
24672
24673        @Override
24674        public boolean isInstantAppInstallerComponent(ComponentName component) {
24675            synchronized (mPackages) {
24676                return mInstantAppInstallerActivity != null
24677                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24678            }
24679        }
24680
24681        @Override
24682        public void pruneInstantApps() {
24683            mInstantAppRegistry.pruneInstantApps();
24684        }
24685
24686        @Override
24687        public String getSetupWizardPackageName() {
24688            return mSetupWizardPackage;
24689        }
24690
24691        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24692            if (policy != null) {
24693                mExternalSourcesPolicy = policy;
24694            }
24695        }
24696
24697        @Override
24698        public boolean isPackagePersistent(String packageName) {
24699            synchronized (mPackages) {
24700                PackageParser.Package pkg = mPackages.get(packageName);
24701                return pkg != null
24702                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24703                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24704                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24705                        : false;
24706            }
24707        }
24708
24709        @Override
24710        public List<PackageInfo> getOverlayPackages(int userId) {
24711            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24712            synchronized (mPackages) {
24713                for (PackageParser.Package p : mPackages.values()) {
24714                    if (p.mOverlayTarget != null) {
24715                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24716                        if (pkg != null) {
24717                            overlayPackages.add(pkg);
24718                        }
24719                    }
24720                }
24721            }
24722            return overlayPackages;
24723        }
24724
24725        @Override
24726        public List<String> getTargetPackageNames(int userId) {
24727            List<String> targetPackages = new ArrayList<>();
24728            synchronized (mPackages) {
24729                for (PackageParser.Package p : mPackages.values()) {
24730                    if (p.mOverlayTarget == null) {
24731                        targetPackages.add(p.packageName);
24732                    }
24733                }
24734            }
24735            return targetPackages;
24736        }
24737
24738        @Override
24739        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24740                @Nullable List<String> overlayPackageNames) {
24741            synchronized (mPackages) {
24742                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24743                    Slog.e(TAG, "failed to find package " + targetPackageName);
24744                    return false;
24745                }
24746                ArrayList<String> overlayPaths = null;
24747                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24748                    final int N = overlayPackageNames.size();
24749                    overlayPaths = new ArrayList<>(N);
24750                    for (int i = 0; i < N; i++) {
24751                        final String packageName = overlayPackageNames.get(i);
24752                        final PackageParser.Package pkg = mPackages.get(packageName);
24753                        if (pkg == null) {
24754                            Slog.e(TAG, "failed to find package " + packageName);
24755                            return false;
24756                        }
24757                        overlayPaths.add(pkg.baseCodePath);
24758                    }
24759                }
24760
24761                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24762                ps.setOverlayPaths(overlayPaths, userId);
24763                return true;
24764            }
24765        }
24766
24767        @Override
24768        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24769                int flags, int userId) {
24770            return resolveIntentInternal(
24771                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24772        }
24773
24774        @Override
24775        public ResolveInfo resolveService(Intent intent, String resolvedType,
24776                int flags, int userId, int callingUid) {
24777            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24778        }
24779
24780        @Override
24781        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24782            synchronized (mPackages) {
24783                mIsolatedOwners.put(isolatedUid, ownerUid);
24784            }
24785        }
24786
24787        @Override
24788        public void removeIsolatedUid(int isolatedUid) {
24789            synchronized (mPackages) {
24790                mIsolatedOwners.delete(isolatedUid);
24791            }
24792        }
24793
24794        @Override
24795        public int getUidTargetSdkVersion(int uid) {
24796            synchronized (mPackages) {
24797                return getUidTargetSdkVersionLockedLPr(uid);
24798            }
24799        }
24800
24801        @Override
24802        public boolean canAccessInstantApps(int callingUid, int userId) {
24803            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24804        }
24805    }
24806
24807    @Override
24808    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24809        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24810        synchronized (mPackages) {
24811            final long identity = Binder.clearCallingIdentity();
24812            try {
24813                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24814                        packageNames, userId);
24815            } finally {
24816                Binder.restoreCallingIdentity(identity);
24817            }
24818        }
24819    }
24820
24821    @Override
24822    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24823        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24824        synchronized (mPackages) {
24825            final long identity = Binder.clearCallingIdentity();
24826            try {
24827                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24828                        packageNames, userId);
24829            } finally {
24830                Binder.restoreCallingIdentity(identity);
24831            }
24832        }
24833    }
24834
24835    private static void enforceSystemOrPhoneCaller(String tag) {
24836        int callingUid = Binder.getCallingUid();
24837        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24838            throw new SecurityException(
24839                    "Cannot call " + tag + " from UID " + callingUid);
24840        }
24841    }
24842
24843    boolean isHistoricalPackageUsageAvailable() {
24844        return mPackageUsage.isHistoricalPackageUsageAvailable();
24845    }
24846
24847    /**
24848     * Return a <b>copy</b> of the collection of packages known to the package manager.
24849     * @return A copy of the values of mPackages.
24850     */
24851    Collection<PackageParser.Package> getPackages() {
24852        synchronized (mPackages) {
24853            return new ArrayList<>(mPackages.values());
24854        }
24855    }
24856
24857    /**
24858     * Logs process start information (including base APK hash) to the security log.
24859     * @hide
24860     */
24861    @Override
24862    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24863            String apkFile, int pid) {
24864        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24865            return;
24866        }
24867        if (!SecurityLog.isLoggingEnabled()) {
24868            return;
24869        }
24870        Bundle data = new Bundle();
24871        data.putLong("startTimestamp", System.currentTimeMillis());
24872        data.putString("processName", processName);
24873        data.putInt("uid", uid);
24874        data.putString("seinfo", seinfo);
24875        data.putString("apkFile", apkFile);
24876        data.putInt("pid", pid);
24877        Message msg = mProcessLoggingHandler.obtainMessage(
24878                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24879        msg.setData(data);
24880        mProcessLoggingHandler.sendMessage(msg);
24881    }
24882
24883    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24884        return mCompilerStats.getPackageStats(pkgName);
24885    }
24886
24887    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24888        return getOrCreateCompilerPackageStats(pkg.packageName);
24889    }
24890
24891    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24892        return mCompilerStats.getOrCreatePackageStats(pkgName);
24893    }
24894
24895    public void deleteCompilerPackageStats(String pkgName) {
24896        mCompilerStats.deletePackageStats(pkgName);
24897    }
24898
24899    @Override
24900    public int getInstallReason(String packageName, int userId) {
24901        final int callingUid = Binder.getCallingUid();
24902        enforceCrossUserPermission(callingUid, userId,
24903                true /* requireFullPermission */, false /* checkShell */,
24904                "get install reason");
24905        synchronized (mPackages) {
24906            final PackageSetting ps = mSettings.mPackages.get(packageName);
24907            if (filterAppAccessLPr(ps, callingUid, userId)) {
24908                return PackageManager.INSTALL_REASON_UNKNOWN;
24909            }
24910            if (ps != null) {
24911                return ps.getInstallReason(userId);
24912            }
24913        }
24914        return PackageManager.INSTALL_REASON_UNKNOWN;
24915    }
24916
24917    @Override
24918    public boolean canRequestPackageInstalls(String packageName, int userId) {
24919        return canRequestPackageInstallsInternal(packageName, 0, userId,
24920                true /* throwIfPermNotDeclared*/);
24921    }
24922
24923    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24924            boolean throwIfPermNotDeclared) {
24925        int callingUid = Binder.getCallingUid();
24926        int uid = getPackageUid(packageName, 0, userId);
24927        if (callingUid != uid && callingUid != Process.ROOT_UID
24928                && callingUid != Process.SYSTEM_UID) {
24929            throw new SecurityException(
24930                    "Caller uid " + callingUid + " does not own package " + packageName);
24931        }
24932        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24933        if (info == null) {
24934            return false;
24935        }
24936        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24937            return false;
24938        }
24939        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24940        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24941        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24942            if (throwIfPermNotDeclared) {
24943                throw new SecurityException("Need to declare " + appOpPermission
24944                        + " to call this api");
24945            } else {
24946                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24947                return false;
24948            }
24949        }
24950        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24951            return false;
24952        }
24953        if (mExternalSourcesPolicy != null) {
24954            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24955            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24956                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24957            }
24958        }
24959        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24960    }
24961
24962    @Override
24963    public ComponentName getInstantAppResolverSettingsComponent() {
24964        return mInstantAppResolverSettingsComponent;
24965    }
24966
24967    @Override
24968    public ComponentName getInstantAppInstallerComponent() {
24969        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24970            return null;
24971        }
24972        return mInstantAppInstallerActivity == null
24973                ? null : mInstantAppInstallerActivity.getComponentName();
24974    }
24975
24976    @Override
24977    public String getInstantAppAndroidId(String packageName, int userId) {
24978        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24979                "getInstantAppAndroidId");
24980        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24981                true /* requireFullPermission */, false /* checkShell */,
24982                "getInstantAppAndroidId");
24983        // Make sure the target is an Instant App.
24984        if (!isInstantApp(packageName, userId)) {
24985            return null;
24986        }
24987        synchronized (mPackages) {
24988            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24989        }
24990    }
24991}
24992
24993interface PackageSender {
24994    void sendPackageBroadcast(final String action, final String pkg,
24995        final Bundle extras, final int flags, final String targetPkg,
24996        final IIntentReceiver finishedReceiver, final int[] userIds);
24997    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24998        int appId, int... userIds);
24999}
25000