Home | History | Annotate | Download | only in pm
      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 
     17 package com.android.server.pm;
     18 
     19 import static android.Manifest.permission.DELETE_PACKAGES;
     20 import static android.Manifest.permission.INSTALL_PACKAGES;
     21 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
     22 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
     23 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
     24 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
     25 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
     26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
     27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
     28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
     29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
     30 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
     31 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
     32 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
     33 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
     34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
     35 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
     36 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
     37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
     38 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
     39 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
     40 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
     41 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
     42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
     43 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
     44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
     45 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
     46 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
     47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
     48 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
     49 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
     50 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
     51 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
     52 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
     53 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
     54 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
     55 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
     56 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
     57 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
     58 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
     59 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
     60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
     61 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
     62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
     63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
     64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
     65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
     66 import static android.content.pm.PackageManager.MATCH_ALL;
     67 import static android.content.pm.PackageManager.MATCH_ANY_USER;
     68 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
     69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
     70 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
     71 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
     72 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
     73 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
     74 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
     75 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
     76 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
     77 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
     78 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
     79 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
     80 import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
     81 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
     82 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
     83 import static android.content.pm.PackageManager.PERMISSION_DENIED;
     84 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
     85 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
     86 import static android.content.pm.PackageParser.isApkFile;
     87 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
     88 import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
     89 import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
     90 import static android.system.OsConstants.O_CREAT;
     91 import static android.system.OsConstants.O_RDWR;
     92 
     93 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
     94 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
     95 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
     96 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
     97 import static com.android.internal.util.ArrayUtils.appendInt;
     98 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
     99 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
    100 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
    101 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
    102 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
    103 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
    104 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
    105 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
    106 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
    107 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
    108 
    109 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
    110 
    111 import android.Manifest;
    112 import android.annotation.IntDef;
    113 import android.annotation.NonNull;
    114 import android.annotation.Nullable;
    115 import android.app.ActivityManager;
    116 import android.app.AppOpsManager;
    117 import android.app.IActivityManager;
    118 import android.app.ResourcesManager;
    119 import android.app.admin.IDevicePolicyManager;
    120 import android.app.admin.SecurityLog;
    121 import android.app.backup.IBackupManager;
    122 import android.content.BroadcastReceiver;
    123 import android.content.ComponentName;
    124 import android.content.ContentResolver;
    125 import android.content.Context;
    126 import android.content.IIntentReceiver;
    127 import android.content.Intent;
    128 import android.content.IntentFilter;
    129 import android.content.IntentSender;
    130 import android.content.IntentSender.SendIntentException;
    131 import android.content.ServiceConnection;
    132 import android.content.pm.ActivityInfo;
    133 import android.content.pm.ApplicationInfo;
    134 import android.content.pm.AppsQueryHelper;
    135 import android.content.pm.AuxiliaryResolveInfo;
    136 import android.content.pm.ChangedPackages;
    137 import android.content.pm.ComponentInfo;
    138 import android.content.pm.FallbackCategoryProvider;
    139 import android.content.pm.FeatureInfo;
    140 import android.content.pm.IDexModuleRegisterCallback;
    141 import android.content.pm.IOnPermissionsChangeListener;
    142 import android.content.pm.IPackageDataObserver;
    143 import android.content.pm.IPackageDeleteObserver;
    144 import android.content.pm.IPackageDeleteObserver2;
    145 import android.content.pm.IPackageInstallObserver2;
    146 import android.content.pm.IPackageInstaller;
    147 import android.content.pm.IPackageManager;
    148 import android.content.pm.IPackageManagerNative;
    149 import android.content.pm.IPackageMoveObserver;
    150 import android.content.pm.IPackageStatsObserver;
    151 import android.content.pm.InstantAppInfo;
    152 import android.content.pm.InstantAppRequest;
    153 import android.content.pm.InstantAppResolveInfo;
    154 import android.content.pm.InstrumentationInfo;
    155 import android.content.pm.IntentFilterVerificationInfo;
    156 import android.content.pm.KeySet;
    157 import android.content.pm.PackageCleanItem;
    158 import android.content.pm.PackageInfo;
    159 import android.content.pm.PackageInfoLite;
    160 import android.content.pm.PackageInstaller;
    161 import android.content.pm.PackageManager;
    162 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
    163 import android.content.pm.PackageManagerInternal;
    164 import android.content.pm.PackageParser;
    165 import android.content.pm.PackageParser.ActivityIntentInfo;
    166 import android.content.pm.PackageParser.PackageLite;
    167 import android.content.pm.PackageParser.PackageParserException;
    168 import android.content.pm.PackageStats;
    169 import android.content.pm.PackageUserState;
    170 import android.content.pm.ParceledListSlice;
    171 import android.content.pm.PermissionGroupInfo;
    172 import android.content.pm.PermissionInfo;
    173 import android.content.pm.ProviderInfo;
    174 import android.content.pm.ResolveInfo;
    175 import android.content.pm.ServiceInfo;
    176 import android.content.pm.SharedLibraryInfo;
    177 import android.content.pm.Signature;
    178 import android.content.pm.UserInfo;
    179 import android.content.pm.VerifierDeviceIdentity;
    180 import android.content.pm.VerifierInfo;
    181 import android.content.pm.VersionedPackage;
    182 import android.content.res.Resources;
    183 import android.database.ContentObserver;
    184 import android.graphics.Bitmap;
    185 import android.hardware.display.DisplayManager;
    186 import android.net.Uri;
    187 import android.os.Binder;
    188 import android.os.Build;
    189 import android.os.Bundle;
    190 import android.os.Debug;
    191 import android.os.Environment;
    192 import android.os.Environment.UserEnvironment;
    193 import android.os.FileUtils;
    194 import android.os.Handler;
    195 import android.os.IBinder;
    196 import android.os.Looper;
    197 import android.os.Message;
    198 import android.os.Parcel;
    199 import android.os.ParcelFileDescriptor;
    200 import android.os.PatternMatcher;
    201 import android.os.Process;
    202 import android.os.RemoteCallbackList;
    203 import android.os.RemoteException;
    204 import android.os.ResultReceiver;
    205 import android.os.SELinux;
    206 import android.os.ServiceManager;
    207 import android.os.ShellCallback;
    208 import android.os.SystemClock;
    209 import android.os.SystemProperties;
    210 import android.os.Trace;
    211 import android.os.UserHandle;
    212 import android.os.UserManager;
    213 import android.os.UserManagerInternal;
    214 import android.os.storage.IStorageManager;
    215 import android.os.storage.StorageEventListener;
    216 import android.os.storage.StorageManager;
    217 import android.os.storage.StorageManagerInternal;
    218 import android.os.storage.VolumeInfo;
    219 import android.os.storage.VolumeRecord;
    220 import android.provider.Settings.Global;
    221 import android.provider.Settings.Secure;
    222 import android.security.KeyStore;
    223 import android.security.SystemKeyStore;
    224 import android.service.pm.PackageServiceDumpProto;
    225 import android.system.ErrnoException;
    226 import android.system.Os;
    227 import android.text.TextUtils;
    228 import android.text.format.DateUtils;
    229 import android.util.ArrayMap;
    230 import android.util.ArraySet;
    231 import android.util.Base64;
    232 import android.util.TimingsTraceLog;
    233 import android.util.DisplayMetrics;
    234 import android.util.EventLog;
    235 import android.util.ExceptionUtils;
    236 import android.util.Log;
    237 import android.util.LogPrinter;
    238 import android.util.MathUtils;
    239 import android.util.PackageUtils;
    240 import android.util.Pair;
    241 import android.util.PrintStreamPrinter;
    242 import android.util.Slog;
    243 import android.util.SparseArray;
    244 import android.util.SparseBooleanArray;
    245 import android.util.SparseIntArray;
    246 import android.util.Xml;
    247 import android.util.jar.StrictJarFile;
    248 import android.util.proto.ProtoOutputStream;
    249 import android.view.Display;
    250 
    251 import com.android.internal.R;
    252 import com.android.internal.annotations.GuardedBy;
    253 import com.android.internal.app.IMediaContainerService;
    254 import com.android.internal.app.ResolverActivity;
    255 import com.android.internal.content.NativeLibraryHelper;
    256 import com.android.internal.content.PackageHelper;
    257 import com.android.internal.logging.MetricsLogger;
    258 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
    259 import com.android.internal.os.IParcelFileDescriptorFactory;
    260 import com.android.internal.os.RoSystemProperties;
    261 import com.android.internal.os.SomeArgs;
    262 import com.android.internal.os.Zygote;
    263 import com.android.internal.telephony.CarrierAppUtils;
    264 import com.android.internal.util.ArrayUtils;
    265 import com.android.internal.util.ConcurrentUtils;
    266 import com.android.internal.util.DumpUtils;
    267 import com.android.internal.util.FastPrintWriter;
    268 import com.android.internal.util.FastXmlSerializer;
    269 import com.android.internal.util.IndentingPrintWriter;
    270 import com.android.internal.util.Preconditions;
    271 import com.android.internal.util.XmlUtils;
    272 import com.android.server.AttributeCache;
    273 import com.android.server.DeviceIdleController;
    274 import com.android.server.EventLogTags;
    275 import com.android.server.FgThread;
    276 import com.android.server.IntentResolver;
    277 import com.android.server.LocalServices;
    278 import com.android.server.LockGuard;
    279 import com.android.server.ServiceThread;
    280 import com.android.server.SystemConfig;
    281 import com.android.server.SystemServerInitThreadPool;
    282 import com.android.server.Watchdog;
    283 import com.android.server.net.NetworkPolicyManagerInternal;
    284 import com.android.server.pm.Installer.InstallerException;
    285 import com.android.server.pm.PermissionsState.PermissionState;
    286 import com.android.server.pm.Settings.DatabaseVersion;
    287 import com.android.server.pm.Settings.VersionInfo;
    288 import com.android.server.pm.dex.DexManager;
    289 import com.android.server.pm.dex.DexoptOptions;
    290 import com.android.server.pm.dex.PackageDexUsage;
    291 import com.android.server.storage.DeviceStorageMonitorInternal;
    292 
    293 import dalvik.system.CloseGuard;
    294 import dalvik.system.DexFile;
    295 import dalvik.system.VMRuntime;
    296 
    297 import libcore.io.IoUtils;
    298 import libcore.io.Streams;
    299 import libcore.util.EmptyArray;
    300 
    301 import org.xmlpull.v1.XmlPullParser;
    302 import org.xmlpull.v1.XmlPullParserException;
    303 import org.xmlpull.v1.XmlSerializer;
    304 
    305 import java.io.BufferedOutputStream;
    306 import java.io.BufferedReader;
    307 import java.io.ByteArrayInputStream;
    308 import java.io.ByteArrayOutputStream;
    309 import java.io.File;
    310 import java.io.FileDescriptor;
    311 import java.io.FileInputStream;
    312 import java.io.FileOutputStream;
    313 import java.io.FileReader;
    314 import java.io.FilenameFilter;
    315 import java.io.IOException;
    316 import java.io.InputStream;
    317 import java.io.OutputStream;
    318 import java.io.PrintWriter;
    319 import java.lang.annotation.Retention;
    320 import java.lang.annotation.RetentionPolicy;
    321 import java.nio.charset.StandardCharsets;
    322 import java.security.DigestInputStream;
    323 import java.security.MessageDigest;
    324 import java.security.NoSuchAlgorithmException;
    325 import java.security.PublicKey;
    326 import java.security.SecureRandom;
    327 import java.security.cert.Certificate;
    328 import java.security.cert.CertificateEncodingException;
    329 import java.security.cert.CertificateException;
    330 import java.text.SimpleDateFormat;
    331 import java.util.ArrayList;
    332 import java.util.Arrays;
    333 import java.util.Collection;
    334 import java.util.Collections;
    335 import java.util.Comparator;
    336 import java.util.Date;
    337 import java.util.HashMap;
    338 import java.util.HashSet;
    339 import java.util.Iterator;
    340 import java.util.List;
    341 import java.util.Map;
    342 import java.util.Objects;
    343 import java.util.Set;
    344 import java.util.concurrent.CountDownLatch;
    345 import java.util.concurrent.Future;
    346 import java.util.concurrent.TimeUnit;
    347 import java.util.concurrent.atomic.AtomicBoolean;
    348 import java.util.concurrent.atomic.AtomicInteger;
    349 import java.util.zip.GZIPInputStream;
    350 
    351 /**
    352  * Keep track of all those APKs everywhere.
    353  * <p>
    354  * Internally there are two important locks:
    355  * <ul>
    356  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
    357  * and other related state. It is a fine-grained lock that should only be held
    358  * momentarily, as it's one of the most contended locks in the system.
    359  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
    360  * operations typically involve heavy lifting of application data on disk. Since
    361  * {@code installd} is single-threaded, and it's operations can often be slow,
    362  * this lock should never be acquired while already holding {@link #mPackages}.
    363  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
    364  * holding {@link #mInstallLock}.
    365  * </ul>
    366  * Many internal methods rely on the caller to hold the appropriate locks, and
    367  * this contract is expressed through method name suffixes:
    368  * <ul>
    369  * <li>fooLI(): the caller must hold {@link #mInstallLock}
    370  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
    371  * being modified must be frozen
    372  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
    373  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
    374  * </ul>
    375  * <p>
    376  * Because this class is very central to the platform's security; please run all
    377  * CTS and unit tests whenever making modifications:
    378  *
    379  * <pre>
    380  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
    381  * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
    382  * </pre>
    383  */
    384 public class PackageManagerService extends IPackageManager.Stub
    385         implements PackageSender {
    386     static final String TAG = "PackageManager";
    387     static final boolean DEBUG_SETTINGS = false;
    388     static final boolean DEBUG_PREFERRED = false;
    389     static final boolean DEBUG_UPGRADE = false;
    390     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
    391     private static final boolean DEBUG_BACKUP = false;
    392     private static final boolean DEBUG_INSTALL = false;
    393     private static final boolean DEBUG_REMOVE = false;
    394     private static final boolean DEBUG_BROADCASTS = false;
    395     private static final boolean DEBUG_SHOW_INFO = false;
    396     private static final boolean DEBUG_PACKAGE_INFO = false;
    397     private static final boolean DEBUG_INTENT_MATCHING = false;
    398     private static final boolean DEBUG_PACKAGE_SCANNING = false;
    399     private static final boolean DEBUG_VERIFY = false;
    400     private static final boolean DEBUG_FILTERS = false;
    401     private static final boolean DEBUG_PERMISSIONS = false;
    402     private static final boolean DEBUG_SHARED_LIBRARIES = false;
    403     private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
    404 
    405     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
    406     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
    407     // user, but by default initialize to this.
    408     public static final boolean DEBUG_DEXOPT = false;
    409 
    410     private static final boolean DEBUG_ABI_SELECTION = false;
    411     private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
    412     private static final boolean DEBUG_TRIAGED_MISSING = false;
    413     private static final boolean DEBUG_APP_DATA = false;
    414 
    415     /** REMOVE. According to Svet, this was only used to reset permissions during development. */
    416     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
    417 
    418     private static final boolean HIDE_EPHEMERAL_APIS = false;
    419 
    420     private static final boolean ENABLE_FREE_CACHE_V2 =
    421             SystemProperties.getBoolean("fw.free_cache_v2", true);
    422 
    423     private static final int RADIO_UID = Process.PHONE_UID;
    424     private static final int LOG_UID = Process.LOG_UID;
    425     private static final int NFC_UID = Process.NFC_UID;
    426     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
    427     private static final int SHELL_UID = Process.SHELL_UID;
    428 
    429     // Cap the size of permission trees that 3rd party apps can define
    430     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
    431 
    432     // Suffix used during package installation when copying/moving
    433     // package apks to install directory.
    434     private static final String INSTALL_PACKAGE_SUFFIX = "-";
    435 
    436     static final int SCAN_NO_DEX = 1<<1;
    437     static final int SCAN_FORCE_DEX = 1<<2;
    438     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
    439     static final int SCAN_NEW_INSTALL = 1<<4;
    440     static final int SCAN_UPDATE_TIME = 1<<5;
    441     static final int SCAN_BOOTING = 1<<6;
    442     static final int SCAN_TRUSTED_OVERLAY = 1<<7;
    443     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
    444     static final int SCAN_REPLACING = 1<<9;
    445     static final int SCAN_REQUIRE_KNOWN = 1<<10;
    446     static final int SCAN_MOVE = 1<<11;
    447     static final int SCAN_INITIAL = 1<<12;
    448     static final int SCAN_CHECK_ONLY = 1<<13;
    449     static final int SCAN_DONT_KILL_APP = 1<<14;
    450     static final int SCAN_IGNORE_FROZEN = 1<<15;
    451     static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
    452     static final int SCAN_AS_INSTANT_APP = 1<<17;
    453     static final int SCAN_AS_FULL_APP = 1<<18;
    454     static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
    455     /** Should not be with the scan flags */
    456     static final int FLAGS_REMOVE_CHATTY = 1<<31;
    457 
    458     private static final String STATIC_SHARED_LIB_DELIMITER = "_";
    459     /** Extension of the compressed packages */
    460     private final static String COMPRESSED_EXTENSION = ".gz";
    461     /** Suffix of stub packages on the system partition */
    462     private final static String STUB_SUFFIX = "-Stub";
    463 
    464     private static final int[] EMPTY_INT_ARRAY = new int[0];
    465 
    466     private static final int TYPE_UNKNOWN = 0;
    467     private static final int TYPE_ACTIVITY = 1;
    468     private static final int TYPE_RECEIVER = 2;
    469     private static final int TYPE_SERVICE = 3;
    470     private static final int TYPE_PROVIDER = 4;
    471     @IntDef(prefix = { "TYPE_" }, value = {
    472             TYPE_UNKNOWN,
    473             TYPE_ACTIVITY,
    474             TYPE_RECEIVER,
    475             TYPE_SERVICE,
    476             TYPE_PROVIDER,
    477     })
    478     @Retention(RetentionPolicy.SOURCE)
    479     public @interface ComponentType {}
    480 
    481     /**
    482      * Timeout (in milliseconds) after which the watchdog should declare that
    483      * our handler thread is wedged.  The usual default for such things is one
    484      * minute but we sometimes do very lengthy I/O operations on this thread,
    485      * such as installing multi-gigabyte applications, so ours needs to be longer.
    486      */
    487     static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
    488 
    489     /**
    490      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
    491      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
    492      * settings entry if available, otherwise we use the hardcoded default.  If it's been
    493      * more than this long since the last fstrim, we force one during the boot sequence.
    494      *
    495      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
    496      * one gets run at the next available charging+idle time.  This final mandatory
    497      * no-fstrim check kicks in only of the other scheduling criteria is never met.
    498      */
    499     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
    500 
    501     /**
    502      * Whether verification is enabled by default.
    503      */
    504     private static final boolean DEFAULT_VERIFY_ENABLE = true;
    505 
    506     /**
    507      * The default maximum time to wait for the verification agent to return in
    508      * milliseconds.
    509      */
    510     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
    511 
    512     /**
    513      * The default response for package verification timeout.
    514      *
    515      * This can be either PackageManager.VERIFICATION_ALLOW or
    516      * PackageManager.VERIFICATION_REJECT.
    517      */
    518     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
    519 
    520     static final String PLATFORM_PACKAGE_NAME = "android";
    521 
    522     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
    523 
    524     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
    525             DEFAULT_CONTAINER_PACKAGE,
    526             "com.android.defcontainer.DefaultContainerService");
    527 
    528     private static final String KILL_APP_REASON_GIDS_CHANGED =
    529             "permission grant or revoke changed gids";
    530 
    531     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
    532             "permissions revoked";
    533 
    534     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
    535 
    536     private static final String PACKAGE_SCHEME = "package";
    537 
    538     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
    539 
    540     /** Permission grant: not grant the permission. */
    541     private static final int GRANT_DENIED = 1;
    542 
    543     /** Permission grant: grant the permission as an install permission. */
    544     private static final int GRANT_INSTALL = 2;
    545 
    546     /** Permission grant: grant the permission as a runtime one. */
    547     private static final int GRANT_RUNTIME = 3;
    548 
    549     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
    550     private static final int GRANT_UPGRADE = 4;
    551 
    552     /** Canonical intent used to identify what counts as a "web browser" app */
    553     private static final Intent sBrowserIntent;
    554     static {
    555         sBrowserIntent = new Intent();
    556         sBrowserIntent.setAction(Intent.ACTION_VIEW);
    557         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
    558         sBrowserIntent.setData(Uri.parse("http:"));
    559     }
    560 
    561     /**
    562      * The set of all protected actions [i.e. those actions for which a high priority
    563      * intent filter is disallowed].
    564      */
    565     private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
    566     static {
    567         PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
    568         PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
    569         PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
    570         PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
    571     }
    572 
    573     // Compilation reasons.
    574     public static final int REASON_FIRST_BOOT = 0;
    575     public static final int REASON_BOOT = 1;
    576     public static final int REASON_INSTALL = 2;
    577     public static final int REASON_BACKGROUND_DEXOPT = 3;
    578     public static final int REASON_AB_OTA = 4;
    579     public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
    580     public static final int REASON_SHARED = 6;
    581 
    582     public static final int REASON_LAST = REASON_SHARED;
    583 
    584     /** All dangerous permission names in the same order as the events in MetricsEvent */
    585     private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
    586             Manifest.permission.READ_CALENDAR,
    587             Manifest.permission.WRITE_CALENDAR,
    588             Manifest.permission.CAMERA,
    589             Manifest.permission.READ_CONTACTS,
    590             Manifest.permission.WRITE_CONTACTS,
    591             Manifest.permission.GET_ACCOUNTS,
    592             Manifest.permission.ACCESS_FINE_LOCATION,
    593             Manifest.permission.ACCESS_COARSE_LOCATION,
    594             Manifest.permission.RECORD_AUDIO,
    595             Manifest.permission.READ_PHONE_STATE,
    596             Manifest.permission.CALL_PHONE,
    597             Manifest.permission.READ_CALL_LOG,
    598             Manifest.permission.WRITE_CALL_LOG,
    599             Manifest.permission.ADD_VOICEMAIL,
    600             Manifest.permission.USE_SIP,
    601             Manifest.permission.PROCESS_OUTGOING_CALLS,
    602             Manifest.permission.READ_CELL_BROADCASTS,
    603             Manifest.permission.BODY_SENSORS,
    604             Manifest.permission.SEND_SMS,
    605             Manifest.permission.RECEIVE_SMS,
    606             Manifest.permission.READ_SMS,
    607             Manifest.permission.RECEIVE_WAP_PUSH,
    608             Manifest.permission.RECEIVE_MMS,
    609             Manifest.permission.READ_EXTERNAL_STORAGE,
    610             Manifest.permission.WRITE_EXTERNAL_STORAGE,
    611             Manifest.permission.READ_PHONE_NUMBERS,
    612             Manifest.permission.ANSWER_PHONE_CALLS);
    613 
    614 
    615     /**
    616      * Version number for the package parser cache. Increment this whenever the format or
    617      * extent of cached data changes. See {@code PackageParser#setCacheDir}.
    618      */
    619     private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
    620 
    621     /**
    622      * Whether the package parser cache is enabled.
    623      */
    624     private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
    625 
    626     final ServiceThread mHandlerThread;
    627 
    628     final PackageHandler mHandler;
    629 
    630     private final ProcessLoggingHandler mProcessLoggingHandler;
    631 
    632     /**
    633      * Messages for {@link #mHandler} that need to wait for system ready before
    634      * being dispatched.
    635      */
    636     private ArrayList<Message> mPostSystemReadyMessages;
    637 
    638     final int mSdkVersion = Build.VERSION.SDK_INT;
    639 
    640     final Context mContext;
    641     final boolean mFactoryTest;
    642     final boolean mOnlyCore;
    643     final DisplayMetrics mMetrics;
    644     final int mDefParseFlags;
    645     final String[] mSeparateProcesses;
    646     final boolean mIsUpgrade;
    647     final boolean mIsPreNUpgrade;
    648     final boolean mIsPreNMR1Upgrade;
    649 
    650     // Have we told the Activity Manager to whitelist the default container service by uid yet?
    651     @GuardedBy("mPackages")
    652     boolean mDefaultContainerWhitelisted = false;
    653 
    654     @GuardedBy("mPackages")
    655     private boolean mDexOptDialogShown;
    656 
    657     /** The location for ASEC container files on internal storage. */
    658     final String mAsecInternalPath;
    659 
    660     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
    661     // LOCK HELD.  Can be called with mInstallLock held.
    662     @GuardedBy("mInstallLock")
    663     final Installer mInstaller;
    664 
    665     /** Directory where installed third-party apps stored */
    666     final File mAppInstallDir;
    667 
    668     /**
    669      * Directory to which applications installed internally have their
    670      * 32 bit native libraries copied.
    671      */
    672     private File mAppLib32InstallDir;
    673 
    674     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
    675     // apps.
    676     final File mDrmAppPrivateInstallDir;
    677 
    678     // ----------------------------------------------------------------
    679 
    680     // Lock for state used when installing and doing other long running
    681     // operations.  Methods that must be called with this lock held have
    682     // the suffix "LI".
    683     final Object mInstallLock = new Object();
    684 
    685     // ----------------------------------------------------------------
    686 
    687     // Keys are String (package name), values are Package.  This also serves
    688     // as the lock for the global state.  Methods that must be called with
    689     // this lock held have the prefix "LP".
    690     @GuardedBy("mPackages")
    691     final ArrayMap<String, PackageParser.Package> mPackages =
    692             new ArrayMap<String, PackageParser.Package>();
    693 
    694     final ArrayMap<String, Set<String>> mKnownCodebase =
    695             new ArrayMap<String, Set<String>>();
    696 
    697     // Keys are isolated uids and values are the uid of the application
    698     // that created the isolated proccess.
    699     @GuardedBy("mPackages")
    700     final SparseIntArray mIsolatedOwners = new SparseIntArray();
    701 
    702     /**
    703      * Tracks new system packages [received in an OTA] that we expect to
    704      * find updated user-installed versions. Keys are package name, values
    705      * are package location.
    706      */
    707     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
    708     /**
    709      * Tracks high priority intent filters for protected actions. During boot, certain
    710      * filter actions are protected and should never be allowed to have a high priority
    711      * intent filter for them. However, there is one, and only one exception -- the
    712      * setup wizard. It must be able to define a high priority intent filter for these
    713      * actions to ensure there are no escapes from the wizard. We need to delay processing
    714      * of these during boot as we need to look at all of the system packages in order
    715      * to know which component is the setup wizard.
    716      */
    717     private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
    718     /**
    719      * Whether or not processing protected filters should be deferred.
    720      */
    721     private boolean mDeferProtectedFilters = true;
    722 
    723     /**
    724      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
    725      */
    726     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
    727     /**
    728      * Whether or not system app permissions should be promoted from install to runtime.
    729      */
    730     boolean mPromoteSystemApps;
    731 
    732     @GuardedBy("mPackages")
    733     final Settings mSettings;
    734 
    735     /**
    736      * Set of package names that are currently "frozen", which means active
    737      * surgery is being done on the code/data for that package. The platform
    738      * will refuse to launch frozen packages to avoid race conditions.
    739      *
    740      * @see PackageFreezer
    741      */
    742     @GuardedBy("mPackages")
    743     final ArraySet<String> mFrozenPackages = new ArraySet<>();
    744 
    745     final ProtectedPackages mProtectedPackages;
    746 
    747     @GuardedBy("mLoadedVolumes")
    748     final ArraySet<String> mLoadedVolumes = new ArraySet<>();
    749 
    750     boolean mFirstBoot;
    751 
    752     PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
    753 
    754     // System configuration read by SystemConfig.
    755     final int[] mGlobalGids;
    756     final SparseArray<ArraySet<String>> mSystemPermissions;
    757     @GuardedBy("mAvailableFeatures")
    758     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
    759 
    760     // If mac_permissions.xml was found for seinfo labeling.
    761     boolean mFoundPolicyFile;
    762 
    763     private final InstantAppRegistry mInstantAppRegistry;
    764 
    765     @GuardedBy("mPackages")
    766     int mChangedPackagesSequenceNumber;
    767     /**
    768      * List of changed [installed, removed or updated] packages.
    769      * mapping from user id -> sequence number -> package name
    770      */
    771     @GuardedBy("mPackages")
    772     final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
    773     /**
    774      * The sequence number of the last change to a package.
    775      * mapping from user id -> package name -> sequence number
    776      */
    777     @GuardedBy("mPackages")
    778     final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
    779 
    780     class PackageParserCallback implements PackageParser.Callback {
    781         @Override public final boolean hasFeature(String feature) {
    782             return PackageManagerService.this.hasSystemFeature(feature, 0);
    783         }
    784 
    785         final List<PackageParser.Package> getStaticOverlayPackagesLocked(
    786                 Collection<PackageParser.Package> allPackages, String targetPackageName) {
    787             List<PackageParser.Package> overlayPackages = null;
    788             for (PackageParser.Package p : allPackages) {
    789                 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
    790                     if (overlayPackages == null) {
    791                         overlayPackages = new ArrayList<PackageParser.Package>();
    792                     }
    793                     overlayPackages.add(p);
    794                 }
    795             }
    796             if (overlayPackages != null) {
    797                 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
    798                     public int compare(PackageParser.Package p1, PackageParser.Package p2) {
    799                         return p1.mOverlayPriority - p2.mOverlayPriority;
    800                     }
    801                 };
    802                 Collections.sort(overlayPackages, cmp);
    803             }
    804             return overlayPackages;
    805         }
    806 
    807         final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
    808                 String targetPackageName, String targetPath) {
    809             if ("android".equals(targetPackageName)) {
    810                 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
    811                 // native AssetManager.
    812                 return null;
    813             }
    814             List<PackageParser.Package> overlayPackages =
    815                     getStaticOverlayPackagesLocked(allPackages, targetPackageName);
    816             if (overlayPackages == null || overlayPackages.isEmpty()) {
    817                 return null;
    818             }
    819             List<String> overlayPathList = null;
    820             for (PackageParser.Package overlayPackage : overlayPackages) {
    821                 if (targetPath == null) {
    822                     if (overlayPathList == null) {
    823                         overlayPathList = new ArrayList<String>();
    824                     }
    825                     overlayPathList.add(overlayPackage.baseCodePath);
    826                     continue;
    827                 }
    828 
    829                 try {
    830                     // Creates idmaps for system to parse correctly the Android manifest of the
    831                     // target package.
    832                     //
    833                     // OverlayManagerService will update each of them with a correct gid from its
    834                     // target package app id.
    835                     mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
    836                             UserHandle.getSharedAppGid(
    837                                     UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
    838                     if (overlayPathList == null) {
    839                         overlayPathList = new ArrayList<String>();
    840                     }
    841                     overlayPathList.add(overlayPackage.baseCodePath);
    842                 } catch (InstallerException e) {
    843                     Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
    844                             overlayPackage.baseCodePath);
    845                 }
    846             }
    847             return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
    848         }
    849 
    850         String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
    851             synchronized (mPackages) {
    852                 return getStaticOverlayPathsLocked(
    853                         mPackages.values(), targetPackageName, targetPath);
    854             }
    855         }
    856 
    857         @Override public final String[] getOverlayApks(String targetPackageName) {
    858             return getStaticOverlayPaths(targetPackageName, null);
    859         }
    860 
    861         @Override public final String[] getOverlayPaths(String targetPackageName,
    862                 String targetPath) {
    863             return getStaticOverlayPaths(targetPackageName, targetPath);
    864         }
    865     };
    866 
    867     class ParallelPackageParserCallback extends PackageParserCallback {
    868         List<PackageParser.Package> mOverlayPackages = null;
    869 
    870         void findStaticOverlayPackages() {
    871             synchronized (mPackages) {
    872                 for (PackageParser.Package p : mPackages.values()) {
    873                     if (p.mIsStaticOverlay) {
    874                         if (mOverlayPackages == null) {
    875                             mOverlayPackages = new ArrayList<PackageParser.Package>();
    876                         }
    877                         mOverlayPackages.add(p);
    878                     }
    879                 }
    880             }
    881         }
    882 
    883         @Override
    884         synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
    885             // We can trust mOverlayPackages without holding mPackages because package uninstall
    886             // can't happen while running parallel parsing.
    887             // Moreover holding mPackages on each parsing thread causes dead-lock.
    888             return mOverlayPackages == null ? null :
    889                     getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
    890         }
    891     }
    892 
    893     final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
    894     final ParallelPackageParserCallback mParallelPackageParserCallback =
    895             new ParallelPackageParserCallback();
    896 
    897     public static final class SharedLibraryEntry {
    898         public final @Nullable String path;
    899         public final @Nullable String apk;
    900         public final @NonNull SharedLibraryInfo info;
    901 
    902         SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
    903                 String declaringPackageName, int declaringPackageVersionCode) {
    904             path = _path;
    905             apk = _apk;
    906             info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
    907                     declaringPackageName, declaringPackageVersionCode), null);
    908         }
    909     }
    910 
    911     // Currently known shared libraries.
    912     final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
    913     final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
    914             new ArrayMap<>();
    915 
    916     // All available activities, for your resolving pleasure.
    917     final ActivityIntentResolver mActivities =
    918             new ActivityIntentResolver();
    919 
    920     // All available receivers, for your resolving pleasure.
    921     final ActivityIntentResolver mReceivers =
    922             new ActivityIntentResolver();
    923 
    924     // All available services, for your resolving pleasure.
    925     final ServiceIntentResolver mServices = new ServiceIntentResolver();
    926 
    927     // All available providers, for your resolving pleasure.
    928     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
    929 
    930     // Mapping from provider base names (first directory in content URI codePath)
    931     // to the provider information.
    932     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
    933             new ArrayMap<String, PackageParser.Provider>();
    934 
    935     // Mapping from instrumentation class names to info about them.
    936     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
    937             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
    938 
    939     // Mapping from permission names to info about them.
    940     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
    941             new ArrayMap<String, PackageParser.PermissionGroup>();
    942 
    943     // Packages whose data we have transfered into another package, thus
    944     // should no longer exist.
    945     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
    946 
    947     // Broadcast actions that are only available to the system.
    948     @GuardedBy("mProtectedBroadcasts")
    949     final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
    950 
    951     /** List of packages waiting for verification. */
    952     final SparseArray<PackageVerificationState> mPendingVerification
    953             = new SparseArray<PackageVerificationState>();
    954 
    955     /** Set of packages associated with each app op permission. */
    956     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
    957 
    958     final PackageInstallerService mInstallerService;
    959 
    960     private final PackageDexOptimizer mPackageDexOptimizer;
    961     // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
    962     // is used by other apps).
    963     private final DexManager mDexManager;
    964 
    965     private AtomicInteger mNextMoveId = new AtomicInteger();
    966     private final MoveCallbacks mMoveCallbacks;
    967 
    968     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
    969 
    970     // Cache of users who need badging.
    971     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
    972 
    973     /** Token for keys in mPendingVerification. */
    974     private int mPendingVerificationToken = 0;
    975 
    976     volatile boolean mSystemReady;
    977     volatile boolean mSafeMode;
    978     volatile boolean mHasSystemUidErrors;
    979     private volatile boolean mEphemeralAppsDisabled;
    980 
    981     ApplicationInfo mAndroidApplication;
    982     final ActivityInfo mResolveActivity = new ActivityInfo();
    983     final ResolveInfo mResolveInfo = new ResolveInfo();
    984     ComponentName mResolveComponentName;
    985     PackageParser.Package mPlatformPackage;
    986     ComponentName mCustomResolverComponentName;
    987 
    988     boolean mResolverReplaced = false;
    989 
    990     private final @Nullable ComponentName mIntentFilterVerifierComponent;
    991     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
    992 
    993     private int mIntentFilterVerificationToken = 0;
    994 
    995     /** The service connection to the ephemeral resolver */
    996     final EphemeralResolverConnection mInstantAppResolverConnection;
    997     /** Component used to show resolver settings for Instant Apps */
    998     final ComponentName mInstantAppResolverSettingsComponent;
    999 
   1000     /** Activity used to install instant applications */
   1001     ActivityInfo mInstantAppInstallerActivity;
   1002     final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
   1003 
   1004     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
   1005             = new SparseArray<IntentFilterVerificationState>();
   1006 
   1007     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
   1008 
   1009     // List of packages names to keep cached, even if they are uninstalled for all users
   1010     private List<String> mKeepUninstalledPackages;
   1011 
   1012     private UserManagerInternal mUserManagerInternal;
   1013 
   1014     private DeviceIdleController.LocalService mDeviceIdleController;
   1015 
   1016     private File mCacheDir;
   1017 
   1018     private ArraySet<String> mPrivappPermissionsViolations;
   1019 
   1020     private Future<?> mPrepareAppDataFuture;
   1021 
   1022     private static class IFVerificationParams {
   1023         PackageParser.Package pkg;
   1024         boolean replacing;
   1025         int userId;
   1026         int verifierUid;
   1027 
   1028         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
   1029                 int _userId, int _verifierUid) {
   1030             pkg = _pkg;
   1031             replacing = _replacing;
   1032             userId = _userId;
   1033             replacing = _replacing;
   1034             verifierUid = _verifierUid;
   1035         }
   1036     }
   1037 
   1038     private interface IntentFilterVerifier<T extends IntentFilter> {
   1039         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
   1040                                                T filter, String packageName);
   1041         void startVerifications(int userId);
   1042         void receiveVerificationResponse(int verificationId);
   1043     }
   1044 
   1045     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
   1046         private Context mContext;
   1047         private ComponentName mIntentFilterVerifierComponent;
   1048         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
   1049 
   1050         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
   1051             mContext = context;
   1052             mIntentFilterVerifierComponent = verifierComponent;
   1053         }
   1054 
   1055         private String getDefaultScheme() {
   1056             return IntentFilter.SCHEME_HTTPS;
   1057         }
   1058 
   1059         @Override
   1060         public void startVerifications(int userId) {
   1061             // Launch verifications requests
   1062             int count = mCurrentIntentFilterVerifications.size();
   1063             for (int n=0; n<count; n++) {
   1064                 int verificationId = mCurrentIntentFilterVerifications.get(n);
   1065                 final IntentFilterVerificationState ivs =
   1066                         mIntentFilterVerificationStates.get(verificationId);
   1067 
   1068                 String packageName = ivs.getPackageName();
   1069 
   1070                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
   1071                 final int filterCount = filters.size();
   1072                 ArraySet<String> domainsSet = new ArraySet<>();
   1073                 for (int m=0; m<filterCount; m++) {
   1074                     PackageParser.ActivityIntentInfo filter = filters.get(m);
   1075                     domainsSet.addAll(filter.getHostsList());
   1076                 }
   1077                 synchronized (mPackages) {
   1078                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
   1079                             packageName, domainsSet) != null) {
   1080                         scheduleWriteSettingsLocked();
   1081                     }
   1082                 }
   1083                 sendVerificationRequest(verificationId, ivs);
   1084             }
   1085             mCurrentIntentFilterVerifications.clear();
   1086         }
   1087 
   1088         private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
   1089             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
   1090             verificationIntent.putExtra(
   1091                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
   1092                     verificationId);
   1093             verificationIntent.putExtra(
   1094                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
   1095                     getDefaultScheme());
   1096             verificationIntent.putExtra(
   1097                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
   1098                     ivs.getHostsString());
   1099             verificationIntent.putExtra(
   1100                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
   1101                     ivs.getPackageName());
   1102             verificationIntent.setComponent(mIntentFilterVerifierComponent);
   1103             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
   1104 
   1105             DeviceIdleController.LocalService idleController = getDeviceIdleController();
   1106             idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
   1107                     mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
   1108                     UserHandle.USER_SYSTEM, true, "intent filter verifier");
   1109 
   1110             mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
   1111             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1112                     "Sending IntentFilter verification broadcast");
   1113         }
   1114 
   1115         public void receiveVerificationResponse(int verificationId) {
   1116             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
   1117 
   1118             final boolean verified = ivs.isVerified();
   1119 
   1120             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
   1121             final int count = filters.size();
   1122             if (DEBUG_DOMAIN_VERIFICATION) {
   1123                 Slog.i(TAG, "Received verification response " + verificationId
   1124                         + " for " + count + " filters, verified=" + verified);
   1125             }
   1126             for (int n=0; n<count; n++) {
   1127                 PackageParser.ActivityIntentInfo filter = filters.get(n);
   1128                 filter.setVerified(verified);
   1129 
   1130                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
   1131                         + " verified with result:" + verified + " and hosts:"
   1132                         + ivs.getHostsString());
   1133             }
   1134 
   1135             mIntentFilterVerificationStates.remove(verificationId);
   1136 
   1137             final String packageName = ivs.getPackageName();
   1138             IntentFilterVerificationInfo ivi = null;
   1139 
   1140             synchronized (mPackages) {
   1141                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
   1142             }
   1143             if (ivi == null) {
   1144                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
   1145                         + verificationId + " packageName:" + packageName);
   1146                 return;
   1147             }
   1148             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1149                     "Updating IntentFilterVerificationInfo for package " + packageName
   1150                             +" verificationId:" + verificationId);
   1151 
   1152             synchronized (mPackages) {
   1153                 if (verified) {
   1154                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
   1155                 } else {
   1156                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
   1157                 }
   1158                 scheduleWriteSettingsLocked();
   1159 
   1160                 final int userId = ivs.getUserId();
   1161                 if (userId != UserHandle.USER_ALL) {
   1162                     final int userStatus =
   1163                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
   1164 
   1165                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
   1166                     boolean needUpdate = false;
   1167 
   1168                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
   1169                     // already been set by the User thru the Disambiguation dialog
   1170                     switch (userStatus) {
   1171                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
   1172                             if (verified) {
   1173                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
   1174                             } else {
   1175                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
   1176                             }
   1177                             needUpdate = true;
   1178                             break;
   1179 
   1180                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
   1181                             if (verified) {
   1182                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
   1183                                 needUpdate = true;
   1184                             }
   1185                             break;
   1186 
   1187                         default:
   1188                             // Nothing to do
   1189                     }
   1190 
   1191                     if (needUpdate) {
   1192                         mSettings.updateIntentFilterVerificationStatusLPw(
   1193                                 packageName, updatedStatus, userId);
   1194                         scheduleWritePackageRestrictionsLocked(userId);
   1195                     }
   1196                 }
   1197             }
   1198         }
   1199 
   1200         @Override
   1201         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
   1202                     ActivityIntentInfo filter, String packageName) {
   1203             if (!hasValidDomains(filter)) {
   1204                 return false;
   1205             }
   1206             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
   1207             if (ivs == null) {
   1208                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
   1209                         packageName);
   1210             }
   1211             if (DEBUG_DOMAIN_VERIFICATION) {
   1212                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
   1213             }
   1214             ivs.addFilter(filter);
   1215             return true;
   1216         }
   1217 
   1218         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
   1219                 int userId, int verificationId, String packageName) {
   1220             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
   1221                     verifierUid, userId, packageName);
   1222             ivs.setPendingState();
   1223             synchronized (mPackages) {
   1224                 mIntentFilterVerificationStates.append(verificationId, ivs);
   1225                 mCurrentIntentFilterVerifications.add(verificationId);
   1226             }
   1227             return ivs;
   1228         }
   1229     }
   1230 
   1231     private static boolean hasValidDomains(ActivityIntentInfo filter) {
   1232         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
   1233                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
   1234                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
   1235     }
   1236 
   1237     // Set of pending broadcasts for aggregating enable/disable of components.
   1238     static class PendingPackageBroadcasts {
   1239         // for each user id, a map of <package name -> components within that package>
   1240         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
   1241 
   1242         public PendingPackageBroadcasts() {
   1243             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
   1244         }
   1245 
   1246         public ArrayList<String> get(int userId, String packageName) {
   1247             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
   1248             return packages.get(packageName);
   1249         }
   1250 
   1251         public void put(int userId, String packageName, ArrayList<String> components) {
   1252             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
   1253             packages.put(packageName, components);
   1254         }
   1255 
   1256         public void remove(int userId, String packageName) {
   1257             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
   1258             if (packages != null) {
   1259                 packages.remove(packageName);
   1260             }
   1261         }
   1262 
   1263         public void remove(int userId) {
   1264             mUidMap.remove(userId);
   1265         }
   1266 
   1267         public int userIdCount() {
   1268             return mUidMap.size();
   1269         }
   1270 
   1271         public int userIdAt(int n) {
   1272             return mUidMap.keyAt(n);
   1273         }
   1274 
   1275         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
   1276             return mUidMap.get(userId);
   1277         }
   1278 
   1279         public int size() {
   1280             // total number of pending broadcast entries across all userIds
   1281             int num = 0;
   1282             for (int i = 0; i< mUidMap.size(); i++) {
   1283                 num += mUidMap.valueAt(i).size();
   1284             }
   1285             return num;
   1286         }
   1287 
   1288         public void clear() {
   1289             mUidMap.clear();
   1290         }
   1291 
   1292         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
   1293             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
   1294             if (map == null) {
   1295                 map = new ArrayMap<String, ArrayList<String>>();
   1296                 mUidMap.put(userId, map);
   1297             }
   1298             return map;
   1299         }
   1300     }
   1301     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
   1302 
   1303     // Service Connection to remote media container service to copy
   1304     // package uri's from external media onto secure containers
   1305     // or internal storage.
   1306     private IMediaContainerService mContainerService = null;
   1307 
   1308     static final int SEND_PENDING_BROADCAST = 1;
   1309     static final int MCS_BOUND = 3;
   1310     static final int END_COPY = 4;
   1311     static final int INIT_COPY = 5;
   1312     static final int MCS_UNBIND = 6;
   1313     static final int START_CLEANING_PACKAGE = 7;
   1314     static final int FIND_INSTALL_LOC = 8;
   1315     static final int POST_INSTALL = 9;
   1316     static final int MCS_RECONNECT = 10;
   1317     static final int MCS_GIVE_UP = 11;
   1318     static final int UPDATED_MEDIA_STATUS = 12;
   1319     static final int WRITE_SETTINGS = 13;
   1320     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
   1321     static final int PACKAGE_VERIFIED = 15;
   1322     static final int CHECK_PENDING_VERIFICATION = 16;
   1323     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
   1324     static final int INTENT_FILTER_VERIFIED = 18;
   1325     static final int WRITE_PACKAGE_LIST = 19;
   1326     static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
   1327 
   1328     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
   1329 
   1330     // Delay time in millisecs
   1331     static final int BROADCAST_DELAY = 10 * 1000;
   1332 
   1333     private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
   1334             2 * 60 * 60 * 1000L; /* two hours */
   1335 
   1336     static UserManagerService sUserManager;
   1337 
   1338     // Stores a list of users whose package restrictions file needs to be updated
   1339     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
   1340 
   1341     final private DefaultContainerConnection mDefContainerConn =
   1342             new DefaultContainerConnection();
   1343     class DefaultContainerConnection implements ServiceConnection {
   1344         public void onServiceConnected(ComponentName name, IBinder service) {
   1345             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
   1346             final IMediaContainerService imcs = IMediaContainerService.Stub
   1347                     .asInterface(Binder.allowBlocking(service));
   1348             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
   1349         }
   1350 
   1351         public void onServiceDisconnected(ComponentName name) {
   1352             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
   1353         }
   1354     }
   1355 
   1356     // Recordkeeping of restore-after-install operations that are currently in flight
   1357     // between the Package Manager and the Backup Manager
   1358     static class PostInstallData {
   1359         public InstallArgs args;
   1360         public PackageInstalledInfo res;
   1361 
   1362         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
   1363             args = _a;
   1364             res = _r;
   1365         }
   1366     }
   1367 
   1368     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
   1369     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
   1370 
   1371     // XML tags for backup/restore of various bits of state
   1372     private static final String TAG_PREFERRED_BACKUP = "pa";
   1373     private static final String TAG_DEFAULT_APPS = "da";
   1374     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
   1375 
   1376     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
   1377     private static final String TAG_ALL_GRANTS = "rt-grants";
   1378     private static final String TAG_GRANT = "grant";
   1379     private static final String ATTR_PACKAGE_NAME = "pkg";
   1380 
   1381     private static final String TAG_PERMISSION = "perm";
   1382     private static final String ATTR_PERMISSION_NAME = "name";
   1383     private static final String ATTR_IS_GRANTED = "g";
   1384     private static final String ATTR_USER_SET = "set";
   1385     private static final String ATTR_USER_FIXED = "fixed";
   1386     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
   1387 
   1388     // System/policy permission grants are not backed up
   1389     private static final int SYSTEM_RUNTIME_GRANT_MASK =
   1390             FLAG_PERMISSION_POLICY_FIXED
   1391             | FLAG_PERMISSION_SYSTEM_FIXED
   1392             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
   1393 
   1394     // And we back up these user-adjusted states
   1395     private static final int USER_RUNTIME_GRANT_MASK =
   1396             FLAG_PERMISSION_USER_SET
   1397             | FLAG_PERMISSION_USER_FIXED
   1398             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
   1399 
   1400     final @Nullable String mRequiredVerifierPackage;
   1401     final @NonNull String mRequiredInstallerPackage;
   1402     final @NonNull String mRequiredUninstallerPackage;
   1403     final @Nullable String mSetupWizardPackage;
   1404     final @Nullable String mStorageManagerPackage;
   1405     final @NonNull String mServicesSystemSharedLibraryPackageName;
   1406     final @NonNull String mSharedSystemSharedLibraryPackageName;
   1407 
   1408     final boolean mPermissionReviewRequired;
   1409 
   1410     private final PackageUsage mPackageUsage = new PackageUsage();
   1411     private final CompilerStats mCompilerStats = new CompilerStats();
   1412 
   1413     class PackageHandler extends Handler {
   1414         private boolean mBound = false;
   1415         final ArrayList<HandlerParams> mPendingInstalls =
   1416             new ArrayList<HandlerParams>();
   1417 
   1418         private boolean connectToService() {
   1419             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
   1420                     " DefaultContainerService");
   1421             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
   1422             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1423             if (mContext.bindServiceAsUser(service, mDefContainerConn,
   1424                     Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
   1425                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1426                 mBound = true;
   1427                 return true;
   1428             }
   1429             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1430             return false;
   1431         }
   1432 
   1433         private void disconnectService() {
   1434             mContainerService = null;
   1435             mBound = false;
   1436             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1437             mContext.unbindService(mDefContainerConn);
   1438             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1439         }
   1440 
   1441         PackageHandler(Looper looper) {
   1442             super(looper);
   1443         }
   1444 
   1445         public void handleMessage(Message msg) {
   1446             try {
   1447                 doHandleMessage(msg);
   1448             } finally {
   1449                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1450             }
   1451         }
   1452 
   1453         void doHandleMessage(Message msg) {
   1454             switch (msg.what) {
   1455                 case INIT_COPY: {
   1456                     HandlerParams params = (HandlerParams) msg.obj;
   1457                     int idx = mPendingInstalls.size();
   1458                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
   1459                     // If a bind was already initiated we dont really
   1460                     // need to do anything. The pending install
   1461                     // will be processed later on.
   1462                     if (!mBound) {
   1463                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
   1464                                 System.identityHashCode(mHandler));
   1465                         // If this is the only one pending we might
   1466                         // have to bind to the service again.
   1467                         if (!connectToService()) {
   1468                             Slog.e(TAG, "Failed to bind to media container service");
   1469                             params.serviceError();
   1470                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
   1471                                     System.identityHashCode(mHandler));
   1472                             if (params.traceMethod != null) {
   1473                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
   1474                                         params.traceCookie);
   1475                             }
   1476                             return;
   1477                         } else {
   1478                             // Once we bind to the service, the first
   1479                             // pending request will be processed.
   1480                             mPendingInstalls.add(idx, params);
   1481                         }
   1482                     } else {
   1483                         mPendingInstalls.add(idx, params);
   1484                         // Already bound to the service. Just make
   1485                         // sure we trigger off processing the first request.
   1486                         if (idx == 0) {
   1487                             mHandler.sendEmptyMessage(MCS_BOUND);
   1488                         }
   1489                     }
   1490                     break;
   1491                 }
   1492                 case MCS_BOUND: {
   1493                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
   1494                     if (msg.obj != null) {
   1495                         mContainerService = (IMediaContainerService) msg.obj;
   1496                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
   1497                                 System.identityHashCode(mHandler));
   1498                     }
   1499                     if (mContainerService == null) {
   1500                         if (!mBound) {
   1501                             // Something seriously wrong since we are not bound and we are not
   1502                             // waiting for connection. Bail out.
   1503                             Slog.e(TAG, "Cannot bind to media container service");
   1504                             for (HandlerParams params : mPendingInstalls) {
   1505                                 // Indicate service bind error
   1506                                 params.serviceError();
   1507                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1508                                         System.identityHashCode(params));
   1509                                 if (params.traceMethod != null) {
   1510                                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
   1511                                             params.traceMethod, params.traceCookie);
   1512                                 }
   1513                                 return;
   1514                             }
   1515                             mPendingInstalls.clear();
   1516                         } else {
   1517                             Slog.w(TAG, "Waiting to connect to media container service");
   1518                         }
   1519                     } else if (mPendingInstalls.size() > 0) {
   1520                         HandlerParams params = mPendingInstalls.get(0);
   1521                         if (params != null) {
   1522                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1523                                     System.identityHashCode(params));
   1524                             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
   1525                             if (params.startCopy()) {
   1526                                 // We are done...  look for more work or to
   1527                                 // go idle.
   1528                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
   1529                                         "Checking for more work or unbind...");
   1530                                 // Delete pending install
   1531                                 if (mPendingInstalls.size() > 0) {
   1532                                     mPendingInstalls.remove(0);
   1533                                 }
   1534                                 if (mPendingInstalls.size() == 0) {
   1535                                     if (mBound) {
   1536                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
   1537                                                 "Posting delayed MCS_UNBIND");
   1538                                         removeMessages(MCS_UNBIND);
   1539                                         Message ubmsg = obtainMessage(MCS_UNBIND);
   1540                                         // Unbind after a little delay, to avoid
   1541                                         // continual thrashing.
   1542                                         sendMessageDelayed(ubmsg, 10000);
   1543                                     }
   1544                                 } else {
   1545                                     // There are more pending requests in queue.
   1546                                     // Just post MCS_BOUND message to trigger processing
   1547                                     // of next pending install.
   1548                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
   1549                                             "Posting MCS_BOUND for next work");
   1550                                     mHandler.sendEmptyMessage(MCS_BOUND);
   1551                                 }
   1552                             }
   1553                             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   1554                         }
   1555                     } else {
   1556                         // Should never happen ideally.
   1557                         Slog.w(TAG, "Empty queue");
   1558                     }
   1559                     break;
   1560                 }
   1561                 case MCS_RECONNECT: {
   1562                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
   1563                     if (mPendingInstalls.size() > 0) {
   1564                         if (mBound) {
   1565                             disconnectService();
   1566                         }
   1567                         if (!connectToService()) {
   1568                             Slog.e(TAG, "Failed to bind to media container service");
   1569                             for (HandlerParams params : mPendingInstalls) {
   1570                                 // Indicate service bind error
   1571                                 params.serviceError();
   1572                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1573                                         System.identityHashCode(params));
   1574                             }
   1575                             mPendingInstalls.clear();
   1576                         }
   1577                     }
   1578                     break;
   1579                 }
   1580                 case MCS_UNBIND: {
   1581                     // If there is no actual work left, then time to unbind.
   1582                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
   1583 
   1584                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
   1585                         if (mBound) {
   1586                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
   1587 
   1588                             disconnectService();
   1589                         }
   1590                     } else if (mPendingInstalls.size() > 0) {
   1591                         // There are more pending requests in queue.
   1592                         // Just post MCS_BOUND message to trigger processing
   1593                         // of next pending install.
   1594                         mHandler.sendEmptyMessage(MCS_BOUND);
   1595                     }
   1596 
   1597                     break;
   1598                 }
   1599                 case MCS_GIVE_UP: {
   1600                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
   1601                     HandlerParams params = mPendingInstalls.remove(0);
   1602                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1603                             System.identityHashCode(params));
   1604                     break;
   1605                 }
   1606                 case SEND_PENDING_BROADCAST: {
   1607                     String packages[];
   1608                     ArrayList<String> components[];
   1609                     int size = 0;
   1610                     int uids[];
   1611                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1612                     synchronized (mPackages) {
   1613                         if (mPendingBroadcasts == null) {
   1614                             return;
   1615                         }
   1616                         size = mPendingBroadcasts.size();
   1617                         if (size <= 0) {
   1618                             // Nothing to be done. Just return
   1619                             return;
   1620                         }
   1621                         packages = new String[size];
   1622                         components = new ArrayList[size];
   1623                         uids = new int[size];
   1624                         int i = 0;  // filling out the above arrays
   1625 
   1626                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
   1627                             int packageUserId = mPendingBroadcasts.userIdAt(n);
   1628                             Iterator<Map.Entry<String, ArrayList<String>>> it
   1629                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
   1630                                             .entrySet().iterator();
   1631                             while (it.hasNext() && i < size) {
   1632                                 Map.Entry<String, ArrayList<String>> ent = it.next();
   1633                                 packages[i] = ent.getKey();
   1634                                 components[i] = ent.getValue();
   1635                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
   1636                                 uids[i] = (ps != null)
   1637                                         ? UserHandle.getUid(packageUserId, ps.appId)
   1638                                         : -1;
   1639                                 i++;
   1640                             }
   1641                         }
   1642                         size = i;
   1643                         mPendingBroadcasts.clear();
   1644                     }
   1645                     // Send broadcasts
   1646                     for (int i = 0; i < size; i++) {
   1647                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
   1648                     }
   1649                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1650                     break;
   1651                 }
   1652                 case START_CLEANING_PACKAGE: {
   1653                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1654                     final String packageName = (String)msg.obj;
   1655                     final int userId = msg.arg1;
   1656                     final boolean andCode = msg.arg2 != 0;
   1657                     synchronized (mPackages) {
   1658                         if (userId == UserHandle.USER_ALL) {
   1659                             int[] users = sUserManager.getUserIds();
   1660                             for (int user : users) {
   1661                                 mSettings.addPackageToCleanLPw(
   1662                                         new PackageCleanItem(user, packageName, andCode));
   1663                             }
   1664                         } else {
   1665                             mSettings.addPackageToCleanLPw(
   1666                                     new PackageCleanItem(userId, packageName, andCode));
   1667                         }
   1668                     }
   1669                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1670                     startCleaningPackages();
   1671                 } break;
   1672                 case POST_INSTALL: {
   1673                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
   1674 
   1675                     PostInstallData data = mRunningInstalls.get(msg.arg1);
   1676                     final boolean didRestore = (msg.arg2 != 0);
   1677                     mRunningInstalls.delete(msg.arg1);
   1678 
   1679                     if (data != null) {
   1680                         InstallArgs args = data.args;
   1681                         PackageInstalledInfo parentRes = data.res;
   1682 
   1683                         final boolean grantPermissions = (args.installFlags
   1684                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
   1685                         final boolean killApp = (args.installFlags
   1686                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
   1687                         final boolean virtualPreload = ((args.installFlags
   1688                                 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
   1689                         final String[] grantedPermissions = args.installGrantPermissions;
   1690 
   1691                         // Handle the parent package
   1692                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
   1693                                 virtualPreload, grantedPermissions, didRestore,
   1694                                 args.installerPackageName, args.observer);
   1695 
   1696                         // Handle the child packages
   1697                         final int childCount = (parentRes.addedChildPackages != null)
   1698                                 ? parentRes.addedChildPackages.size() : 0;
   1699                         for (int i = 0; i < childCount; i++) {
   1700                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
   1701                             handlePackagePostInstall(childRes, grantPermissions, killApp,
   1702                                     virtualPreload, grantedPermissions, false /*didRestore*/,
   1703                                     args.installerPackageName, args.observer);
   1704                         }
   1705 
   1706                         // Log tracing if needed
   1707                         if (args.traceMethod != null) {
   1708                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
   1709                                     args.traceCookie);
   1710                         }
   1711                     } else {
   1712                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
   1713                     }
   1714 
   1715                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
   1716                 } break;
   1717                 case UPDATED_MEDIA_STATUS: {
   1718                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
   1719                     boolean reportStatus = msg.arg1 == 1;
   1720                     boolean doGc = msg.arg2 == 1;
   1721                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
   1722                     if (doGc) {
   1723                         // Force a gc to clear up stale containers.
   1724                         Runtime.getRuntime().gc();
   1725                     }
   1726                     if (msg.obj != null) {
   1727                         @SuppressWarnings("unchecked")
   1728                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
   1729                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
   1730                         // Unload containers
   1731                         unloadAllContainers(args);
   1732                     }
   1733                     if (reportStatus) {
   1734                         try {
   1735                             if (DEBUG_SD_INSTALL) Log.i(TAG,
   1736                                     "Invoking StorageManagerService call back");
   1737                             PackageHelper.getStorageManager().finishMediaUpdate();
   1738                         } catch (RemoteException e) {
   1739                             Log.e(TAG, "StorageManagerService not running?");
   1740                         }
   1741                     }
   1742                 } break;
   1743                 case WRITE_SETTINGS: {
   1744                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1745                     synchronized (mPackages) {
   1746                         removeMessages(WRITE_SETTINGS);
   1747                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   1748                         mSettings.writeLPr();
   1749                         mDirtyUsers.clear();
   1750                     }
   1751                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1752                 } break;
   1753                 case WRITE_PACKAGE_RESTRICTIONS: {
   1754                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1755                     synchronized (mPackages) {
   1756                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   1757                         for (int userId : mDirtyUsers) {
   1758                             mSettings.writePackageRestrictionsLPr(userId);
   1759                         }
   1760                         mDirtyUsers.clear();
   1761                     }
   1762                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1763                 } break;
   1764                 case WRITE_PACKAGE_LIST: {
   1765                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1766                     synchronized (mPackages) {
   1767                         removeMessages(WRITE_PACKAGE_LIST);
   1768                         mSettings.writePackageListLPr(msg.arg1);
   1769                     }
   1770                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1771                 } break;
   1772                 case CHECK_PENDING_VERIFICATION: {
   1773                     final int verificationId = msg.arg1;
   1774                     final PackageVerificationState state = mPendingVerification.get(verificationId);
   1775 
   1776                     if ((state != null) && !state.timeoutExtended()) {
   1777                         final InstallArgs args = state.getInstallArgs();
   1778                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
   1779 
   1780                         Slog.i(TAG, "Verification timed out for " + originUri);
   1781                         mPendingVerification.remove(verificationId);
   1782 
   1783                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   1784 
   1785                         final UserHandle user = args.getUser();
   1786                         if (getDefaultVerificationResponse(user)
   1787                                 == PackageManager.VERIFICATION_ALLOW) {
   1788                             Slog.i(TAG, "Continuing with installation of " + originUri);
   1789                             state.setVerifierResponse(Binder.getCallingUid(),
   1790                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
   1791                             broadcastPackageVerified(verificationId, originUri,
   1792                                     PackageManager.VERIFICATION_ALLOW, user);
   1793                             try {
   1794                                 ret = args.copyApk(mContainerService, true);
   1795                             } catch (RemoteException e) {
   1796                                 Slog.e(TAG, "Could not contact the ContainerService");
   1797                             }
   1798                         } else {
   1799                             broadcastPackageVerified(verificationId, originUri,
   1800                                     PackageManager.VERIFICATION_REJECT, user);
   1801                         }
   1802 
   1803                         Trace.asyncTraceEnd(
   1804                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
   1805 
   1806                         processPendingInstall(args, ret);
   1807                         mHandler.sendEmptyMessage(MCS_UNBIND);
   1808                     }
   1809                     break;
   1810                 }
   1811                 case PACKAGE_VERIFIED: {
   1812                     final int verificationId = msg.arg1;
   1813 
   1814                     final PackageVerificationState state = mPendingVerification.get(verificationId);
   1815                     if (state == null) {
   1816                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
   1817                         break;
   1818                     }
   1819 
   1820                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
   1821 
   1822                     state.setVerifierResponse(response.callerUid, response.code);
   1823 
   1824                     if (state.isVerificationComplete()) {
   1825                         mPendingVerification.remove(verificationId);
   1826 
   1827                         final InstallArgs args = state.getInstallArgs();
   1828                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
   1829 
   1830                         int ret;
   1831                         if (state.isInstallAllowed()) {
   1832                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   1833                             broadcastPackageVerified(verificationId, originUri,
   1834                                     response.code, state.getInstallArgs().getUser());
   1835                             try {
   1836                                 ret = args.copyApk(mContainerService, true);
   1837                             } catch (RemoteException e) {
   1838                                 Slog.e(TAG, "Could not contact the ContainerService");
   1839                             }
   1840                         } else {
   1841                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   1842                         }
   1843 
   1844                         Trace.asyncTraceEnd(
   1845                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
   1846 
   1847                         processPendingInstall(args, ret);
   1848                         mHandler.sendEmptyMessage(MCS_UNBIND);
   1849                     }
   1850 
   1851                     break;
   1852                 }
   1853                 case START_INTENT_FILTER_VERIFICATIONS: {
   1854                     IFVerificationParams params = (IFVerificationParams) msg.obj;
   1855                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
   1856                             params.replacing, params.pkg);
   1857                     break;
   1858                 }
   1859                 case INTENT_FILTER_VERIFIED: {
   1860                     final int verificationId = msg.arg1;
   1861 
   1862                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
   1863                             verificationId);
   1864                     if (state == null) {
   1865                         Slog.w(TAG, "Invalid IntentFilter verification token "
   1866                                 + verificationId + " received");
   1867                         break;
   1868                     }
   1869 
   1870                     final int userId = state.getUserId();
   1871 
   1872                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1873                             "Processing IntentFilter verification with token:"
   1874                             + verificationId + " and userId:" + userId);
   1875 
   1876                     final IntentFilterVerificationResponse response =
   1877                             (IntentFilterVerificationResponse) msg.obj;
   1878 
   1879                     state.setVerifierResponse(response.callerUid, response.code);
   1880 
   1881                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1882                             "IntentFilter verification with token:" + verificationId
   1883                             + " and userId:" + userId
   1884                             + " is settings verifier response with response code:"
   1885                             + response.code);
   1886 
   1887                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
   1888                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
   1889                                 + response.getFailedDomainsString());
   1890                     }
   1891 
   1892                     if (state.isVerificationComplete()) {
   1893                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
   1894                     } else {
   1895                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1896                                 "IntentFilter verification with token:" + verificationId
   1897                                 + " was not said to be complete");
   1898                     }
   1899 
   1900                     break;
   1901                 }
   1902                 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
   1903                     InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
   1904                             mInstantAppResolverConnection,
   1905                             (InstantAppRequest) msg.obj,
   1906                             mInstantAppInstallerActivity,
   1907                             mHandler);
   1908                 }
   1909             }
   1910         }
   1911     }
   1912 
   1913     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
   1914             boolean killApp, boolean virtualPreload, String[] grantedPermissions,
   1915             boolean launchedForRestore, String installerPackage,
   1916             IPackageInstallObserver2 installObserver) {
   1917         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   1918             // Send the removed broadcasts
   1919             if (res.removedInfo != null) {
   1920                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
   1921             }
   1922 
   1923             // Now that we successfully installed the package, grant runtime
   1924             // permissions if requested before broadcasting the install. Also
   1925             // for legacy apps in permission review mode we clear the permission
   1926             // review flag which is used to emulate runtime permissions for
   1927             // legacy apps.
   1928             if (grantPermissions) {
   1929                 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
   1930             }
   1931 
   1932             final boolean update = res.removedInfo != null
   1933                     && res.removedInfo.removedPackage != null;
   1934             final String installerPackageName =
   1935                     res.installerPackageName != null
   1936                             ? res.installerPackageName
   1937                             : res.removedInfo != null
   1938                                     ? res.removedInfo.installerPackageName
   1939                                     : null;
   1940 
   1941             // If this is the first time we have child packages for a disabled privileged
   1942             // app that had no children, we grant requested runtime permissions to the new
   1943             // children if the parent on the system image had them already granted.
   1944             if (res.pkg.parentPackage != null) {
   1945                 synchronized (mPackages) {
   1946                     grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
   1947                 }
   1948             }
   1949 
   1950             synchronized (mPackages) {
   1951                 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
   1952             }
   1953 
   1954             final String packageName = res.pkg.applicationInfo.packageName;
   1955 
   1956             // Determine the set of users who are adding this package for
   1957             // the first time vs. those who are seeing an update.
   1958             int[] firstUsers = EMPTY_INT_ARRAY;
   1959             int[] updateUsers = EMPTY_INT_ARRAY;
   1960             final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
   1961             final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
   1962             for (int newUser : res.newUsers) {
   1963                 if (ps.getInstantApp(newUser)) {
   1964                     continue;
   1965                 }
   1966                 if (allNewUsers) {
   1967                     firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
   1968                     continue;
   1969                 }
   1970                 boolean isNew = true;
   1971                 for (int origUser : res.origUsers) {
   1972                     if (origUser == newUser) {
   1973                         isNew = false;
   1974                         break;
   1975                     }
   1976                 }
   1977                 if (isNew) {
   1978                     firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
   1979                 } else {
   1980                     updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
   1981                 }
   1982             }
   1983 
   1984             // Send installed broadcasts if the package is not a static shared lib.
   1985             if (res.pkg.staticSharedLibName == null) {
   1986                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
   1987 
   1988                 // Send added for users that see the package for the first time
   1989                 // sendPackageAddedForNewUsers also deals with system apps
   1990                 int appId = UserHandle.getAppId(res.uid);
   1991                 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
   1992                 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
   1993                         virtualPreload /*startReceiver*/, appId, firstUsers);
   1994 
   1995                 // Send added for users that don't see the package for the first time
   1996                 Bundle extras = new Bundle(1);
   1997                 extras.putInt(Intent.EXTRA_UID, res.uid);
   1998                 if (update) {
   1999                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
   2000                 }
   2001                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
   2002                         extras, 0 /*flags*/,
   2003                         null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
   2004                 if (installerPackageName != null) {
   2005                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
   2006                             extras, 0 /*flags*/,
   2007                             installerPackageName, null /*finishedReceiver*/, updateUsers);
   2008                 }
   2009 
   2010                 // Send replaced for users that don't see the package for the first time
   2011                 if (update) {
   2012                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
   2013                             packageName, extras, 0 /*flags*/,
   2014                             null /*targetPackage*/, null /*finishedReceiver*/,
   2015                             updateUsers);
   2016                     if (installerPackageName != null) {
   2017                         sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
   2018                                 extras, 0 /*flags*/,
   2019                                 installerPackageName, null /*finishedReceiver*/, updateUsers);
   2020                     }
   2021                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
   2022                             null /*package*/, null /*extras*/, 0 /*flags*/,
   2023                             packageName /*targetPackage*/,
   2024                             null /*finishedReceiver*/, updateUsers);
   2025                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
   2026                     // First-install and we did a restore, so we're responsible for the
   2027                     // first-launch broadcast.
   2028                     if (DEBUG_BACKUP) {
   2029                         Slog.i(TAG, "Post-restore of " + packageName
   2030                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
   2031                     }
   2032                     sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
   2033                 }
   2034 
   2035                 // Send broadcast package appeared if forward locked/external for all users
   2036                 // treat asec-hosted packages like removable media on upgrade
   2037                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
   2038                     if (DEBUG_INSTALL) {
   2039                         Slog.i(TAG, "upgrading pkg " + res.pkg
   2040                                 + " is ASEC-hosted -> AVAILABLE");
   2041                     }
   2042                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
   2043                     ArrayList<String> pkgList = new ArrayList<>(1);
   2044                     pkgList.add(packageName);
   2045                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
   2046                 }
   2047             }
   2048 
   2049             // Work that needs to happen on first install within each user
   2050             if (firstUsers != null && firstUsers.length > 0) {
   2051                 synchronized (mPackages) {
   2052                     for (int userId : firstUsers) {
   2053                         // If this app is a browser and it's newly-installed for some
   2054                         // users, clear any default-browser state in those users. The
   2055                         // app's nature doesn't depend on the user, so we can just check
   2056                         // its browser nature in any user and generalize.
   2057                         if (packageIsBrowser(packageName, userId)) {
   2058                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
   2059                         }
   2060 
   2061                         // We may also need to apply pending (restored) runtime
   2062                         // permission grants within these users.
   2063                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
   2064                     }
   2065                 }
   2066             }
   2067 
   2068             // Log current value of "unknown sources" setting
   2069             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
   2070                     getUnknownSourcesSettings());
   2071 
   2072             // Remove the replaced package's older resources safely now
   2073             // We delete after a gc for applications  on sdcard.
   2074             if (res.removedInfo != null && res.removedInfo.args != null) {
   2075                 Runtime.getRuntime().gc();
   2076                 synchronized (mInstallLock) {
   2077                     res.removedInfo.args.doPostDeleteLI(true);
   2078                 }
   2079             } else {
   2080                 // Force a gc to clear up things. Ask for a background one, it's fine to go on
   2081                 // and not block here.
   2082                 VMRuntime.getRuntime().requestConcurrentGC();
   2083             }
   2084 
   2085             // Notify DexManager that the package was installed for new users.
   2086             // The updated users should already be indexed and the package code paths
   2087             // should not change.
   2088             // Don't notify the manager for ephemeral apps as they are not expected to
   2089             // survive long enough to benefit of background optimizations.
   2090             for (int userId : firstUsers) {
   2091                 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
   2092                 // There's a race currently where some install events may interleave with an uninstall.
   2093                 // This can lead to package info being null (b/36642664).
   2094                 if (info != null) {
   2095                     mDexManager.notifyPackageInstalled(info, userId);
   2096                 }
   2097             }
   2098         }
   2099 
   2100         // If someone is watching installs - notify them
   2101         if (installObserver != null) {
   2102             try {
   2103                 Bundle extras = extrasForInstallResult(res);
   2104                 installObserver.onPackageInstalled(res.name, res.returnCode,
   2105                         res.returnMsg, extras);
   2106             } catch (RemoteException e) {
   2107                 Slog.i(TAG, "Observer no longer exists.");
   2108             }
   2109         }
   2110     }
   2111 
   2112     private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
   2113             PackageParser.Package pkg) {
   2114         if (pkg.parentPackage == null) {
   2115             return;
   2116         }
   2117         if (pkg.requestedPermissions == null) {
   2118             return;
   2119         }
   2120         final PackageSetting disabledSysParentPs = mSettings
   2121                 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
   2122         if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
   2123                 || !disabledSysParentPs.isPrivileged()
   2124                 || (disabledSysParentPs.childPackageNames != null
   2125                         && !disabledSysParentPs.childPackageNames.isEmpty())) {
   2126             return;
   2127         }
   2128         final int[] allUserIds = sUserManager.getUserIds();
   2129         final int permCount = pkg.requestedPermissions.size();
   2130         for (int i = 0; i < permCount; i++) {
   2131             String permission = pkg.requestedPermissions.get(i);
   2132             BasePermission bp = mSettings.mPermissions.get(permission);
   2133             if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
   2134                 continue;
   2135             }
   2136             for (int userId : allUserIds) {
   2137                 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
   2138                         permission, userId)) {
   2139                     grantRuntimePermission(pkg.packageName, permission, userId);
   2140                 }
   2141             }
   2142         }
   2143     }
   2144 
   2145     private StorageEventListener mStorageListener = new StorageEventListener() {
   2146         @Override
   2147         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
   2148             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
   2149                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
   2150                     final String volumeUuid = vol.getFsUuid();
   2151 
   2152                     // Clean up any users or apps that were removed or recreated
   2153                     // while this volume was missing
   2154                     sUserManager.reconcileUsers(volumeUuid);
   2155                     reconcileApps(volumeUuid);
   2156 
   2157                     // Clean up any install sessions that expired or were
   2158                     // cancelled while this volume was missing
   2159                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
   2160 
   2161                     loadPrivatePackages(vol);
   2162 
   2163                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
   2164                     unloadPrivatePackages(vol);
   2165                 }
   2166             }
   2167 
   2168             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
   2169                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
   2170                     updateExternalMediaStatus(true, false);
   2171                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
   2172                     updateExternalMediaStatus(false, false);
   2173                 }
   2174             }
   2175         }
   2176 
   2177         @Override
   2178         public void onVolumeForgotten(String fsUuid) {
   2179             if (TextUtils.isEmpty(fsUuid)) {
   2180                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
   2181                 return;
   2182             }
   2183 
   2184             // Remove any apps installed on the forgotten volume
   2185             synchronized (mPackages) {
   2186                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
   2187                 for (PackageSetting ps : packages) {
   2188                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
   2189                     deletePackageVersioned(new VersionedPackage(ps.name,
   2190                             PackageManager.VERSION_CODE_HIGHEST),
   2191                             new LegacyPackageDeleteObserver(null).getBinder(),
   2192                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
   2193                     // Try very hard to release any references to this package
   2194                     // so we don't risk the system server being killed due to
   2195                     // open FDs
   2196                     AttributeCache.instance().removePackage(ps.name);
   2197                 }
   2198 
   2199                 mSettings.onVolumeForgotten(fsUuid);
   2200                 mSettings.writeLPr();
   2201             }
   2202         }
   2203     };
   2204 
   2205     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
   2206             String[] grantedPermissions) {
   2207         for (int userId : userIds) {
   2208             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
   2209         }
   2210     }
   2211 
   2212     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
   2213             String[] grantedPermissions) {
   2214         PackageSetting ps = (PackageSetting) pkg.mExtras;
   2215         if (ps == null) {
   2216             return;
   2217         }
   2218 
   2219         PermissionsState permissionsState = ps.getPermissionsState();
   2220 
   2221         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
   2222                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
   2223 
   2224         final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
   2225                 >= Build.VERSION_CODES.M;
   2226 
   2227         final boolean instantApp = isInstantApp(pkg.packageName, userId);
   2228 
   2229         for (String permission : pkg.requestedPermissions) {
   2230             final BasePermission bp;
   2231             synchronized (mPackages) {
   2232                 bp = mSettings.mPermissions.get(permission);
   2233             }
   2234             if (bp != null && (bp.isRuntime() || bp.isDevelopment())
   2235                     && (!instantApp || bp.isInstant())
   2236                     && (supportsRuntimePermissions || !bp.isRuntimeOnly())
   2237                     && (grantedPermissions == null
   2238                            || ArrayUtils.contains(grantedPermissions, permission))) {
   2239                 final int flags = permissionsState.getPermissionFlags(permission, userId);
   2240                 if (supportsRuntimePermissions) {
   2241                     // Installer cannot change immutable permissions.
   2242                     if ((flags & immutableFlags) == 0) {
   2243                         grantRuntimePermission(pkg.packageName, permission, userId);
   2244                     }
   2245                 } else if (mPermissionReviewRequired) {
   2246                     // In permission review mode we clear the review flag when we
   2247                     // are asked to install the app with all permissions granted.
   2248                     if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
   2249                         updatePermissionFlags(permission, pkg.packageName,
   2250                                 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
   2251                     }
   2252                 }
   2253             }
   2254         }
   2255     }
   2256 
   2257     Bundle extrasForInstallResult(PackageInstalledInfo res) {
   2258         Bundle extras = null;
   2259         switch (res.returnCode) {
   2260             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
   2261                 extras = new Bundle();
   2262                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
   2263                         res.origPermission);
   2264                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
   2265                         res.origPackage);
   2266                 break;
   2267             }
   2268             case PackageManager.INSTALL_SUCCEEDED: {
   2269                 extras = new Bundle();
   2270                 extras.putBoolean(Intent.EXTRA_REPLACING,
   2271                         res.removedInfo != null && res.removedInfo.removedPackage != null);
   2272                 break;
   2273             }
   2274         }
   2275         return extras;
   2276     }
   2277 
   2278     void scheduleWriteSettingsLocked() {
   2279         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
   2280             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
   2281         }
   2282     }
   2283 
   2284     void scheduleWritePackageListLocked(int userId) {
   2285         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
   2286             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
   2287             msg.arg1 = userId;
   2288             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
   2289         }
   2290     }
   2291 
   2292     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
   2293         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
   2294         scheduleWritePackageRestrictionsLocked(userId);
   2295     }
   2296 
   2297     void scheduleWritePackageRestrictionsLocked(int userId) {
   2298         final int[] userIds = (userId == UserHandle.USER_ALL)
   2299                 ? sUserManager.getUserIds() : new int[]{userId};
   2300         for (int nextUserId : userIds) {
   2301             if (!sUserManager.exists(nextUserId)) return;
   2302             mDirtyUsers.add(nextUserId);
   2303             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
   2304                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
   2305             }
   2306         }
   2307     }
   2308 
   2309     public static PackageManagerService main(Context context, Installer installer,
   2310             boolean factoryTest, boolean onlyCore) {
   2311         // Self-check for initial settings.
   2312         PackageManagerServiceCompilerMapping.checkProperties();
   2313 
   2314         PackageManagerService m = new PackageManagerService(context, installer,
   2315                 factoryTest, onlyCore);
   2316         m.enableSystemUserPackages();
   2317         ServiceManager.addService("package", m);
   2318         final PackageManagerNative pmn = m.new PackageManagerNative();
   2319         ServiceManager.addService("package_native", pmn);
   2320         return m;
   2321     }
   2322 
   2323     private void enableSystemUserPackages() {
   2324         if (!UserManager.isSplitSystemUser()) {
   2325             return;
   2326         }
   2327         // For system user, enable apps based on the following conditions:
   2328         // - app is whitelisted or belong to one of these groups:
   2329         //   -- system app which has no launcher icons
   2330         //   -- system app which has INTERACT_ACROSS_USERS permission
   2331         //   -- system IME app
   2332         // - app is not in the blacklist
   2333         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
   2334         Set<String> enableApps = new ArraySet<>();
   2335         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
   2336                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
   2337                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
   2338         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
   2339         enableApps.addAll(wlApps);
   2340         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
   2341                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
   2342         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
   2343         enableApps.removeAll(blApps);
   2344         Log.i(TAG, "Applications installed for system user: " + enableApps);
   2345         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
   2346                 UserHandle.SYSTEM);
   2347         final int allAppsSize = allAps.size();
   2348         synchronized (mPackages) {
   2349             for (int i = 0; i < allAppsSize; i++) {
   2350                 String pName = allAps.get(i);
   2351                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
   2352                 // Should not happen, but we shouldn't be failing if it does
   2353                 if (pkgSetting == null) {
   2354                     continue;
   2355                 }
   2356                 boolean install = enableApps.contains(pName);
   2357                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
   2358                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
   2359                             + " for system user");
   2360                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
   2361                 }
   2362             }
   2363             scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
   2364         }
   2365     }
   2366 
   2367     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
   2368         DisplayManager displayManager = (DisplayManager) context.getSystemService(
   2369                 Context.DISPLAY_SERVICE);
   2370         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
   2371     }
   2372 
   2373     /**
   2374      * Requests that files preopted on a secondary system partition be copied to the data partition
   2375      * if possible.  Note that the actual copying of the files is accomplished by init for security
   2376      * reasons. This simply requests that the copy takes place and awaits confirmation of its
   2377      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
   2378      */
   2379     private static void requestCopyPreoptedFiles() {
   2380         final int WAIT_TIME_MS = 100;
   2381         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
   2382         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
   2383             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
   2384             // We will wait for up to 100 seconds.
   2385             final long timeStart = SystemClock.uptimeMillis();
   2386             final long timeEnd = timeStart + 100 * 1000;
   2387             long timeNow = timeStart;
   2388             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
   2389                 try {
   2390                     Thread.sleep(WAIT_TIME_MS);
   2391                 } catch (InterruptedException e) {
   2392                     // Do nothing
   2393                 }
   2394                 timeNow = SystemClock.uptimeMillis();
   2395                 if (timeNow > timeEnd) {
   2396                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
   2397                     Slog.wtf(TAG, "cppreopt did not finish!");
   2398                     break;
   2399                 }
   2400             }
   2401 
   2402             Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
   2403         }
   2404     }
   2405 
   2406     public PackageManagerService(Context context, Installer installer,
   2407             boolean factoryTest, boolean onlyCore) {
   2408         LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
   2409         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
   2410         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
   2411                 SystemClock.uptimeMillis());
   2412 
   2413         if (mSdkVersion <= 0) {
   2414             Slog.w(TAG, "**** ro.build.version.sdk not set!");
   2415         }
   2416 
   2417         mContext = context;
   2418 
   2419         mPermissionReviewRequired = context.getResources().getBoolean(
   2420                 R.bool.config_permissionReviewRequired);
   2421 
   2422         mFactoryTest = factoryTest;
   2423         mOnlyCore = onlyCore;
   2424         mMetrics = new DisplayMetrics();
   2425         mSettings = new Settings(mPackages);
   2426         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
   2427                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2428         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
   2429                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2430         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
   2431                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2432         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
   2433                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2434         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
   2435                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2436         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
   2437                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2438 
   2439         String separateProcesses = SystemProperties.get("debug.separate_processes");
   2440         if (separateProcesses != null && separateProcesses.length() > 0) {
   2441             if ("*".equals(separateProcesses)) {
   2442                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
   2443                 mSeparateProcesses = null;
   2444                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
   2445             } else {
   2446                 mDefParseFlags = 0;
   2447                 mSeparateProcesses = separateProcesses.split(",");
   2448                 Slog.w(TAG, "Running with debug.separate_processes: "
   2449                         + separateProcesses);
   2450             }
   2451         } else {
   2452             mDefParseFlags = 0;
   2453             mSeparateProcesses = null;
   2454         }
   2455 
   2456         mInstaller = installer;
   2457         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
   2458                 "*dexopt*");
   2459         mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
   2460         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
   2461 
   2462         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
   2463                 FgThread.get().getLooper());
   2464 
   2465         getDefaultDisplayMetrics(context, mMetrics);
   2466 
   2467         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
   2468         SystemConfig systemConfig = SystemConfig.getInstance();
   2469         mGlobalGids = systemConfig.getGlobalGids();
   2470         mSystemPermissions = systemConfig.getSystemPermissions();
   2471         mAvailableFeatures = systemConfig.getAvailableFeatures();
   2472         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   2473 
   2474         mProtectedPackages = new ProtectedPackages(mContext);
   2475 
   2476         synchronized (mInstallLock) {
   2477         // writer
   2478         synchronized (mPackages) {
   2479             mHandlerThread = new ServiceThread(TAG,
   2480                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
   2481             mHandlerThread.start();
   2482             mHandler = new PackageHandler(mHandlerThread.getLooper());
   2483             mProcessLoggingHandler = new ProcessLoggingHandler();
   2484             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
   2485 
   2486             mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
   2487             mInstantAppRegistry = new InstantAppRegistry(this);
   2488 
   2489             File dataDir = Environment.getDataDirectory();
   2490             mAppInstallDir = new File(dataDir, "app");
   2491             mAppLib32InstallDir = new File(dataDir, "app-lib");
   2492             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
   2493             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
   2494             sUserManager = new UserManagerService(context, this,
   2495                     new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
   2496 
   2497             // Propagate permission configuration in to package manager.
   2498             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
   2499                     = systemConfig.getPermissions();
   2500             for (int i=0; i<permConfig.size(); i++) {
   2501                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
   2502                 BasePermission bp = mSettings.mPermissions.get(perm.name);
   2503                 if (bp == null) {
   2504                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
   2505                     mSettings.mPermissions.put(perm.name, bp);
   2506                 }
   2507                 if (perm.gids != null) {
   2508                     bp.setGids(perm.gids, perm.perUser);
   2509                 }
   2510             }
   2511 
   2512             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
   2513             final int builtInLibCount = libConfig.size();
   2514             for (int i = 0; i < builtInLibCount; i++) {
   2515                 String name = libConfig.keyAt(i);
   2516                 String path = libConfig.valueAt(i);
   2517                 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
   2518                         SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
   2519             }
   2520 
   2521             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
   2522 
   2523             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
   2524             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
   2525             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   2526 
   2527             // Clean up orphaned packages for which the code path doesn't exist
   2528             // and they are an update to a system app - caused by bug/32321269
   2529             final int packageSettingCount = mSettings.mPackages.size();
   2530             for (int i = packageSettingCount - 1; i >= 0; i--) {
   2531                 PackageSetting ps = mSettings.mPackages.valueAt(i);
   2532                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
   2533                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
   2534                     mSettings.mPackages.removeAt(i);
   2535                     mSettings.enableSystemPackageLPw(ps.name);
   2536                 }
   2537             }
   2538 
   2539             if (mFirstBoot) {
   2540                 requestCopyPreoptedFiles();
   2541             }
   2542 
   2543             String customResolverActivity = Resources.getSystem().getString(
   2544                     R.string.config_customResolverActivity);
   2545             if (TextUtils.isEmpty(customResolverActivity)) {
   2546                 customResolverActivity = null;
   2547             } else {
   2548                 mCustomResolverComponentName = ComponentName.unflattenFromString(
   2549                         customResolverActivity);
   2550             }
   2551 
   2552             long startTime = SystemClock.uptimeMillis();
   2553 
   2554             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
   2555                     startTime);
   2556 
   2557             final String bootClassPath = System.getenv("BOOTCLASSPATH");
   2558             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
   2559 
   2560             if (bootClassPath == null) {
   2561                 Slog.w(TAG, "No BOOTCLASSPATH found!");
   2562             }
   2563 
   2564             if (systemServerClassPath == null) {
   2565                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
   2566             }
   2567 
   2568             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
   2569 
   2570             final VersionInfo ver = mSettings.getInternalVersion();
   2571             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
   2572             if (mIsUpgrade) {
   2573                 logCriticalInfo(Log.INFO,
   2574                         "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
   2575             }
   2576 
   2577             // when upgrading from pre-M, promote system app permissions from install to runtime
   2578             mPromoteSystemApps =
   2579                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
   2580 
   2581             // When upgrading from pre-N, we need to handle package extraction like first boot,
   2582             // as there is no profiling data available.
   2583             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
   2584 
   2585             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
   2586 
   2587             // save off the names of pre-existing system packages prior to scanning; we don't
   2588             // want to automatically grant runtime permissions for new system apps
   2589             if (mPromoteSystemApps) {
   2590                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
   2591                 while (pkgSettingIter.hasNext()) {
   2592                     PackageSetting ps = pkgSettingIter.next();
   2593                     if (isSystemApp(ps)) {
   2594                         mExistingSystemPackages.add(ps.name);
   2595                     }
   2596                 }
   2597             }
   2598 
   2599             mCacheDir = preparePackageParserCache(mIsUpgrade);
   2600 
   2601             // Set flag to monitor and not change apk file paths when
   2602             // scanning install directories.
   2603             int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
   2604 
   2605             if (mIsUpgrade || mFirstBoot) {
   2606                 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
   2607             }
   2608 
   2609             // Collect vendor overlay packages. (Do this before scanning any apps.)
   2610             // For security and version matching reason, only consider
   2611             // overlay packages if they reside in the right directory.
   2612             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
   2613                     | PackageParser.PARSE_IS_SYSTEM
   2614                     | PackageParser.PARSE_IS_SYSTEM_DIR
   2615                     | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
   2616 
   2617             mParallelPackageParserCallback.findStaticOverlayPackages();
   2618 
   2619             // Find base frameworks (resource packages without code).
   2620             scanDirTracedLI(frameworkDir, mDefParseFlags
   2621                     | PackageParser.PARSE_IS_SYSTEM
   2622                     | PackageParser.PARSE_IS_SYSTEM_DIR
   2623                     | PackageParser.PARSE_IS_PRIVILEGED,
   2624                     scanFlags | SCAN_NO_DEX, 0);
   2625 
   2626             // Collected privileged system packages.
   2627             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
   2628             scanDirTracedLI(privilegedAppDir, mDefParseFlags
   2629                     | PackageParser.PARSE_IS_SYSTEM
   2630                     | PackageParser.PARSE_IS_SYSTEM_DIR
   2631                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
   2632 
   2633             // Collect ordinary system packages.
   2634             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
   2635             scanDirTracedLI(systemAppDir, mDefParseFlags
   2636                     | PackageParser.PARSE_IS_SYSTEM
   2637                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
   2638 
   2639             // Collect all vendor packages.
   2640             File vendorAppDir = new File("/vendor/app");
   2641             try {
   2642                 vendorAppDir = vendorAppDir.getCanonicalFile();
   2643             } catch (IOException e) {
   2644                 // failed to look up canonical path, continue with original one
   2645             }
   2646             scanDirTracedLI(vendorAppDir, mDefParseFlags
   2647                     | PackageParser.PARSE_IS_SYSTEM
   2648                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
   2649 
   2650             // Collect all OEM packages.
   2651             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
   2652             scanDirTracedLI(oemAppDir, mDefParseFlags
   2653                     | PackageParser.PARSE_IS_SYSTEM
   2654                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
   2655 
   2656             // Prune any system packages that no longer exist.
   2657             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
   2658             // Stub packages must either be replaced with full versions in the /data
   2659             // partition or be disabled.
   2660             final List<String> stubSystemApps = new ArrayList<>();
   2661             if (!mOnlyCore) {
   2662                 // do this first before mucking with mPackages for the "expecting better" case
   2663                 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
   2664                 while (pkgIterator.hasNext()) {
   2665                     final PackageParser.Package pkg = pkgIterator.next();
   2666                     if (pkg.isStub) {
   2667                         stubSystemApps.add(pkg.packageName);
   2668                     }
   2669                 }
   2670 
   2671                 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
   2672                 while (psit.hasNext()) {
   2673                     PackageSetting ps = psit.next();
   2674 
   2675                     /*
   2676                      * If this is not a system app, it can't be a
   2677                      * disable system app.
   2678                      */
   2679                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
   2680                         continue;
   2681                     }
   2682 
   2683                     /*
   2684                      * If the package is scanned, it's not erased.
   2685                      */
   2686                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
   2687                     if (scannedPkg != null) {
   2688                         /*
   2689                          * If the system app is both scanned and in the
   2690                          * disabled packages list, then it must have been
   2691                          * added via OTA. Remove it from the currently
   2692                          * scanned package so the previously user-installed
   2693                          * application can be scanned.
   2694                          */
   2695                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
   2696                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
   2697                                     + ps.name + "; removing system app.  Last known codePath="
   2698                                     + ps.codePathString + ", installStatus=" + ps.installStatus
   2699                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
   2700                                     + scannedPkg.mVersionCode);
   2701                             removePackageLI(scannedPkg, true);
   2702                             mExpectingBetter.put(ps.name, ps.codePath);
   2703                         }
   2704 
   2705                         continue;
   2706                     }
   2707 
   2708                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
   2709                         psit.remove();
   2710                         logCriticalInfo(Log.WARN, "System package " + ps.name
   2711                                 + " no longer exists; it's data will be wiped");
   2712                         // Actual deletion of code and data will be handled by later
   2713                         // reconciliation step
   2714                     } else {
   2715                         // we still have a disabled system package, but, it still might have
   2716                         // been removed. check the code path still exists and check there's
   2717                         // still a package. the latter can happen if an OTA keeps the same
   2718                         // code path, but, changes the package name.
   2719                         final PackageSetting disabledPs =
   2720                                 mSettings.getDisabledSystemPkgLPr(ps.name);
   2721                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()
   2722                                 || disabledPs.pkg == null) {
   2723                             possiblyDeletedUpdatedSystemApps.add(ps.name);
   2724                         }
   2725                     }
   2726                 }
   2727             }
   2728 
   2729             //look for any incomplete package installations
   2730             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
   2731             for (int i = 0; i < deletePkgsList.size(); i++) {
   2732                 // Actual deletion of code and data will be handled by later
   2733                 // reconciliation step
   2734                 final String packageName = deletePkgsList.get(i).name;
   2735                 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
   2736                 synchronized (mPackages) {
   2737                     mSettings.removePackageLPw(packageName);
   2738                 }
   2739             }
   2740 
   2741             //delete tmp files
   2742             deleteTempPackageFiles();
   2743 
   2744             final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
   2745 
   2746             // Remove any shared userIDs that have no associated packages
   2747             mSettings.pruneSharedUsersLPw();
   2748             final long systemScanTime = SystemClock.uptimeMillis() - startTime;
   2749             final int systemPackagesCount = mPackages.size();
   2750             Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
   2751                     + " ms, packageCount: " + systemPackagesCount
   2752                     + " , timePerPackage: "
   2753                     + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
   2754                     + " , cached: " + cachedSystemApps);
   2755             if (mIsUpgrade && systemPackagesCount > 0) {
   2756                 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
   2757                         ((int) systemScanTime) / systemPackagesCount);
   2758             }
   2759             if (!mOnlyCore) {
   2760                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
   2761                         SystemClock.uptimeMillis());
   2762                 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
   2763 
   2764                 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
   2765                         | PackageParser.PARSE_FORWARD_LOCK,
   2766                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
   2767 
   2768                 // Remove disable package settings for updated system apps that were
   2769                 // removed via an OTA. If the update is no longer present, remove the
   2770                 // app completely. Otherwise, revoke their system privileges.
   2771                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
   2772                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
   2773                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
   2774 
   2775                     final String msg;
   2776                     if (deletedPkg == null) {
   2777                         // should have found an update, but, we didn't; remove everything
   2778                         msg = "Updated system package " + deletedAppName
   2779                                 + " no longer exists; removing its data";
   2780                         // Actual deletion of code and data will be handled by later
   2781                         // reconciliation step
   2782                     } else {
   2783                         // found an update; revoke system privileges
   2784                         msg = "Updated system package + " + deletedAppName
   2785                                 + " no longer exists; revoking system privileges";
   2786 
   2787                         // Don't do anything if a stub is removed from the system image. If
   2788                         // we were to remove the uncompressed version from the /data partition,
   2789                         // this is where it'd be done.
   2790 
   2791                         final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
   2792                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
   2793                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
   2794                     }
   2795                     logCriticalInfo(Log.WARN, msg);
   2796                 }
   2797 
   2798                 /*
   2799                  * Make sure all system apps that we expected to appear on
   2800                  * the userdata partition actually showed up. If they never
   2801                  * appeared, crawl back and revive the system version.
   2802                  */
   2803                 for (int i = 0; i < mExpectingBetter.size(); i++) {
   2804                     final String packageName = mExpectingBetter.keyAt(i);
   2805                     if (!mPackages.containsKey(packageName)) {
   2806                         final File scanFile = mExpectingBetter.valueAt(i);
   2807 
   2808                         logCriticalInfo(Log.WARN, "Expected better " + packageName
   2809                                 + " but never showed up; reverting to system");
   2810 
   2811                         int reparseFlags = mDefParseFlags;
   2812                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
   2813                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   2814                                     | PackageParser.PARSE_IS_SYSTEM_DIR
   2815                                     | PackageParser.PARSE_IS_PRIVILEGED;
   2816                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
   2817                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   2818                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
   2819                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
   2820                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   2821                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
   2822                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
   2823                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   2824                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
   2825                         } else {
   2826                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
   2827                             continue;
   2828                         }
   2829 
   2830                         mSettings.enableSystemPackageLPw(packageName);
   2831 
   2832                         try {
   2833                             scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
   2834                         } catch (PackageManagerException e) {
   2835                             Slog.e(TAG, "Failed to parse original system package: "
   2836                                     + e.getMessage());
   2837                         }
   2838                     }
   2839                 }
   2840 
   2841                 // Uncompress and install any stubbed system applications.
   2842                 // This must be done last to ensure all stubs are replaced or disabled.
   2843                 decompressSystemApplications(stubSystemApps, scanFlags);
   2844 
   2845                 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
   2846                                 - cachedSystemApps;
   2847 
   2848                 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
   2849                 final int dataPackagesCount = mPackages.size() - systemPackagesCount;
   2850                 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
   2851                         + " ms, packageCount: " + dataPackagesCount
   2852                         + " , timePerPackage: "
   2853                         + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
   2854                         + " , cached: " + cachedNonSystemApps);
   2855                 if (mIsUpgrade && dataPackagesCount > 0) {
   2856                     MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
   2857                             ((int) dataScanTime) / dataPackagesCount);
   2858                 }
   2859             }
   2860             mExpectingBetter.clear();
   2861 
   2862             // Resolve the storage manager.
   2863             mStorageManagerPackage = getStorageManagerPackageName();
   2864 
   2865             // Resolve protected action filters. Only the setup wizard is allowed to
   2866             // have a high priority filter for these actions.
   2867             mSetupWizardPackage = getSetupWizardPackageName();
   2868             if (mProtectedFilters.size() > 0) {
   2869                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
   2870                     Slog.i(TAG, "No setup wizard;"
   2871                         + " All protected intents capped to priority 0");
   2872                 }
   2873                 for (ActivityIntentInfo filter : mProtectedFilters) {
   2874                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
   2875                         if (DEBUG_FILTERS) {
   2876                             Slog.i(TAG, "Found setup wizard;"
   2877                                 + " allow priority " + filter.getPriority() + ";"
   2878                                 + " package: " + filter.activity.info.packageName
   2879                                 + " activity: " + filter.activity.className
   2880                                 + " priority: " + filter.getPriority());
   2881                         }
   2882                         // skip setup wizard; allow it to keep the high priority filter
   2883                         continue;
   2884                     }
   2885                     if (DEBUG_FILTERS) {
   2886                         Slog.i(TAG, "Protected action; cap priority to 0;"
   2887                                 + " package: " + filter.activity.info.packageName
   2888                                 + " activity: " + filter.activity.className
   2889                                 + " origPrio: " + filter.getPriority());
   2890                     }
   2891                     filter.setPriority(0);
   2892                 }
   2893             }
   2894             mDeferProtectedFilters = false;
   2895             mProtectedFilters.clear();
   2896 
   2897             // Now that we know all of the shared libraries, update all clients to have
   2898             // the correct library paths.
   2899             updateAllSharedLibrariesLPw(null);
   2900 
   2901             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
   2902                 // NOTE: We ignore potential failures here during a system scan (like
   2903                 // the rest of the commands above) because there's precious little we
   2904                 // can do about it. A settings error is reported, though.
   2905                 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
   2906             }
   2907 
   2908             // Now that we know all the packages we are keeping,
   2909             // read and update their last usage times.
   2910             mPackageUsage.read(mPackages);
   2911             mCompilerStats.read();
   2912 
   2913             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
   2914                     SystemClock.uptimeMillis());
   2915             Slog.i(TAG, "Time to scan packages: "
   2916                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
   2917                     + " seconds");
   2918 
   2919             // If the platform SDK has changed since the last time we booted,
   2920             // we need to re-grant app permission to catch any new ones that
   2921             // appear.  This is really a hack, and means that apps can in some
   2922             // cases get permissions that the user didn't initially explicitly
   2923             // allow...  it would be nice to have some better way to handle
   2924             // this situation.
   2925             int updateFlags = UPDATE_PERMISSIONS_ALL;
   2926             if (ver.sdkVersion != mSdkVersion) {
   2927                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
   2928                         + mSdkVersion + "; regranting permissions for internal storage");
   2929                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
   2930             }
   2931             updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
   2932             ver.sdkVersion = mSdkVersion;
   2933 
   2934             // If this is the first boot or an update from pre-M, and it is a normal
   2935             // boot, then we need to initialize the default preferred apps across
   2936             // all defined users.
   2937             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
   2938                 for (UserInfo user : sUserManager.getUsers(true)) {
   2939                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
   2940                     applyFactoryDefaultBrowserLPw(user.id);
   2941                     primeDomainVerificationsLPw(user.id);
   2942                 }
   2943             }
   2944 
   2945             // Prepare storage for system user really early during boot,
   2946             // since core system apps like SettingsProvider and SystemUI
   2947             // can't wait for user to start
   2948             final int storageFlags;
   2949             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
   2950                 storageFlags = StorageManager.FLAG_STORAGE_DE;
   2951             } else {
   2952                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
   2953             }
   2954             List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
   2955                     UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
   2956                     true /* onlyCoreApps */);
   2957             mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
   2958                 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
   2959                         Trace.TRACE_TAG_PACKAGE_MANAGER);
   2960                 traceLog.traceBegin("AppDataFixup");
   2961                 try {
   2962                     mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
   2963                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
   2964                 } catch (InstallerException e) {
   2965                     Slog.w(TAG, "Trouble fixing GIDs", e);
   2966                 }
   2967                 traceLog.traceEnd();
   2968 
   2969                 traceLog.traceBegin("AppDataPrepare");
   2970                 if (deferPackages == null || deferPackages.isEmpty()) {
   2971                     return;
   2972                 }
   2973                 int count = 0;
   2974                 for (String pkgName : deferPackages) {
   2975                     PackageParser.Package pkg = null;
   2976                     synchronized (mPackages) {
   2977                         PackageSetting ps = mSettings.getPackageLPr(pkgName);
   2978                         if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
   2979                             pkg = ps.pkg;
   2980                         }
   2981                     }
   2982                     if (pkg != null) {
   2983                         synchronized (mInstallLock) {
   2984                             prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
   2985                                     true /* maybeMigrateAppData */);
   2986                         }
   2987                         count++;
   2988                     }
   2989                 }
   2990                 traceLog.traceEnd();
   2991                 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
   2992             }, "prepareAppData");
   2993 
   2994             // If this is first boot after an OTA, and a normal boot, then
   2995             // we need to clear code cache directories.
   2996             // Note that we do *not* clear the application profiles. These remain valid
   2997             // across OTAs and are used to drive profile verification (post OTA) and
   2998             // profile compilation (without waiting to collect a fresh set of profiles).
   2999             if (mIsUpgrade && !onlyCore) {
   3000                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
   3001                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
   3002                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
   3003                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
   3004                         // No apps are running this early, so no need to freeze
   3005                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
   3006                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
   3007                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   3008                     }
   3009                 }
   3010                 ver.fingerprint = Build.FINGERPRINT;
   3011             }
   3012 
   3013             checkDefaultBrowser();
   3014 
   3015             // clear only after permissions and other defaults have been updated
   3016             mExistingSystemPackages.clear();
   3017             mPromoteSystemApps = false;
   3018 
   3019             // All the changes are done during package scanning.
   3020             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
   3021 
   3022             // can downgrade to reader
   3023             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
   3024             mSettings.writeLPr();
   3025             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3026             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
   3027                     SystemClock.uptimeMillis());
   3028 
   3029             if (!mOnlyCore) {
   3030                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
   3031                 mRequiredInstallerPackage = getRequiredInstallerLPr();
   3032                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
   3033                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
   3034                 if (mIntentFilterVerifierComponent != null) {
   3035                     mIntentFilterVerifier = new IntentVerifierProxy(mContext,
   3036                             mIntentFilterVerifierComponent);
   3037                 } else {
   3038                     mIntentFilterVerifier = null;
   3039                 }
   3040                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
   3041                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
   3042                         SharedLibraryInfo.VERSION_UNDEFINED);
   3043                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
   3044                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
   3045                         SharedLibraryInfo.VERSION_UNDEFINED);
   3046             } else {
   3047                 mRequiredVerifierPackage = null;
   3048                 mRequiredInstallerPackage = null;
   3049                 mRequiredUninstallerPackage = null;
   3050                 mIntentFilterVerifierComponent = null;
   3051                 mIntentFilterVerifier = null;
   3052                 mServicesSystemSharedLibraryPackageName = null;
   3053                 mSharedSystemSharedLibraryPackageName = null;
   3054             }
   3055 
   3056             mInstallerService = new PackageInstallerService(context, this);
   3057             final Pair<ComponentName, String> instantAppResolverComponent =
   3058                     getInstantAppResolverLPr();
   3059             if (instantAppResolverComponent != null) {
   3060                 if (DEBUG_EPHEMERAL) {
   3061                     Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
   3062                 }
   3063                 mInstantAppResolverConnection = new EphemeralResolverConnection(
   3064                         mContext, instantAppResolverComponent.first,
   3065                         instantAppResolverComponent.second);
   3066                 mInstantAppResolverSettingsComponent =
   3067                         getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
   3068             } else {
   3069                 mInstantAppResolverConnection = null;
   3070                 mInstantAppResolverSettingsComponent = null;
   3071             }
   3072             updateInstantAppInstallerLocked(null);
   3073 
   3074             // Read and update the usage of dex files.
   3075             // Do this at the end of PM init so that all the packages have their
   3076             // data directory reconciled.
   3077             // At this point we know the code paths of the packages, so we can validate
   3078             // the disk file and build the internal cache.
   3079             // The usage file is expected to be small so loading and verifying it
   3080             // should take a fairly small time compare to the other activities (e.g. package
   3081             // scanning).
   3082             final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
   3083             final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
   3084             for (int userId : currentUserIds) {
   3085                 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
   3086             }
   3087             mDexManager.load(userPackages);
   3088             if (mIsUpgrade) {
   3089                 MetricsLogger.histogram(null, "ota_package_manager_init_time",
   3090                         (int) (SystemClock.uptimeMillis() - startTime));
   3091             }
   3092         } // synchronized (mPackages)
   3093         } // synchronized (mInstallLock)
   3094 
   3095         // Now after opening every single application zip, make sure they
   3096         // are all flushed.  Not really needed, but keeps things nice and
   3097         // tidy.
   3098         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
   3099         Runtime.getRuntime().gc();
   3100         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3101 
   3102         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
   3103         FallbackCategoryProvider.loadFallbacks();
   3104         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3105 
   3106         // The initial scanning above does many calls into installd while
   3107         // holding the mPackages lock, but we're mostly interested in yelling
   3108         // once we have a booted system.
   3109         mInstaller.setWarnIfHeld(mPackages);
   3110 
   3111         // Expose private service for system components to use.
   3112         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
   3113         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3114     }
   3115 
   3116     /**
   3117      * Uncompress and install stub applications.
   3118      * <p>In order to save space on the system partition, some applications are shipped in a
   3119      * compressed form. In addition the compressed bits for the full application, the
   3120      * system image contains a tiny stub comprised of only the Android manifest.
   3121      * <p>During the first boot, attempt to uncompress and install the full application. If
   3122      * the application can't be installed for any reason, disable the stub and prevent
   3123      * uncompressing the full application during future boots.
   3124      * <p>In order to forcefully attempt an installation of a full application, go to app
   3125      * settings and enable the application.
   3126      */
   3127     private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
   3128         for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
   3129             final String pkgName = stubSystemApps.get(i);
   3130             // skip if the system package is already disabled
   3131             if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
   3132                 stubSystemApps.remove(i);
   3133                 continue;
   3134             }
   3135             // skip if the package isn't installed (?!); this should never happen
   3136             final PackageParser.Package pkg = mPackages.get(pkgName);
   3137             if (pkg == null) {
   3138                 stubSystemApps.remove(i);
   3139                 continue;
   3140             }
   3141             // skip if the package has been disabled by the user
   3142             final PackageSetting ps = mSettings.mPackages.get(pkgName);
   3143             if (ps != null) {
   3144                 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
   3145                 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
   3146                     stubSystemApps.remove(i);
   3147                     continue;
   3148                 }
   3149             }
   3150 
   3151             if (DEBUG_COMPRESSION) {
   3152                 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
   3153             }
   3154 
   3155             // uncompress the binary to its eventual destination on /data
   3156             final File scanFile = decompressPackage(pkg);
   3157             if (scanFile == null) {
   3158                 continue;
   3159             }
   3160 
   3161             // install the package to replace the stub on /system
   3162             try {
   3163                 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
   3164                 removePackageLI(pkg, true /*chatty*/);
   3165                 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
   3166                 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
   3167                         UserHandle.USER_SYSTEM, "android");
   3168                 stubSystemApps.remove(i);
   3169                 continue;
   3170             } catch (PackageManagerException e) {
   3171                 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
   3172             }
   3173 
   3174             // any failed attempt to install the package will be cleaned up later
   3175         }
   3176 
   3177         // disable any stub still left; these failed to install the full application
   3178         for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
   3179             final String pkgName = stubSystemApps.get(i);
   3180             final PackageSetting ps = mSettings.mPackages.get(pkgName);
   3181             ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
   3182                     UserHandle.USER_SYSTEM, "android");
   3183             logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
   3184         }
   3185     }
   3186 
   3187     private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
   3188         if (DEBUG_COMPRESSION) {
   3189             Slog.i(TAG, "Decompress file"
   3190                     + "; src: " + srcFile.getAbsolutePath()
   3191                     + ", dst: " + dstFile.getAbsolutePath());
   3192         }
   3193         try (
   3194                 InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
   3195                 OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
   3196         ) {
   3197             Streams.copy(fileIn, fileOut);
   3198             Os.chmod(dstFile.getAbsolutePath(), 0644);
   3199             return PackageManager.INSTALL_SUCCEEDED;
   3200         } catch (IOException e) {
   3201             logCriticalInfo(Log.ERROR, "Failed to decompress file"
   3202                     + "; src: " + srcFile.getAbsolutePath()
   3203                     + ", dst: " + dstFile.getAbsolutePath());
   3204         }
   3205         return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   3206     }
   3207 
   3208     private File[] getCompressedFiles(String codePath) {
   3209         final File stubCodePath = new File(codePath);
   3210         final String stubName = stubCodePath.getName();
   3211 
   3212         // The layout of a compressed package on a given partition is as follows :
   3213         //
   3214         // Compressed artifacts:
   3215         //
   3216         // /partition/ModuleName/foo.gz
   3217         // /partation/ModuleName/bar.gz
   3218         //
   3219         // Stub artifact:
   3220         //
   3221         // /partition/ModuleName-Stub/ModuleName-Stub.apk
   3222         //
   3223         // In other words, stub is on the same partition as the compressed artifacts
   3224         // and in a directory that's suffixed with "-Stub".
   3225         int idx = stubName.lastIndexOf(STUB_SUFFIX);
   3226         if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
   3227             return null;
   3228         }
   3229 
   3230         final File stubParentDir = stubCodePath.getParentFile();
   3231         if (stubParentDir == null) {
   3232             Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
   3233             return null;
   3234         }
   3235 
   3236         final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
   3237         final File[] files = compressedPath.listFiles(new FilenameFilter() {
   3238             @Override
   3239             public boolean accept(File dir, String name) {
   3240                 return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
   3241             }
   3242         });
   3243 
   3244         if (DEBUG_COMPRESSION && files != null && files.length > 0) {
   3245             Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
   3246         }
   3247 
   3248         return files;
   3249     }
   3250 
   3251     private boolean compressedFileExists(String codePath) {
   3252         final File[] compressedFiles = getCompressedFiles(codePath);
   3253         return compressedFiles != null && compressedFiles.length > 0;
   3254     }
   3255 
   3256     /**
   3257      * Decompresses the given package on the system image onto
   3258      * the /data partition.
   3259      * @return The directory the package was decompressed into. Otherwise, {@code null}.
   3260      */
   3261     private File decompressPackage(PackageParser.Package pkg) {
   3262         final File[] compressedFiles = getCompressedFiles(pkg.codePath);
   3263         if (compressedFiles == null || compressedFiles.length == 0) {
   3264             if (DEBUG_COMPRESSION) {
   3265                 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
   3266             }
   3267             return null;
   3268         }
   3269         final File dstCodePath =
   3270                 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
   3271         int ret = PackageManager.INSTALL_SUCCEEDED;
   3272         try {
   3273             Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
   3274             Os.chmod(dstCodePath.getAbsolutePath(), 0755);
   3275             for (File srcFile : compressedFiles) {
   3276                 final String srcFileName = srcFile.getName();
   3277                 final String dstFileName = srcFileName.substring(
   3278                         0, srcFileName.length() - COMPRESSED_EXTENSION.length());
   3279                 final File dstFile = new File(dstCodePath, dstFileName);
   3280                 ret = decompressFile(srcFile, dstFile);
   3281                 if (ret != PackageManager.INSTALL_SUCCEEDED) {
   3282                     logCriticalInfo(Log.ERROR, "Failed to decompress"
   3283                             + "; pkg: " + pkg.packageName
   3284                             + ", file: " + dstFileName);
   3285                     break;
   3286                 }
   3287             }
   3288         } catch (ErrnoException e) {
   3289             logCriticalInfo(Log.ERROR, "Failed to decompress"
   3290                     + "; pkg: " + pkg.packageName
   3291                     + ", err: " + e.errno);
   3292         }
   3293         if (ret == PackageManager.INSTALL_SUCCEEDED) {
   3294             final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
   3295             NativeLibraryHelper.Handle handle = null;
   3296             try {
   3297                 handle = NativeLibraryHelper.Handle.create(dstCodePath);
   3298                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
   3299                         null /*abiOverride*/);
   3300             } catch (IOException e) {
   3301                 logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
   3302                         + "; pkg: " + pkg.packageName);
   3303                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   3304             } finally {
   3305                 IoUtils.closeQuietly(handle);
   3306             }
   3307         }
   3308         if (ret != PackageManager.INSTALL_SUCCEEDED) {
   3309             if (dstCodePath == null || !dstCodePath.exists()) {
   3310                 return null;
   3311             }
   3312             removeCodePathLI(dstCodePath);
   3313             return null;
   3314         }
   3315 
   3316         return dstCodePath;
   3317     }
   3318 
   3319     private void updateInstantAppInstallerLocked(String modifiedPackage) {
   3320         // we're only interested in updating the installer appliction when 1) it's not
   3321         // already set or 2) the modified package is the installer
   3322         if (mInstantAppInstallerActivity != null
   3323                 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
   3324                         .equals(modifiedPackage)) {
   3325             return;
   3326         }
   3327         setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
   3328     }
   3329 
   3330     private static File preparePackageParserCache(boolean isUpgrade) {
   3331         if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
   3332             return null;
   3333         }
   3334 
   3335         // Disable package parsing on eng builds to allow for faster incremental development.
   3336         if (Build.IS_ENG) {
   3337             return null;
   3338         }
   3339 
   3340         if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
   3341             Slog.i(TAG, "Disabling package parser cache due to system property.");
   3342             return null;
   3343         }
   3344 
   3345         // The base directory for the package parser cache lives under /data/system/.
   3346         final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
   3347                 "package_cache");
   3348         if (cacheBaseDir == null) {
   3349             return null;
   3350         }
   3351 
   3352         // If this is a system upgrade scenario, delete the contents of the package cache dir.
   3353         // This also serves to "GC" unused entries when the package cache version changes (which
   3354         // can only happen during upgrades).
   3355         if (isUpgrade) {
   3356             FileUtils.deleteContents(cacheBaseDir);
   3357         }
   3358 
   3359 
   3360         // Return the versioned package cache directory. This is something like
   3361         // "/data/system/package_cache/1"
   3362         File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
   3363 
   3364         // The following is a workaround to aid development on non-numbered userdebug
   3365         // builds or cases where "adb sync" is used on userdebug builds. If we detect that
   3366         // the system partition is newer.
   3367         //
   3368         // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
   3369         // that starts with "eng." to signify that this is an engineering build and not
   3370         // destined for release.
   3371         if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
   3372             Slog.w(TAG, "Wiping cache directory because the system partition changed.");
   3373 
   3374             // Heuristic: If the /system directory has been modified recently due to an "adb sync"
   3375             // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
   3376             // in general and should not be used for production changes. In this specific case,
   3377             // we know that they will work.
   3378             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
   3379             if (cacheDir.lastModified() < frameworkDir.lastModified()) {
   3380                 FileUtils.deleteContents(cacheBaseDir);
   3381                 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
   3382             }
   3383         }
   3384 
   3385         return cacheDir;
   3386     }
   3387 
   3388     @Override
   3389     public boolean isFirstBoot() {
   3390         // allow instant applications
   3391         return mFirstBoot;
   3392     }
   3393 
   3394     @Override
   3395     public boolean isOnlyCoreApps() {
   3396         // allow instant applications
   3397         return mOnlyCore;
   3398     }
   3399 
   3400     @Override
   3401     public boolean isUpgrade() {
   3402         // allow instant applications
   3403         return mIsUpgrade;
   3404     }
   3405 
   3406     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
   3407         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
   3408 
   3409         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
   3410                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3411                 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
   3412         if (matches.size() == 1) {
   3413             return matches.get(0).getComponentInfo().packageName;
   3414         } else if (matches.size() == 0) {
   3415             Log.e(TAG, "There should probably be a verifier, but, none were found");
   3416             return null;
   3417         }
   3418         throw new RuntimeException("There must be exactly one verifier; found " + matches);
   3419     }
   3420 
   3421     private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
   3422         synchronized (mPackages) {
   3423             SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
   3424             if (libraryEntry == null) {
   3425                 throw new IllegalStateException("Missing required shared library:" + name);
   3426             }
   3427             return libraryEntry.apk;
   3428         }
   3429     }
   3430 
   3431     private @NonNull String getRequiredInstallerLPr() {
   3432         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
   3433         intent.addCategory(Intent.CATEGORY_DEFAULT);
   3434         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
   3435 
   3436         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
   3437                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3438                 UserHandle.USER_SYSTEM);
   3439         if (matches.size() == 1) {
   3440             ResolveInfo resolveInfo = matches.get(0);
   3441             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
   3442                 throw new RuntimeException("The installer must be a privileged app");
   3443             }
   3444             return matches.get(0).getComponentInfo().packageName;
   3445         } else {
   3446             throw new RuntimeException("There must be exactly one installer; found " + matches);
   3447         }
   3448     }
   3449 
   3450     private @NonNull String getRequiredUninstallerLPr() {
   3451         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
   3452         intent.addCategory(Intent.CATEGORY_DEFAULT);
   3453         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
   3454 
   3455         final ResolveInfo resolveInfo = resolveIntent(intent, null,
   3456                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3457                 UserHandle.USER_SYSTEM);
   3458         if (resolveInfo == null ||
   3459                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
   3460             throw new RuntimeException("There must be exactly one uninstaller; found "
   3461                     + resolveInfo);
   3462         }
   3463         return resolveInfo.getComponentInfo().packageName;
   3464     }
   3465 
   3466     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
   3467         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
   3468 
   3469         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
   3470                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3471                 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
   3472         ResolveInfo best = null;
   3473         final int N = matches.size();
   3474         for (int i = 0; i < N; i++) {
   3475             final ResolveInfo cur = matches.get(i);
   3476             final String packageName = cur.getComponentInfo().packageName;
   3477             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
   3478                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
   3479                 continue;
   3480             }
   3481 
   3482             if (best == null || cur.priority > best.priority) {
   3483                 best = cur;
   3484             }
   3485         }
   3486 
   3487         if (best != null) {
   3488             return best.getComponentInfo().getComponentName();
   3489         }
   3490         Slog.w(TAG, "Intent filter verifier not found");
   3491         return null;
   3492     }
   3493 
   3494     @Override
   3495     public @Nullable ComponentName getInstantAppResolverComponent() {
   3496         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   3497             return null;
   3498         }
   3499         synchronized (mPackages) {
   3500             final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
   3501             if (instantAppResolver == null) {
   3502                 return null;
   3503             }
   3504             return instantAppResolver.first;
   3505         }
   3506     }
   3507 
   3508     private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
   3509         final String[] packageArray =
   3510                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
   3511         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
   3512             if (DEBUG_EPHEMERAL) {
   3513                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
   3514             }
   3515             return null;
   3516         }
   3517 
   3518         final int callingUid = Binder.getCallingUid();
   3519         final int resolveFlags =
   3520                 MATCH_DIRECT_BOOT_AWARE
   3521                 | MATCH_DIRECT_BOOT_UNAWARE
   3522                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
   3523         String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
   3524         final Intent resolverIntent = new Intent(actionName);
   3525         List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
   3526                 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
   3527         // temporarily look for the old action
   3528         if (resolvers.size() == 0) {
   3529             if (DEBUG_EPHEMERAL) {
   3530                 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
   3531             }
   3532             actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
   3533             resolverIntent.setAction(actionName);
   3534             resolvers = queryIntentServicesInternal(resolverIntent, null,
   3535                     resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
   3536         }
   3537         final int N = resolvers.size();
   3538         if (N == 0) {
   3539             if (DEBUG_EPHEMERAL) {
   3540                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
   3541             }
   3542             return null;
   3543         }
   3544 
   3545         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
   3546         for (int i = 0; i < N; i++) {
   3547             final ResolveInfo info = resolvers.get(i);
   3548 
   3549             if (info.serviceInfo == null) {
   3550                 continue;
   3551             }
   3552 
   3553             final String packageName = info.serviceInfo.packageName;
   3554             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
   3555                 if (DEBUG_EPHEMERAL) {
   3556                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
   3557                             + " pkg: " + packageName + ", info:" + info);
   3558                 }
   3559                 continue;
   3560             }
   3561 
   3562             if (DEBUG_EPHEMERAL) {
   3563                 Slog.v(TAG, "Ephemeral resolver found;"
   3564                         + " pkg: " + packageName + ", info:" + info);
   3565             }
   3566             return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
   3567         }
   3568         if (DEBUG_EPHEMERAL) {
   3569             Slog.v(TAG, "Ephemeral resolver NOT found");
   3570         }
   3571         return null;
   3572     }
   3573 
   3574     private @Nullable ActivityInfo getInstantAppInstallerLPr() {
   3575         final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
   3576         intent.addCategory(Intent.CATEGORY_DEFAULT);
   3577         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
   3578 
   3579         final int resolveFlags =
   3580                 MATCH_DIRECT_BOOT_AWARE
   3581                 | MATCH_DIRECT_BOOT_UNAWARE
   3582                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
   3583         List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
   3584                 resolveFlags, UserHandle.USER_SYSTEM);
   3585         // temporarily look for the old action
   3586         if (matches.isEmpty()) {
   3587             if (DEBUG_EPHEMERAL) {
   3588                 Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
   3589             }
   3590             intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
   3591             matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
   3592                     resolveFlags, UserHandle.USER_SYSTEM);
   3593         }
   3594         Iterator<ResolveInfo> iter = matches.iterator();
   3595         while (iter.hasNext()) {
   3596             final ResolveInfo rInfo = iter.next();
   3597             final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
   3598             if (ps != null) {
   3599                 final PermissionsState permissionsState = ps.getPermissionsState();
   3600                 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
   3601                     continue;
   3602                 }
   3603             }
   3604             iter.remove();
   3605         }
   3606         if (matches.size() == 0) {
   3607             return null;
   3608         } else if (matches.size() == 1) {
   3609             return (ActivityInfo) matches.get(0).getComponentInfo();
   3610         } else {
   3611             throw new RuntimeException(
   3612                     "There must be at most one ephemeral installer; found " + matches);
   3613         }
   3614     }
   3615 
   3616     private @Nullable ComponentName getInstantAppResolverSettingsLPr(
   3617             @NonNull ComponentName resolver) {
   3618         final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
   3619                 .addCategory(Intent.CATEGORY_DEFAULT)
   3620                 .setPackage(resolver.getPackageName());
   3621         final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
   3622         List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
   3623                 UserHandle.USER_SYSTEM);
   3624         // temporarily look for the old action
   3625         if (matches.isEmpty()) {
   3626             if (DEBUG_EPHEMERAL) {
   3627                 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
   3628             }
   3629             intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
   3630             matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
   3631                     UserHandle.USER_SYSTEM);
   3632         }
   3633         if (matches.isEmpty()) {
   3634             return null;
   3635         }
   3636         return matches.get(0).getComponentInfo().getComponentName();
   3637     }
   3638 
   3639     private void primeDomainVerificationsLPw(int userId) {
   3640         if (DEBUG_DOMAIN_VERIFICATION) {
   3641             Slog.d(TAG, "Priming domain verifications in user " + userId);
   3642         }
   3643 
   3644         SystemConfig systemConfig = SystemConfig.getInstance();
   3645         ArraySet<String> packages = systemConfig.getLinkedApps();
   3646 
   3647         for (String packageName : packages) {
   3648             PackageParser.Package pkg = mPackages.get(packageName);
   3649             if (pkg != null) {
   3650                 if (!pkg.isSystemApp()) {
   3651                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
   3652                     continue;
   3653                 }
   3654 
   3655                 ArraySet<String> domains = null;
   3656                 for (PackageParser.Activity a : pkg.activities) {
   3657                     for (ActivityIntentInfo filter : a.intents) {
   3658                         if (hasValidDomains(filter)) {
   3659                             if (domains == null) {
   3660                                 domains = new ArraySet<String>();
   3661                             }
   3662                             domains.addAll(filter.getHostsList());
   3663                         }
   3664                     }
   3665                 }
   3666 
   3667                 if (domains != null && domains.size() > 0) {
   3668                     if (DEBUG_DOMAIN_VERIFICATION) {
   3669                         Slog.v(TAG, "      + " + packageName);
   3670                     }
   3671                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
   3672                     // state w.r.t. the formal app-linkage "no verification attempted" state;
   3673                     // and then 'always' in the per-user state actually used for intent resolution.
   3674                     final IntentFilterVerificationInfo ivi;
   3675                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
   3676                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
   3677                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
   3678                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
   3679                 } else {
   3680                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
   3681                             + "' does not handle web links");
   3682                 }
   3683             } else {
   3684                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
   3685             }
   3686         }
   3687 
   3688         scheduleWritePackageRestrictionsLocked(userId);
   3689         scheduleWriteSettingsLocked();
   3690     }
   3691 
   3692     private void applyFactoryDefaultBrowserLPw(int userId) {
   3693         // The default browser app's package name is stored in a string resource,
   3694         // with a product-specific overlay used for vendor customization.
   3695         String browserPkg = mContext.getResources().getString(
   3696                 com.android.internal.R.string.default_browser);
   3697         if (!TextUtils.isEmpty(browserPkg)) {
   3698             // non-empty string => required to be a known package
   3699             PackageSetting ps = mSettings.mPackages.get(browserPkg);
   3700             if (ps == null) {
   3701                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
   3702                 browserPkg = null;
   3703             } else {
   3704                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
   3705             }
   3706         }
   3707 
   3708         // Nothing valid explicitly set? Make the factory-installed browser the explicit
   3709         // default.  If there's more than one, just leave everything alone.
   3710         if (browserPkg == null) {
   3711             calculateDefaultBrowserLPw(userId);
   3712         }
   3713     }
   3714 
   3715     private void calculateDefaultBrowserLPw(int userId) {
   3716         List<String> allBrowsers = resolveAllBrowserApps(userId);
   3717         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
   3718         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
   3719     }
   3720 
   3721     private List<String> resolveAllBrowserApps(int userId) {
   3722         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
   3723         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
   3724                 PackageManager.MATCH_ALL, userId);
   3725 
   3726         final int count = list.size();
   3727         List<String> result = new ArrayList<String>(count);
   3728         for (int i=0; i<count; i++) {
   3729             ResolveInfo info = list.get(i);
   3730             if (info.activityInfo == null
   3731                     || !info.handleAllWebDataURI
   3732                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
   3733                     || result.contains(info.activityInfo.packageName)) {
   3734                 continue;
   3735             }
   3736             result.add(info.activityInfo.packageName);
   3737         }
   3738 
   3739         return result;
   3740     }
   3741 
   3742     private boolean packageIsBrowser(String packageName, int userId) {
   3743         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
   3744                 PackageManager.MATCH_ALL, userId);
   3745         final int N = list.size();
   3746         for (int i = 0; i < N; i++) {
   3747             ResolveInfo info = list.get(i);
   3748             if (packageName.equals(info.activityInfo.packageName)) {
   3749                 return true;
   3750             }
   3751         }
   3752         return false;
   3753     }
   3754 
   3755     private void checkDefaultBrowser() {
   3756         final int myUserId = UserHandle.myUserId();
   3757         final String packageName = getDefaultBrowserPackageName(myUserId);
   3758         if (packageName != null) {
   3759             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
   3760             if (info == null) {
   3761                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
   3762                 synchronized (mPackages) {
   3763                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
   3764                 }
   3765             }
   3766         }
   3767     }
   3768 
   3769     @Override
   3770     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   3771             throws RemoteException {
   3772         try {
   3773             return super.onTransact(code, data, reply, flags);
   3774         } catch (RuntimeException e) {
   3775             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
   3776                 Slog.wtf(TAG, "Package Manager Crash", e);
   3777             }
   3778             throw e;
   3779         }
   3780     }
   3781 
   3782     static int[] appendInts(int[] cur, int[] add) {
   3783         if (add == null) return cur;
   3784         if (cur == null) return add;
   3785         final int N = add.length;
   3786         for (int i=0; i<N; i++) {
   3787             cur = appendInt(cur, add[i]);
   3788         }
   3789         return cur;
   3790     }
   3791 
   3792     /**
   3793      * Returns whether or not a full application can see an instant application.
   3794      * <p>
   3795      * Currently, there are three cases in which this can occur:
   3796      * <ol>
   3797      * <li>The calling application is a "special" process. Special processes
   3798      *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
   3799      * <li>The calling application has the permission
   3800      *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
   3801      * <li>The calling application is the default launcher on the
   3802      *     system partition.</li>
   3803      * </ol>
   3804      */
   3805     private boolean canViewInstantApps(int callingUid, int userId) {
   3806         if (callingUid < Process.FIRST_APPLICATION_UID) {
   3807             return true;
   3808         }
   3809         if (mContext.checkCallingOrSelfPermission(
   3810                 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
   3811             return true;
   3812         }
   3813         if (mContext.checkCallingOrSelfPermission(
   3814                 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
   3815             final ComponentName homeComponent = getDefaultHomeActivity(userId);
   3816             if (homeComponent != null
   3817                     && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
   3818                 return true;
   3819             }
   3820         }
   3821         return false;
   3822     }
   3823 
   3824     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
   3825         if (!sUserManager.exists(userId)) return null;
   3826         if (ps == null) {
   3827             return null;
   3828         }
   3829         PackageParser.Package p = ps.pkg;
   3830         if (p == null) {
   3831             return null;
   3832         }
   3833         final int callingUid = Binder.getCallingUid();
   3834         // Filter out ephemeral app metadata:
   3835         //   * The system/shell/root can see metadata for any app
   3836         //   * An installed app can see metadata for 1) other installed apps
   3837         //     and 2) ephemeral apps that have explicitly interacted with it
   3838         //   * Ephemeral apps can only see their own data and exposed installed apps
   3839         //   * Holding a signature permission allows seeing instant apps
   3840         if (filterAppAccessLPr(ps, callingUid, userId)) {
   3841             return null;
   3842         }
   3843 
   3844         final PermissionsState permissionsState = ps.getPermissionsState();
   3845 
   3846         // Compute GIDs only if requested
   3847         final int[] gids = (flags & PackageManager.GET_GIDS) == 0
   3848                 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
   3849         // Compute granted permissions only if package has requested permissions
   3850         final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
   3851                 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
   3852         final PackageUserState state = ps.readUserState(userId);
   3853 
   3854         if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
   3855                 && ps.isSystem()) {
   3856             flags |= MATCH_ANY_USER;
   3857         }
   3858 
   3859         PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
   3860                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
   3861 
   3862         if (packageInfo == null) {
   3863             return null;
   3864         }
   3865 
   3866         packageInfo.packageName = packageInfo.applicationInfo.packageName =
   3867                 resolveExternalPackageNameLPr(p);
   3868 
   3869         return packageInfo;
   3870     }
   3871 
   3872     @Override
   3873     public void checkPackageStartable(String packageName, int userId) {
   3874         final int callingUid = Binder.getCallingUid();
   3875         if (getInstantAppPackageName(callingUid) != null) {
   3876             throw new SecurityException("Instant applications don't have access to this method");
   3877         }
   3878         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
   3879         synchronized (mPackages) {
   3880             final PackageSetting ps = mSettings.mPackages.get(packageName);
   3881             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
   3882                 throw new SecurityException("Package " + packageName + " was not found!");
   3883             }
   3884 
   3885             if (!ps.getInstalled(userId)) {
   3886                 throw new SecurityException(
   3887                         "Package " + packageName + " was not installed for user " + userId + "!");
   3888             }
   3889 
   3890             if (mSafeMode && !ps.isSystem()) {
   3891                 throw new SecurityException("Package " + packageName + " not a system app!");
   3892             }
   3893 
   3894             if (mFrozenPackages.contains(packageName)) {
   3895                 throw new SecurityException("Package " + packageName + " is currently frozen!");
   3896             }
   3897 
   3898             if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
   3899                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
   3900             }
   3901         }
   3902     }
   3903 
   3904     @Override
   3905     public boolean isPackageAvailable(String packageName, int userId) {
   3906         if (!sUserManager.exists(userId)) return false;
   3907         final int callingUid = Binder.getCallingUid();
   3908         enforceCrossUserPermission(callingUid, userId,
   3909                 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
   3910         synchronized (mPackages) {
   3911             PackageParser.Package p = mPackages.get(packageName);
   3912             if (p != null) {
   3913                 final PackageSetting ps = (PackageSetting) p.mExtras;
   3914                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   3915                     return false;
   3916                 }
   3917                 if (ps != null) {
   3918                     final PackageUserState state = ps.readUserState(userId);
   3919                     if (state != null) {
   3920                         return PackageParser.isAvailable(state);
   3921                     }
   3922                 }
   3923             }
   3924         }
   3925         return false;
   3926     }
   3927 
   3928     @Override
   3929     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
   3930         return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
   3931                 flags, Binder.getCallingUid(), userId);
   3932     }
   3933 
   3934     @Override
   3935     public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
   3936             int flags, int userId) {
   3937         return getPackageInfoInternal(versionedPackage.getPackageName(),
   3938                 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
   3939     }
   3940 
   3941     /**
   3942      * Important: The provided filterCallingUid is used exclusively to filter out packages
   3943      * that can be seen based on user state. It's typically the original caller uid prior
   3944      * to clearing. Because it can only be provided by trusted code, it's value can be
   3945      * trusted and will be used as-is; unlike userId which will be validated by this method.
   3946      */
   3947     private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
   3948             int flags, int filterCallingUid, int userId) {
   3949         if (!sUserManager.exists(userId)) return null;
   3950         flags = updateFlagsForPackage(flags, userId, packageName);
   3951         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   3952                 false /* requireFullPermission */, false /* checkShell */, "get package info");
   3953 
   3954         // reader
   3955         synchronized (mPackages) {
   3956             // Normalize package name to handle renamed packages and static libs
   3957             packageName = resolveInternalPackageNameLPr(packageName, versionCode);
   3958 
   3959             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
   3960             if (matchFactoryOnly) {
   3961                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
   3962                 if (ps != null) {
   3963                     if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   3964                         return null;
   3965                     }
   3966                     if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   3967                         return null;
   3968                     }
   3969                     return generatePackageInfo(ps, flags, userId);
   3970                 }
   3971             }
   3972 
   3973             PackageParser.Package p = mPackages.get(packageName);
   3974             if (matchFactoryOnly && p != null && !isSystemApp(p)) {
   3975                 return null;
   3976             }
   3977             if (DEBUG_PACKAGE_INFO)
   3978                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
   3979             if (p != null) {
   3980                 final PackageSetting ps = (PackageSetting) p.mExtras;
   3981                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   3982                     return null;
   3983                 }
   3984                 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
   3985                     return null;
   3986                 }
   3987                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
   3988             }
   3989             if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
   3990                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   3991                 if (ps == null) return null;
   3992                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   3993                     return null;
   3994                 }
   3995                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   3996                     return null;
   3997                 }
   3998                 return generatePackageInfo(ps, flags, userId);
   3999             }
   4000         }
   4001         return null;
   4002     }
   4003 
   4004     private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
   4005         if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
   4006             return true;
   4007         }
   4008         if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
   4009             return true;
   4010         }
   4011         if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
   4012             return true;
   4013         }
   4014         return false;
   4015     }
   4016 
   4017     private boolean isComponentVisibleToInstantApp(
   4018             @Nullable ComponentName component, @ComponentType int type) {
   4019         if (type == TYPE_ACTIVITY) {
   4020             final PackageParser.Activity activity = mActivities.mActivities.get(component);
   4021             return activity != null
   4022                     ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
   4023                     : false;
   4024         } else if (type == TYPE_RECEIVER) {
   4025             final PackageParser.Activity activity = mReceivers.mActivities.get(component);
   4026             return activity != null
   4027                     ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
   4028                     : false;
   4029         } else if (type == TYPE_SERVICE) {
   4030             final PackageParser.Service service = mServices.mServices.get(component);
   4031             return service != null
   4032                     ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
   4033                     : false;
   4034         } else if (type == TYPE_PROVIDER) {
   4035             final PackageParser.Provider provider = mProviders.mProviders.get(component);
   4036             return provider != null
   4037                     ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
   4038                     : false;
   4039         } else if (type == TYPE_UNKNOWN) {
   4040             return isComponentVisibleToInstantApp(component);
   4041         }
   4042         return false;
   4043     }
   4044 
   4045     /**
   4046      * Returns whether or not access to the application should be filtered.
   4047      * <p>
   4048      * Access may be limited based upon whether the calling or target applications
   4049      * are instant applications.
   4050      *
   4051      * @see #canAccessInstantApps(int)
   4052      */
   4053     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
   4054             @Nullable ComponentName component, @ComponentType int componentType, int userId) {
   4055         // if we're in an isolated process, get the real calling UID
   4056         if (Process.isIsolated(callingUid)) {
   4057             callingUid = mIsolatedOwners.get(callingUid);
   4058         }
   4059         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   4060         final boolean callerIsInstantApp = instantAppPkgName != null;
   4061         if (ps == null) {
   4062             if (callerIsInstantApp) {
   4063                 // pretend the application exists, but, needs to be filtered
   4064                 return true;
   4065             }
   4066             return false;
   4067         }
   4068         // if the target and caller are the same application, don't filter
   4069         if (isCallerSameApp(ps.name, callingUid)) {
   4070             return false;
   4071         }
   4072         if (callerIsInstantApp) {
   4073             // request for a specific component; if it hasn't been explicitly exposed, filter
   4074             if (component != null) {
   4075                 return !isComponentVisibleToInstantApp(component, componentType);
   4076             }
   4077             // request for application; if no components have been explicitly exposed, filter
   4078             return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
   4079         }
   4080         if (ps.getInstantApp(userId)) {
   4081             // caller can see all components of all instant applications, don't filter
   4082             if (canViewInstantApps(callingUid, userId)) {
   4083                 return false;
   4084             }
   4085             // request for a specific instant application component, filter
   4086             if (component != null) {
   4087                 return true;
   4088             }
   4089             // request for an instant application; if the caller hasn't been granted access, filter
   4090             return !mInstantAppRegistry.isInstantAccessGranted(
   4091                     userId, UserHandle.getAppId(callingUid), ps.appId);
   4092         }
   4093         return false;
   4094     }
   4095 
   4096     /**
   4097      * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
   4098      */
   4099     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
   4100         return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
   4101     }
   4102 
   4103     private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
   4104             int flags) {
   4105         // Callers can access only the libs they depend on, otherwise they need to explicitly
   4106         // ask for the shared libraries given the caller is allowed to access all static libs.
   4107         if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
   4108             // System/shell/root get to see all static libs
   4109             final int appId = UserHandle.getAppId(uid);
   4110             if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
   4111                     || appId == Process.ROOT_UID) {
   4112                 return false;
   4113             }
   4114         }
   4115 
   4116         // No package means no static lib as it is always on internal storage
   4117         if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
   4118             return false;
   4119         }
   4120 
   4121         final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
   4122                 ps.pkg.staticSharedLibVersion);
   4123         if (libEntry == null) {
   4124             return false;
   4125         }
   4126 
   4127         final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
   4128         final String[] uidPackageNames = getPackagesForUid(resolvedUid);
   4129         if (uidPackageNames == null) {
   4130             return true;
   4131         }
   4132 
   4133         for (String uidPackageName : uidPackageNames) {
   4134             if (ps.name.equals(uidPackageName)) {
   4135                 return false;
   4136             }
   4137             PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
   4138             if (uidPs != null) {
   4139                 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
   4140                         libEntry.info.getName());
   4141                 if (index < 0) {
   4142                     continue;
   4143                 }
   4144                 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
   4145                     return false;
   4146                 }
   4147             }
   4148         }
   4149         return true;
   4150     }
   4151 
   4152     @Override
   4153     public String[] currentToCanonicalPackageNames(String[] names) {
   4154         final int callingUid = Binder.getCallingUid();
   4155         if (getInstantAppPackageName(callingUid) != null) {
   4156             return names;
   4157         }
   4158         final String[] out = new String[names.length];
   4159         // reader
   4160         synchronized (mPackages) {
   4161             final int callingUserId = UserHandle.getUserId(callingUid);
   4162             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
   4163             for (int i=names.length-1; i>=0; i--) {
   4164                 final PackageSetting ps = mSettings.mPackages.get(names[i]);
   4165                 boolean translateName = false;
   4166                 if (ps != null && ps.realName != null) {
   4167                     final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
   4168                     translateName = !targetIsInstantApp
   4169                             || canViewInstantApps
   4170                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
   4171                                     UserHandle.getAppId(callingUid), ps.appId);
   4172                 }
   4173                 out[i] = translateName ? ps.realName : names[i];
   4174             }
   4175         }
   4176         return out;
   4177     }
   4178 
   4179     @Override
   4180     public String[] canonicalToCurrentPackageNames(String[] names) {
   4181         final int callingUid = Binder.getCallingUid();
   4182         if (getInstantAppPackageName(callingUid) != null) {
   4183             return names;
   4184         }
   4185         final String[] out = new String[names.length];
   4186         // reader
   4187         synchronized (mPackages) {
   4188             final int callingUserId = UserHandle.getUserId(callingUid);
   4189             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
   4190             for (int i=names.length-1; i>=0; i--) {
   4191                 final String cur = mSettings.getRenamedPackageLPr(names[i]);
   4192                 boolean translateName = false;
   4193                 if (cur != null) {
   4194                     final PackageSetting ps = mSettings.mPackages.get(names[i]);
   4195                     final boolean targetIsInstantApp =
   4196                             ps != null && ps.getInstantApp(callingUserId);
   4197                     translateName = !targetIsInstantApp
   4198                             || canViewInstantApps
   4199                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
   4200                                     UserHandle.getAppId(callingUid), ps.appId);
   4201                 }
   4202                 out[i] = translateName ? cur : names[i];
   4203             }
   4204         }
   4205         return out;
   4206     }
   4207 
   4208     @Override
   4209     public int getPackageUid(String packageName, int flags, int userId) {
   4210         if (!sUserManager.exists(userId)) return -1;
   4211         final int callingUid = Binder.getCallingUid();
   4212         flags = updateFlagsForPackage(flags, userId, packageName);
   4213         enforceCrossUserPermission(callingUid, userId,
   4214                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
   4215 
   4216         // reader
   4217         synchronized (mPackages) {
   4218             final PackageParser.Package p = mPackages.get(packageName);
   4219             if (p != null && p.isMatch(flags)) {
   4220                 PackageSetting ps = (PackageSetting) p.mExtras;
   4221                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   4222                     return -1;
   4223                 }
   4224                 return UserHandle.getUid(userId, p.applicationInfo.uid);
   4225             }
   4226             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
   4227                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   4228                 if (ps != null && ps.isMatch(flags)
   4229                         && !filterAppAccessLPr(ps, callingUid, userId)) {
   4230                     return UserHandle.getUid(userId, ps.appId);
   4231                 }
   4232             }
   4233         }
   4234 
   4235         return -1;
   4236     }
   4237 
   4238     @Override
   4239     public int[] getPackageGids(String packageName, int flags, int userId) {
   4240         if (!sUserManager.exists(userId)) return null;
   4241         final int callingUid = Binder.getCallingUid();
   4242         flags = updateFlagsForPackage(flags, userId, packageName);
   4243         enforceCrossUserPermission(callingUid, userId,
   4244                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
   4245 
   4246         // reader
   4247         synchronized (mPackages) {
   4248             final PackageParser.Package p = mPackages.get(packageName);
   4249             if (p != null && p.isMatch(flags)) {
   4250                 PackageSetting ps = (PackageSetting) p.mExtras;
   4251                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   4252                     return null;
   4253                 }
   4254                 // TODO: Shouldn't this be checking for package installed state for userId and
   4255                 // return null?
   4256                 return ps.getPermissionsState().computeGids(userId);
   4257             }
   4258             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
   4259                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   4260                 if (ps != null && ps.isMatch(flags)
   4261                         && !filterAppAccessLPr(ps, callingUid, userId)) {
   4262                     return ps.getPermissionsState().computeGids(userId);
   4263                 }
   4264             }
   4265         }
   4266 
   4267         return null;
   4268     }
   4269 
   4270     static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
   4271         if (bp.perm != null) {
   4272             return PackageParser.generatePermissionInfo(bp.perm, flags);
   4273         }
   4274         PermissionInfo pi = new PermissionInfo();
   4275         pi.name = bp.name;
   4276         pi.packageName = bp.sourcePackage;
   4277         pi.nonLocalizedLabel = bp.name;
   4278         pi.protectionLevel = bp.protectionLevel;
   4279         return pi;
   4280     }
   4281 
   4282     @Override
   4283     public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
   4284         final int callingUid = Binder.getCallingUid();
   4285         if (getInstantAppPackageName(callingUid) != null) {
   4286             return null;
   4287         }
   4288         // reader
   4289         synchronized (mPackages) {
   4290             final BasePermission p = mSettings.mPermissions.get(name);
   4291             if (p == null) {
   4292                 return null;
   4293             }
   4294             // If the caller is an app that targets pre 26 SDK drop protection flags.
   4295             PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
   4296             if (permissionInfo != null) {
   4297                 final int protectionLevel = adjustPermissionProtectionFlagsLPr(
   4298                         permissionInfo.protectionLevel, packageName, callingUid);
   4299                 if (permissionInfo.protectionLevel != protectionLevel) {
   4300                     // If we return different protection level, don't use the cached info
   4301                     if (p.perm != null && p.perm.info == permissionInfo) {
   4302                         permissionInfo = new PermissionInfo(permissionInfo);
   4303                     }
   4304                     permissionInfo.protectionLevel = protectionLevel;
   4305                 }
   4306             }
   4307             return permissionInfo;
   4308         }
   4309     }
   4310 
   4311     private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
   4312             String packageName, int uid) {
   4313         // Signature permission flags area always reported
   4314         final int protectionLevelMasked = protectionLevel
   4315                 & (PermissionInfo.PROTECTION_NORMAL
   4316                 | PermissionInfo.PROTECTION_DANGEROUS
   4317                 | PermissionInfo.PROTECTION_SIGNATURE);
   4318         if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
   4319             return protectionLevel;
   4320         }
   4321 
   4322         // System sees all flags.
   4323         final int appId = UserHandle.getAppId(uid);
   4324         if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
   4325                 || appId == Process.SHELL_UID) {
   4326             return protectionLevel;
   4327         }
   4328 
   4329         // Normalize package name to handle renamed packages and static libs
   4330         packageName = resolveInternalPackageNameLPr(packageName,
   4331                 PackageManager.VERSION_CODE_HIGHEST);
   4332 
   4333         // Apps that target O see flags for all protection levels.
   4334         final PackageSetting ps = mSettings.mPackages.get(packageName);
   4335         if (ps == null) {
   4336             return protectionLevel;
   4337         }
   4338         if (ps.appId != appId) {
   4339             return protectionLevel;
   4340         }
   4341 
   4342         final PackageParser.Package pkg = mPackages.get(packageName);
   4343         if (pkg == null) {
   4344             return protectionLevel;
   4345         }
   4346         if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
   4347             return protectionLevelMasked;
   4348         }
   4349 
   4350         return protectionLevel;
   4351     }
   4352 
   4353     @Override
   4354     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
   4355             int flags) {
   4356         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   4357             return null;
   4358         }
   4359         // reader
   4360         synchronized (mPackages) {
   4361             if (group != null && !mPermissionGroups.containsKey(group)) {
   4362                 // This is thrown as NameNotFoundException
   4363                 return null;
   4364             }
   4365 
   4366             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
   4367             for (BasePermission p : mSettings.mPermissions.values()) {
   4368                 if (group == null) {
   4369                     if (p.perm == null || p.perm.info.group == null) {
   4370                         out.add(generatePermissionInfo(p, flags));
   4371                     }
   4372                 } else {
   4373                     if (p.perm != null && group.equals(p.perm.info.group)) {
   4374                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
   4375                     }
   4376                 }
   4377             }
   4378             return new ParceledListSlice<>(out);
   4379         }
   4380     }
   4381 
   4382     @Override
   4383     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
   4384         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   4385             return null;
   4386         }
   4387         // reader
   4388         synchronized (mPackages) {
   4389             return PackageParser.generatePermissionGroupInfo(
   4390                     mPermissionGroups.get(name), flags);
   4391         }
   4392     }
   4393 
   4394     @Override
   4395     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
   4396         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   4397             return ParceledListSlice.emptyList();
   4398         }
   4399         // reader
   4400         synchronized (mPackages) {
   4401             final int N = mPermissionGroups.size();
   4402             ArrayList<PermissionGroupInfo> out
   4403                     = new ArrayList<PermissionGroupInfo>(N);
   4404             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
   4405                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
   4406             }
   4407             return new ParceledListSlice<>(out);
   4408         }
   4409     }
   4410 
   4411     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
   4412             int filterCallingUid, int userId) {
   4413         if (!sUserManager.exists(userId)) return null;
   4414         PackageSetting ps = mSettings.mPackages.get(packageName);
   4415         if (ps != null) {
   4416             if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4417                 return null;
   4418             }
   4419             if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4420                 return null;
   4421             }
   4422             if (ps.pkg == null) {
   4423                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
   4424                 if (pInfo != null) {
   4425                     return pInfo.applicationInfo;
   4426                 }
   4427                 return null;
   4428             }
   4429             ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
   4430                     ps.readUserState(userId), userId);
   4431             if (ai != null) {
   4432                 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
   4433             }
   4434             return ai;
   4435         }
   4436         return null;
   4437     }
   4438 
   4439     @Override
   4440     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
   4441         return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
   4442     }
   4443 
   4444     /**
   4445      * Important: The provided filterCallingUid is used exclusively to filter out applications
   4446      * that can be seen based on user state. It's typically the original caller uid prior
   4447      * to clearing. Because it can only be provided by trusted code, it's value can be
   4448      * trusted and will be used as-is; unlike userId which will be validated by this method.
   4449      */
   4450     private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
   4451             int filterCallingUid, int userId) {
   4452         if (!sUserManager.exists(userId)) return null;
   4453         flags = updateFlagsForApplication(flags, userId, packageName);
   4454         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   4455                 false /* requireFullPermission */, false /* checkShell */, "get application info");
   4456 
   4457         // writer
   4458         synchronized (mPackages) {
   4459             // Normalize package name to handle renamed packages and static libs
   4460             packageName = resolveInternalPackageNameLPr(packageName,
   4461                     PackageManager.VERSION_CODE_HIGHEST);
   4462 
   4463             PackageParser.Package p = mPackages.get(packageName);
   4464             if (DEBUG_PACKAGE_INFO) Log.v(
   4465                     TAG, "getApplicationInfo " + packageName
   4466                     + ": " + p);
   4467             if (p != null) {
   4468                 PackageSetting ps = mSettings.mPackages.get(packageName);
   4469                 if (ps == null) return null;
   4470                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4471                     return null;
   4472                 }
   4473                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4474                     return null;
   4475                 }
   4476                 // Note: isEnabledLP() does not apply here - always return info
   4477                 ApplicationInfo ai = PackageParser.generateApplicationInfo(
   4478                         p, flags, ps.readUserState(userId), userId);
   4479                 if (ai != null) {
   4480                     ai.packageName = resolveExternalPackageNameLPr(p);
   4481                 }
   4482                 return ai;
   4483             }
   4484             if ("android".equals(packageName)||"system".equals(packageName)) {
   4485                 return mAndroidApplication;
   4486             }
   4487             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
   4488                 // Already generates the external package name
   4489                 return generateApplicationInfoFromSettingsLPw(packageName,
   4490                         flags, filterCallingUid, userId);
   4491             }
   4492         }
   4493         return null;
   4494     }
   4495 
   4496     private String normalizePackageNameLPr(String packageName) {
   4497         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
   4498         return normalizedPackageName != null ? normalizedPackageName : packageName;
   4499     }
   4500 
   4501     @Override
   4502     public void deletePreloadsFileCache() {
   4503         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
   4504             throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
   4505         }
   4506         File dir = Environment.getDataPreloadsFileCacheDirectory();
   4507         Slog.i(TAG, "Deleting preloaded file cache " + dir);
   4508         FileUtils.deleteContents(dir);
   4509     }
   4510 
   4511     @Override
   4512     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
   4513             final int storageFlags, final IPackageDataObserver observer) {
   4514         mContext.enforceCallingOrSelfPermission(
   4515                 android.Manifest.permission.CLEAR_APP_CACHE, null);
   4516         mHandler.post(() -> {
   4517             boolean success = false;
   4518             try {
   4519                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
   4520                 success = true;
   4521             } catch (IOException e) {
   4522                 Slog.w(TAG, e);
   4523             }
   4524             if (observer != null) {
   4525                 try {
   4526                     observer.onRemoveCompleted(null, success);
   4527                 } catch (RemoteException e) {
   4528                     Slog.w(TAG, e);
   4529                 }
   4530             }
   4531         });
   4532     }
   4533 
   4534     @Override
   4535     public void freeStorage(final String volumeUuid, final long freeStorageSize,
   4536             final int storageFlags, final IntentSender pi) {
   4537         mContext.enforceCallingOrSelfPermission(
   4538                 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
   4539         mHandler.post(() -> {
   4540             boolean success = false;
   4541             try {
   4542                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
   4543                 success = true;
   4544             } catch (IOException e) {
   4545                 Slog.w(TAG, e);
   4546             }
   4547             if (pi != null) {
   4548                 try {
   4549                     pi.sendIntent(null, success ? 1 : 0, null, null, null);
   4550                 } catch (SendIntentException e) {
   4551                     Slog.w(TAG, e);
   4552                 }
   4553             }
   4554         });
   4555     }
   4556 
   4557     /**
   4558      * Blocking call to clear various types of cached data across the system
   4559      * until the requested bytes are available.
   4560      */
   4561     public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
   4562         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   4563         final File file = storage.findPathForUuid(volumeUuid);
   4564         if (file.getUsableSpace() >= bytes) return;
   4565 
   4566         if (ENABLE_FREE_CACHE_V2) {
   4567             final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
   4568                     volumeUuid);
   4569             final boolean aggressive = (storageFlags
   4570                     & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
   4571             final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
   4572 
   4573             // 1. Pre-flight to determine if we have any chance to succeed
   4574             // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
   4575             if (internalVolume && (aggressive || SystemProperties
   4576                     .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
   4577                 deletePreloadsFileCache();
   4578                 if (file.getUsableSpace() >= bytes) return;
   4579             }
   4580 
   4581             // 3. Consider parsed APK data (aggressive only)
   4582             if (internalVolume && aggressive) {
   4583                 FileUtils.deleteContents(mCacheDir);
   4584                 if (file.getUsableSpace() >= bytes) return;
   4585             }
   4586 
   4587             // 4. Consider cached app data (above quotas)
   4588             try {
   4589                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
   4590                         Installer.FLAG_FREE_CACHE_V2);
   4591             } catch (InstallerException ignored) {
   4592             }
   4593             if (file.getUsableSpace() >= bytes) return;
   4594 
   4595             // 5. Consider shared libraries with refcount=0 and age>min cache period
   4596             if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
   4597                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   4598                             Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
   4599                             DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
   4600                 return;
   4601             }
   4602 
   4603             // 6. Consider dexopt output (aggressive only)
   4604             // TODO: Implement
   4605 
   4606             // 7. Consider installed instant apps unused longer than min cache period
   4607             if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
   4608                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   4609                             Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
   4610                             InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
   4611                 return;
   4612             }
   4613 
   4614             // 8. Consider cached app data (below quotas)
   4615             try {
   4616                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
   4617                         Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
   4618             } catch (InstallerException ignored) {
   4619             }
   4620             if (file.getUsableSpace() >= bytes) return;
   4621 
   4622             // 9. Consider DropBox entries
   4623             // TODO: Implement
   4624 
   4625             // 10. Consider instant meta-data (uninstalled apps) older that min cache period
   4626             if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
   4627                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   4628                             Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
   4629                             InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
   4630                 return;
   4631             }
   4632         } else {
   4633             try {
   4634                 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
   4635             } catch (InstallerException ignored) {
   4636             }
   4637             if (file.getUsableSpace() >= bytes) return;
   4638         }
   4639 
   4640         throw new IOException("Failed to free " + bytes + " on storage device at " + file);
   4641     }
   4642 
   4643     private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
   4644             throws IOException {
   4645         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   4646         final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
   4647 
   4648         List<VersionedPackage> packagesToDelete = null;
   4649         final long now = System.currentTimeMillis();
   4650 
   4651         synchronized (mPackages) {
   4652             final int[] allUsers = sUserManager.getUserIds();
   4653             final int libCount = mSharedLibraries.size();
   4654             for (int i = 0; i < libCount; i++) {
   4655                 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
   4656                 if (versionedLib == null) {
   4657                     continue;
   4658                 }
   4659                 final int versionCount = versionedLib.size();
   4660                 for (int j = 0; j < versionCount; j++) {
   4661                     SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
   4662                     // Skip packages that are not static shared libs.
   4663                     if (!libInfo.isStatic()) {
   4664                         break;
   4665                     }
   4666                     // Important: We skip static shared libs used for some user since
   4667                     // in such a case we need to keep the APK on the device. The check for
   4668                     // a lib being used for any user is performed by the uninstall call.
   4669                     final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
   4670                     // Resolve the package name - we use synthetic package names internally
   4671                     final String internalPackageName = resolveInternalPackageNameLPr(
   4672                             declaringPackage.getPackageName(), declaringPackage.getVersionCode());
   4673                     final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
   4674                     // Skip unused static shared libs cached less than the min period
   4675                     // to prevent pruning a lib needed by a subsequently installed package.
   4676                     if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
   4677                         continue;
   4678                     }
   4679                     if (packagesToDelete == null) {
   4680                         packagesToDelete = new ArrayList<>();
   4681                     }
   4682                     packagesToDelete.add(new VersionedPackage(internalPackageName,
   4683                             declaringPackage.getVersionCode()));
   4684                 }
   4685             }
   4686         }
   4687 
   4688         if (packagesToDelete != null) {
   4689             final int packageCount = packagesToDelete.size();
   4690             for (int i = 0; i < packageCount; i++) {
   4691                 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
   4692                 // Delete the package synchronously (will fail of the lib used for any user).
   4693                 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
   4694                         UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
   4695                                 == PackageManager.DELETE_SUCCEEDED) {
   4696                     if (volume.getUsableSpace() >= neededSpace) {
   4697                         return true;
   4698                     }
   4699                 }
   4700             }
   4701         }
   4702 
   4703         return false;
   4704     }
   4705 
   4706     /**
   4707      * Update given flags based on encryption status of current user.
   4708      */
   4709     private int updateFlags(int flags, int userId) {
   4710         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
   4711                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
   4712             // Caller expressed an explicit opinion about what encryption
   4713             // aware/unaware components they want to see, so fall through and
   4714             // give them what they want
   4715         } else {
   4716             // Caller expressed no opinion, so match based on user state
   4717             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
   4718                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
   4719             } else {
   4720                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
   4721             }
   4722         }
   4723         return flags;
   4724     }
   4725 
   4726     private UserManagerInternal getUserManagerInternal() {
   4727         if (mUserManagerInternal == null) {
   4728             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
   4729         }
   4730         return mUserManagerInternal;
   4731     }
   4732 
   4733     private DeviceIdleController.LocalService getDeviceIdleController() {
   4734         if (mDeviceIdleController == null) {
   4735             mDeviceIdleController =
   4736                     LocalServices.getService(DeviceIdleController.LocalService.class);
   4737         }
   4738         return mDeviceIdleController;
   4739     }
   4740 
   4741     /**
   4742      * Update given flags when being used to request {@link PackageInfo}.
   4743      */
   4744     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
   4745         final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
   4746         boolean triaged = true;
   4747         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
   4748                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
   4749             // Caller is asking for component details, so they'd better be
   4750             // asking for specific encryption matching behavior, or be triaged
   4751             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
   4752                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
   4753                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
   4754                 triaged = false;
   4755             }
   4756         }
   4757         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
   4758                 | PackageManager.MATCH_SYSTEM_ONLY
   4759                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
   4760             triaged = false;
   4761         }
   4762         if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
   4763             enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
   4764                     "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
   4765                     + Debug.getCallers(5));
   4766         } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
   4767                 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
   4768             // If the caller wants all packages and has a restricted profile associated with it,
   4769             // then match all users. This is to make sure that launchers that need to access work
   4770             // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
   4771             // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
   4772             flags |= PackageManager.MATCH_ANY_USER;
   4773         }
   4774         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
   4775             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
   4776                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
   4777         }
   4778         return updateFlags(flags, userId);
   4779     }
   4780 
   4781     /**
   4782      * Update given flags when being used to request {@link ApplicationInfo}.
   4783      */
   4784     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
   4785         return updateFlagsForPackage(flags, userId, cookie);
   4786     }
   4787 
   4788     /**
   4789      * Update given flags when being used to request {@link ComponentInfo}.
   4790      */
   4791     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
   4792         if (cookie instanceof Intent) {
   4793             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
   4794                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
   4795             }
   4796         }
   4797 
   4798         boolean triaged = true;
   4799         // Caller is asking for component details, so they'd better be
   4800         // asking for specific encryption matching behavior, or be triaged
   4801         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
   4802                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
   4803                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
   4804             triaged = false;
   4805         }
   4806         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
   4807             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
   4808                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
   4809         }
   4810 
   4811         return updateFlags(flags, userId);
   4812     }
   4813 
   4814     /**
   4815      * Update given intent when being used to request {@link ResolveInfo}.
   4816      */
   4817     private Intent updateIntentForResolve(Intent intent) {
   4818         if (intent.getSelector() != null) {
   4819             intent = intent.getSelector();
   4820         }
   4821         if (DEBUG_PREFERRED) {
   4822             intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
   4823         }
   4824         return intent;
   4825     }
   4826 
   4827     /**
   4828      * Update given flags when being used to request {@link ResolveInfo}.
   4829      * <p>Instant apps are resolved specially, depending upon context. Minimally,
   4830      * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
   4831      * flag set. However, this flag is only honoured in three circumstances:
   4832      * <ul>
   4833      * <li>when called from a system process</li>
   4834      * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
   4835      * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
   4836      * action and a {@code android.intent.category.BROWSABLE} category</li>
   4837      * </ul>
   4838      */
   4839     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
   4840         return updateFlagsForResolve(flags, userId, intent, callingUid,
   4841                 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
   4842     }
   4843     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
   4844             boolean wantInstantApps) {
   4845         return updateFlagsForResolve(flags, userId, intent, callingUid,
   4846                 wantInstantApps, false /*onlyExposedExplicitly*/);
   4847     }
   4848     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
   4849             boolean wantInstantApps, boolean onlyExposedExplicitly) {
   4850         // Safe mode means we shouldn't match any third-party components
   4851         if (mSafeMode) {
   4852             flags |= PackageManager.MATCH_SYSTEM_ONLY;
   4853         }
   4854         if (getInstantAppPackageName(callingUid) != null) {
   4855             // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
   4856             if (onlyExposedExplicitly) {
   4857                 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
   4858             }
   4859             flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
   4860             flags |= PackageManager.MATCH_INSTANT;
   4861         } else {
   4862             final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
   4863             final boolean allowMatchInstant =
   4864                     (wantInstantApps
   4865                             && Intent.ACTION_VIEW.equals(intent.getAction())
   4866                             && hasWebURI(intent))
   4867                     || (wantMatchInstant && canViewInstantApps(callingUid, userId));
   4868             flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
   4869                     | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
   4870             if (!allowMatchInstant) {
   4871                 flags &= ~PackageManager.MATCH_INSTANT;
   4872             }
   4873         }
   4874         return updateFlagsForComponent(flags, userId, intent /*cookie*/);
   4875     }
   4876 
   4877     @Override
   4878     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
   4879         return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
   4880     }
   4881 
   4882     /**
   4883      * Important: The provided filterCallingUid is used exclusively to filter out activities
   4884      * that can be seen based on user state. It's typically the original caller uid prior
   4885      * to clearing. Because it can only be provided by trusted code, it's value can be
   4886      * trusted and will be used as-is; unlike userId which will be validated by this method.
   4887      */
   4888     private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
   4889             int filterCallingUid, int userId) {
   4890         if (!sUserManager.exists(userId)) return null;
   4891         flags = updateFlagsForComponent(flags, userId, component);
   4892         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   4893                 false /* requireFullPermission */, false /* checkShell */, "get activity info");
   4894         synchronized (mPackages) {
   4895             PackageParser.Activity a = mActivities.mActivities.get(component);
   4896 
   4897             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
   4898             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
   4899                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   4900                 if (ps == null) return null;
   4901                 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
   4902                     return null;
   4903                 }
   4904                 return PackageParser.generateActivityInfo(
   4905                         a, flags, ps.readUserState(userId), userId);
   4906             }
   4907             if (mResolveComponentName.equals(component)) {
   4908                 return PackageParser.generateActivityInfo(
   4909                         mResolveActivity, flags, new PackageUserState(), userId);
   4910             }
   4911         }
   4912         return null;
   4913     }
   4914 
   4915     @Override
   4916     public boolean activitySupportsIntent(ComponentName component, Intent intent,
   4917             String resolvedType) {
   4918         synchronized (mPackages) {
   4919             if (component.equals(mResolveComponentName)) {
   4920                 // The resolver supports EVERYTHING!
   4921                 return true;
   4922             }
   4923             final int callingUid = Binder.getCallingUid();
   4924             final int callingUserId = UserHandle.getUserId(callingUid);
   4925             PackageParser.Activity a = mActivities.mActivities.get(component);
   4926             if (a == null) {
   4927                 return false;
   4928             }
   4929             PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   4930             if (ps == null) {
   4931                 return false;
   4932             }
   4933             if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
   4934                 return false;
   4935             }
   4936             for (int i=0; i<a.intents.size(); i++) {
   4937                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
   4938                         intent.getData(), intent.getCategories(), TAG) >= 0) {
   4939                     return true;
   4940                 }
   4941             }
   4942             return false;
   4943         }
   4944     }
   4945 
   4946     @Override
   4947     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
   4948         if (!sUserManager.exists(userId)) return null;
   4949         final int callingUid = Binder.getCallingUid();
   4950         flags = updateFlagsForComponent(flags, userId, component);
   4951         enforceCrossUserPermission(callingUid, userId,
   4952                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
   4953         synchronized (mPackages) {
   4954             PackageParser.Activity a = mReceivers.mActivities.get(component);
   4955             if (DEBUG_PACKAGE_INFO) Log.v(
   4956                 TAG, "getReceiverInfo " + component + ": " + a);
   4957             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
   4958                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   4959                 if (ps == null) return null;
   4960                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
   4961                     return null;
   4962                 }
   4963                 return PackageParser.generateActivityInfo(
   4964                         a, flags, ps.readUserState(userId), userId);
   4965             }
   4966         }
   4967         return null;
   4968     }
   4969 
   4970     @Override
   4971     public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
   4972             int flags, int userId) {
   4973         if (!sUserManager.exists(userId)) return null;
   4974         Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
   4975         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   4976             return null;
   4977         }
   4978 
   4979         flags = updateFlagsForPackage(flags, userId, null);
   4980 
   4981         final boolean canSeeStaticLibraries =
   4982                 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
   4983                         == PERMISSION_GRANTED
   4984                 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
   4985                         == PERMISSION_GRANTED
   4986                 || canRequestPackageInstallsInternal(packageName,
   4987                         PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
   4988                         false  /* throwIfPermNotDeclared*/)
   4989                 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
   4990                         == PERMISSION_GRANTED;
   4991 
   4992         synchronized (mPackages) {
   4993             List<SharedLibraryInfo> result = null;
   4994 
   4995             final int libCount = mSharedLibraries.size();
   4996             for (int i = 0; i < libCount; i++) {
   4997                 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
   4998                 if (versionedLib == null) {
   4999                     continue;
   5000                 }
   5001 
   5002                 final int versionCount = versionedLib.size();
   5003                 for (int j = 0; j < versionCount; j++) {
   5004                     SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
   5005                     if (!canSeeStaticLibraries && libInfo.isStatic()) {
   5006                         break;
   5007                     }
   5008                     final long identity = Binder.clearCallingIdentity();
   5009                     try {
   5010                         PackageInfo packageInfo = getPackageInfoVersioned(
   5011                                 libInfo.getDeclaringPackage(), flags
   5012                                         | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
   5013                         if (packageInfo == null) {
   5014                             continue;
   5015                         }
   5016                     } finally {
   5017                         Binder.restoreCallingIdentity(identity);
   5018                     }
   5019 
   5020                     SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
   5021                             libInfo.getVersion(), libInfo.getType(),
   5022                             libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
   5023                             flags, userId));
   5024 
   5025                     if (result == null) {
   5026                         result = new ArrayList<>();
   5027                     }
   5028                     result.add(resLibInfo);
   5029                 }
   5030             }
   5031 
   5032             return result != null ? new ParceledListSlice<>(result) : null;
   5033         }
   5034     }
   5035 
   5036     private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
   5037             SharedLibraryInfo libInfo, int flags, int userId) {
   5038         List<VersionedPackage> versionedPackages = null;
   5039         final int packageCount = mSettings.mPackages.size();
   5040         for (int i = 0; i < packageCount; i++) {
   5041             PackageSetting ps = mSettings.mPackages.valueAt(i);
   5042 
   5043             if (ps == null) {
   5044                 continue;
   5045             }
   5046 
   5047             if (!ps.getUserState().get(userId).isAvailable(flags)) {
   5048                 continue;
   5049             }
   5050 
   5051             final String libName = libInfo.getName();
   5052             if (libInfo.isStatic()) {
   5053                 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
   5054                 if (libIdx < 0) {
   5055                     continue;
   5056                 }
   5057                 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
   5058                     continue;
   5059                 }
   5060                 if (versionedPackages == null) {
   5061                     versionedPackages = new ArrayList<>();
   5062                 }
   5063                 // If the dependent is a static shared lib, use the public package name
   5064                 String dependentPackageName = ps.name;
   5065                 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
   5066                     dependentPackageName = ps.pkg.manifestPackageName;
   5067                 }
   5068                 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
   5069             } else if (ps.pkg != null) {
   5070                 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
   5071                         || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
   5072                     if (versionedPackages == null) {
   5073                         versionedPackages = new ArrayList<>();
   5074                     }
   5075                     versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
   5076                 }
   5077             }
   5078         }
   5079 
   5080         return versionedPackages;
   5081     }
   5082 
   5083     @Override
   5084     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
   5085         if (!sUserManager.exists(userId)) return null;
   5086         final int callingUid = Binder.getCallingUid();
   5087         flags = updateFlagsForComponent(flags, userId, component);
   5088         enforceCrossUserPermission(callingUid, userId,
   5089                 false /* requireFullPermission */, false /* checkShell */, "get service info");
   5090         synchronized (mPackages) {
   5091             PackageParser.Service s = mServices.mServices.get(component);
   5092             if (DEBUG_PACKAGE_INFO) Log.v(
   5093                 TAG, "getServiceInfo " + component + ": " + s);
   5094             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
   5095                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   5096                 if (ps == null) return null;
   5097                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
   5098                     return null;
   5099                 }
   5100                 return PackageParser.generateServiceInfo(
   5101                         s, flags, ps.readUserState(userId), userId);
   5102             }
   5103         }
   5104         return null;
   5105     }
   5106 
   5107     @Override
   5108     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
   5109         if (!sUserManager.exists(userId)) return null;
   5110         final int callingUid = Binder.getCallingUid();
   5111         flags = updateFlagsForComponent(flags, userId, component);
   5112         enforceCrossUserPermission(callingUid, userId,
   5113                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
   5114         synchronized (mPackages) {
   5115             PackageParser.Provider p = mProviders.mProviders.get(component);
   5116             if (DEBUG_PACKAGE_INFO) Log.v(
   5117                 TAG, "getProviderInfo " + component + ": " + p);
   5118             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
   5119                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   5120                 if (ps == null) return null;
   5121                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
   5122                     return null;
   5123                 }
   5124                 return PackageParser.generateProviderInfo(
   5125                         p, flags, ps.readUserState(userId), userId);
   5126             }
   5127         }
   5128         return null;
   5129     }
   5130 
   5131     @Override
   5132     public String[] getSystemSharedLibraryNames() {
   5133         // allow instant applications
   5134         synchronized (mPackages) {
   5135             Set<String> libs = null;
   5136             final int libCount = mSharedLibraries.size();
   5137             for (int i = 0; i < libCount; i++) {
   5138                 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
   5139                 if (versionedLib == null) {
   5140                     continue;
   5141                 }
   5142                 final int versionCount = versionedLib.size();
   5143                 for (int j = 0; j < versionCount; j++) {
   5144                     SharedLibraryEntry libEntry = versionedLib.valueAt(j);
   5145                     if (!libEntry.info.isStatic()) {
   5146                         if (libs == null) {
   5147                             libs = new ArraySet<>();
   5148                         }
   5149                         libs.add(libEntry.info.getName());
   5150                         break;
   5151                     }
   5152                     PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
   5153                     if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
   5154                             UserHandle.getUserId(Binder.getCallingUid()),
   5155                             PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
   5156                         if (libs == null) {
   5157                             libs = new ArraySet<>();
   5158                         }
   5159                         libs.add(libEntry.info.getName());
   5160                         break;
   5161                     }
   5162                 }
   5163             }
   5164 
   5165             if (libs != null) {
   5166                 String[] libsArray = new String[libs.size()];
   5167                 libs.toArray(libsArray);
   5168                 return libsArray;
   5169             }
   5170 
   5171             return null;
   5172         }
   5173     }
   5174 
   5175     @Override
   5176     public @NonNull String getServicesSystemSharedLibraryPackageName() {
   5177         // allow instant applications
   5178         synchronized (mPackages) {
   5179             return mServicesSystemSharedLibraryPackageName;
   5180         }
   5181     }
   5182 
   5183     @Override
   5184     public @NonNull String getSharedSystemSharedLibraryPackageName() {
   5185         // allow instant applications
   5186         synchronized (mPackages) {
   5187             return mSharedSystemSharedLibraryPackageName;
   5188         }
   5189     }
   5190 
   5191     private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
   5192         for (int i = userList.length - 1; i >= 0; --i) {
   5193             final int userId = userList[i];
   5194             // don't add instant app to the list of updates
   5195             if (pkgSetting.getInstantApp(userId)) {
   5196                 continue;
   5197             }
   5198             SparseArray<String> changedPackages = mChangedPackages.get(userId);
   5199             if (changedPackages == null) {
   5200                 changedPackages = new SparseArray<>();
   5201                 mChangedPackages.put(userId, changedPackages);
   5202             }
   5203             Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
   5204             if (sequenceNumbers == null) {
   5205                 sequenceNumbers = new HashMap<>();
   5206                 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
   5207             }
   5208             final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
   5209             if (sequenceNumber != null) {
   5210                 changedPackages.remove(sequenceNumber);
   5211             }
   5212             changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
   5213             sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
   5214         }
   5215         mChangedPackagesSequenceNumber++;
   5216     }
   5217 
   5218     @Override
   5219     public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
   5220         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5221             return null;
   5222         }
   5223         synchronized (mPackages) {
   5224             if (sequenceNumber >= mChangedPackagesSequenceNumber) {
   5225                 return null;
   5226             }
   5227             final SparseArray<String> changedPackages = mChangedPackages.get(userId);
   5228             if (changedPackages == null) {
   5229                 return null;
   5230             }
   5231             final List<String> packageNames =
   5232                     new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
   5233             for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
   5234                 final String packageName = changedPackages.get(i);
   5235                 if (packageName != null) {
   5236                     packageNames.add(packageName);
   5237                 }
   5238             }
   5239             return packageNames.isEmpty()
   5240                     ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
   5241         }
   5242     }
   5243 
   5244     @Override
   5245     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
   5246         // allow instant applications
   5247         ArrayList<FeatureInfo> res;
   5248         synchronized (mAvailableFeatures) {
   5249             res = new ArrayList<>(mAvailableFeatures.size() + 1);
   5250             res.addAll(mAvailableFeatures.values());
   5251         }
   5252         final FeatureInfo fi = new FeatureInfo();
   5253         fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
   5254                 FeatureInfo.GL_ES_VERSION_UNDEFINED);
   5255         res.add(fi);
   5256 
   5257         return new ParceledListSlice<>(res);
   5258     }
   5259 
   5260     @Override
   5261     public boolean hasSystemFeature(String name, int version) {
   5262         // allow instant applications
   5263         synchronized (mAvailableFeatures) {
   5264             final FeatureInfo feat = mAvailableFeatures.get(name);
   5265             if (feat == null) {
   5266                 return false;
   5267             } else {
   5268                 return feat.version >= version;
   5269             }
   5270         }
   5271     }
   5272 
   5273     @Override
   5274     public int checkPermission(String permName, String pkgName, int userId) {
   5275         if (!sUserManager.exists(userId)) {
   5276             return PackageManager.PERMISSION_DENIED;
   5277         }
   5278         final int callingUid = Binder.getCallingUid();
   5279 
   5280         synchronized (mPackages) {
   5281             final PackageParser.Package p = mPackages.get(pkgName);
   5282             if (p != null && p.mExtras != null) {
   5283                 final PackageSetting ps = (PackageSetting) p.mExtras;
   5284                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   5285                     return PackageManager.PERMISSION_DENIED;
   5286                 }
   5287                 final boolean instantApp = ps.getInstantApp(userId);
   5288                 final PermissionsState permissionsState = ps.getPermissionsState();
   5289                 if (permissionsState.hasPermission(permName, userId)) {
   5290                     if (instantApp) {
   5291                         BasePermission bp = mSettings.mPermissions.get(permName);
   5292                         if (bp != null && bp.isInstant()) {
   5293                             return PackageManager.PERMISSION_GRANTED;
   5294                         }
   5295                     } else {
   5296                         return PackageManager.PERMISSION_GRANTED;
   5297                     }
   5298                 }
   5299                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
   5300                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
   5301                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
   5302                     return PackageManager.PERMISSION_GRANTED;
   5303                 }
   5304             }
   5305         }
   5306 
   5307         return PackageManager.PERMISSION_DENIED;
   5308     }
   5309 
   5310     @Override
   5311     public int checkUidPermission(String permName, int uid) {
   5312         final int callingUid = Binder.getCallingUid();
   5313         final int callingUserId = UserHandle.getUserId(callingUid);
   5314         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
   5315         final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
   5316         final int userId = UserHandle.getUserId(uid);
   5317         if (!sUserManager.exists(userId)) {
   5318             return PackageManager.PERMISSION_DENIED;
   5319         }
   5320 
   5321         synchronized (mPackages) {
   5322             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   5323             if (obj != null) {
   5324                 if (obj instanceof SharedUserSetting) {
   5325                     if (isCallerInstantApp) {
   5326                         return PackageManager.PERMISSION_DENIED;
   5327                     }
   5328                 } else if (obj instanceof PackageSetting) {
   5329                     final PackageSetting ps = (PackageSetting) obj;
   5330                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   5331                         return PackageManager.PERMISSION_DENIED;
   5332                     }
   5333                 }
   5334                 final SettingBase settingBase = (SettingBase) obj;
   5335                 final PermissionsState permissionsState = settingBase.getPermissionsState();
   5336                 if (permissionsState.hasPermission(permName, userId)) {
   5337                     if (isUidInstantApp) {
   5338                         BasePermission bp = mSettings.mPermissions.get(permName);
   5339                         if (bp != null && bp.isInstant()) {
   5340                             return PackageManager.PERMISSION_GRANTED;
   5341                         }
   5342                     } else {
   5343                         return PackageManager.PERMISSION_GRANTED;
   5344                     }
   5345                 }
   5346                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
   5347                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
   5348                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
   5349                     return PackageManager.PERMISSION_GRANTED;
   5350                 }
   5351             } else {
   5352                 ArraySet<String> perms = mSystemPermissions.get(uid);
   5353                 if (perms != null) {
   5354                     if (perms.contains(permName)) {
   5355                         return PackageManager.PERMISSION_GRANTED;
   5356                     }
   5357                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
   5358                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
   5359                         return PackageManager.PERMISSION_GRANTED;
   5360                     }
   5361                 }
   5362             }
   5363         }
   5364 
   5365         return PackageManager.PERMISSION_DENIED;
   5366     }
   5367 
   5368     @Override
   5369     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
   5370         if (UserHandle.getCallingUserId() != userId) {
   5371             mContext.enforceCallingPermission(
   5372                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   5373                     "isPermissionRevokedByPolicy for user " + userId);
   5374         }
   5375 
   5376         if (checkPermission(permission, packageName, userId)
   5377                 == PackageManager.PERMISSION_GRANTED) {
   5378             return false;
   5379         }
   5380 
   5381         final int callingUid = Binder.getCallingUid();
   5382         if (getInstantAppPackageName(callingUid) != null) {
   5383             if (!isCallerSameApp(packageName, callingUid)) {
   5384                 return false;
   5385             }
   5386         } else {
   5387             if (isInstantApp(packageName, userId)) {
   5388                 return false;
   5389             }
   5390         }
   5391 
   5392         final long identity = Binder.clearCallingIdentity();
   5393         try {
   5394             final int flags = getPermissionFlags(permission, packageName, userId);
   5395             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
   5396         } finally {
   5397             Binder.restoreCallingIdentity(identity);
   5398         }
   5399     }
   5400 
   5401     @Override
   5402     public String getPermissionControllerPackageName() {
   5403         synchronized (mPackages) {
   5404             return mRequiredInstallerPackage;
   5405         }
   5406     }
   5407 
   5408     /**
   5409      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
   5410      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
   5411      * @param checkShell whether to prevent shell from access if there's a debugging restriction
   5412      * @param message the message to log on security exception
   5413      */
   5414     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
   5415             boolean checkShell, String message) {
   5416         if (userId < 0) {
   5417             throw new IllegalArgumentException("Invalid userId " + userId);
   5418         }
   5419         if (checkShell) {
   5420             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
   5421         }
   5422         if (userId == UserHandle.getUserId(callingUid)) return;
   5423         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
   5424             if (requireFullPermission) {
   5425                 mContext.enforceCallingOrSelfPermission(
   5426                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
   5427             } else {
   5428                 try {
   5429                     mContext.enforceCallingOrSelfPermission(
   5430                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
   5431                 } catch (SecurityException se) {
   5432                     mContext.enforceCallingOrSelfPermission(
   5433                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
   5434                 }
   5435             }
   5436         }
   5437     }
   5438 
   5439     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
   5440         if (callingUid == Process.SHELL_UID) {
   5441             if (userHandle >= 0
   5442                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
   5443                 throw new SecurityException("Shell does not have permission to access user "
   5444                         + userHandle);
   5445             } else if (userHandle < 0) {
   5446                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
   5447                         + Debug.getCallers(3));
   5448             }
   5449         }
   5450     }
   5451 
   5452     private BasePermission findPermissionTreeLP(String permName) {
   5453         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
   5454             if (permName.startsWith(bp.name) &&
   5455                     permName.length() > bp.name.length() &&
   5456                     permName.charAt(bp.name.length()) == '.') {
   5457                 return bp;
   5458             }
   5459         }
   5460         return null;
   5461     }
   5462 
   5463     private BasePermission checkPermissionTreeLP(String permName) {
   5464         if (permName != null) {
   5465             BasePermission bp = findPermissionTreeLP(permName);
   5466             if (bp != null) {
   5467                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
   5468                     return bp;
   5469                 }
   5470                 throw new SecurityException("Calling uid "
   5471                         + Binder.getCallingUid()
   5472                         + " is not allowed to add to permission tree "
   5473                         + bp.name + " owned by uid " + bp.uid);
   5474             }
   5475         }
   5476         throw new SecurityException("No permission tree found for " + permName);
   5477     }
   5478 
   5479     static boolean compareStrings(CharSequence s1, CharSequence s2) {
   5480         if (s1 == null) {
   5481             return s2 == null;
   5482         }
   5483         if (s2 == null) {
   5484             return false;
   5485         }
   5486         if (s1.getClass() != s2.getClass()) {
   5487             return false;
   5488         }
   5489         return s1.equals(s2);
   5490     }
   5491 
   5492     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
   5493         if (pi1.icon != pi2.icon) return false;
   5494         if (pi1.logo != pi2.logo) return false;
   5495         if (pi1.protectionLevel != pi2.protectionLevel) return false;
   5496         if (!compareStrings(pi1.name, pi2.name)) return false;
   5497         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
   5498         // We'll take care of setting this one.
   5499         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
   5500         // These are not currently stored in settings.
   5501         //if (!compareStrings(pi1.group, pi2.group)) return false;
   5502         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
   5503         //if (pi1.labelRes != pi2.labelRes) return false;
   5504         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
   5505         return true;
   5506     }
   5507 
   5508     int permissionInfoFootprint(PermissionInfo info) {
   5509         int size = info.name.length();
   5510         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
   5511         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
   5512         return size;
   5513     }
   5514 
   5515     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
   5516         int size = 0;
   5517         for (BasePermission perm : mSettings.mPermissions.values()) {
   5518             if (perm.uid == tree.uid) {
   5519                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
   5520             }
   5521         }
   5522         return size;
   5523     }
   5524 
   5525     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
   5526         // We calculate the max size of permissions defined by this uid and throw
   5527         // if that plus the size of 'info' would exceed our stated maximum.
   5528         if (tree.uid != Process.SYSTEM_UID) {
   5529             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
   5530             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
   5531                 throw new SecurityException("Permission tree size cap exceeded");
   5532             }
   5533         }
   5534     }
   5535 
   5536     boolean addPermissionLocked(PermissionInfo info, boolean async) {
   5537         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5538             throw new SecurityException("Instant apps can't add permissions");
   5539         }
   5540         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
   5541             throw new SecurityException("Label must be specified in permission");
   5542         }
   5543         BasePermission tree = checkPermissionTreeLP(info.name);
   5544         BasePermission bp = mSettings.mPermissions.get(info.name);
   5545         boolean added = bp == null;
   5546         boolean changed = true;
   5547         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
   5548         if (added) {
   5549             enforcePermissionCapLocked(info, tree);
   5550             bp = new BasePermission(info.name, tree.sourcePackage,
   5551                     BasePermission.TYPE_DYNAMIC);
   5552         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
   5553             throw new SecurityException(
   5554                     "Not allowed to modify non-dynamic permission "
   5555                     + info.name);
   5556         } else {
   5557             if (bp.protectionLevel == fixedLevel
   5558                     && bp.perm.owner.equals(tree.perm.owner)
   5559                     && bp.uid == tree.uid
   5560                     && comparePermissionInfos(bp.perm.info, info)) {
   5561                 changed = false;
   5562             }
   5563         }
   5564         bp.protectionLevel = fixedLevel;
   5565         info = new PermissionInfo(info);
   5566         info.protectionLevel = fixedLevel;
   5567         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
   5568         bp.perm.info.packageName = tree.perm.info.packageName;
   5569         bp.uid = tree.uid;
   5570         if (added) {
   5571             mSettings.mPermissions.put(info.name, bp);
   5572         }
   5573         if (changed) {
   5574             if (!async) {
   5575                 mSettings.writeLPr();
   5576             } else {
   5577                 scheduleWriteSettingsLocked();
   5578             }
   5579         }
   5580         return added;
   5581     }
   5582 
   5583     @Override
   5584     public boolean addPermission(PermissionInfo info) {
   5585         synchronized (mPackages) {
   5586             return addPermissionLocked(info, false);
   5587         }
   5588     }
   5589 
   5590     @Override
   5591     public boolean addPermissionAsync(PermissionInfo info) {
   5592         synchronized (mPackages) {
   5593             return addPermissionLocked(info, true);
   5594         }
   5595     }
   5596 
   5597     @Override
   5598     public void removePermission(String name) {
   5599         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5600             throw new SecurityException("Instant applications don't have access to this method");
   5601         }
   5602         synchronized (mPackages) {
   5603             checkPermissionTreeLP(name);
   5604             BasePermission bp = mSettings.mPermissions.get(name);
   5605             if (bp != null) {
   5606                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
   5607                     throw new SecurityException(
   5608                             "Not allowed to modify non-dynamic permission "
   5609                             + name);
   5610                 }
   5611                 mSettings.mPermissions.remove(name);
   5612                 mSettings.writeLPr();
   5613             }
   5614         }
   5615     }
   5616 
   5617     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
   5618             PackageParser.Package pkg, BasePermission bp) {
   5619         int index = pkg.requestedPermissions.indexOf(bp.name);
   5620         if (index == -1) {
   5621             throw new SecurityException("Package " + pkg.packageName
   5622                     + " has not requested permission " + bp.name);
   5623         }
   5624         if (!bp.isRuntime() && !bp.isDevelopment()) {
   5625             throw new SecurityException("Permission " + bp.name
   5626                     + " is not a changeable permission type");
   5627         }
   5628     }
   5629 
   5630     @Override
   5631     public void grantRuntimePermission(String packageName, String name, final int userId) {
   5632         grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
   5633     }
   5634 
   5635     private void grantRuntimePermission(String packageName, String name, final int userId,
   5636             boolean overridePolicy) {
   5637         if (!sUserManager.exists(userId)) {
   5638             Log.e(TAG, "No such user:" + userId);
   5639             return;
   5640         }
   5641         final int callingUid = Binder.getCallingUid();
   5642 
   5643         mContext.enforceCallingOrSelfPermission(
   5644                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
   5645                 "grantRuntimePermission");
   5646 
   5647         enforceCrossUserPermission(callingUid, userId,
   5648                 true /* requireFullPermission */, true /* checkShell */,
   5649                 "grantRuntimePermission");
   5650 
   5651         final int uid;
   5652         final PackageSetting ps;
   5653 
   5654         synchronized (mPackages) {
   5655             final PackageParser.Package pkg = mPackages.get(packageName);
   5656             if (pkg == null) {
   5657                 throw new IllegalArgumentException("Unknown package: " + packageName);
   5658             }
   5659             final BasePermission bp = mSettings.mPermissions.get(name);
   5660             if (bp == null) {
   5661                 throw new IllegalArgumentException("Unknown permission: " + name);
   5662             }
   5663             ps = (PackageSetting) pkg.mExtras;
   5664             if (ps == null
   5665                     || filterAppAccessLPr(ps, callingUid, userId)) {
   5666                 throw new IllegalArgumentException("Unknown package: " + packageName);
   5667             }
   5668 
   5669             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
   5670 
   5671             // If a permission review is required for legacy apps we represent
   5672             // their permissions as always granted runtime ones since we need
   5673             // to keep the review required permission flag per user while an
   5674             // install permission's state is shared across all users.
   5675             if (mPermissionReviewRequired
   5676                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
   5677                     && bp.isRuntime()) {
   5678                 return;
   5679             }
   5680 
   5681             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
   5682 
   5683             final PermissionsState permissionsState = ps.getPermissionsState();
   5684 
   5685             final int flags = permissionsState.getPermissionFlags(name, userId);
   5686             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
   5687                 throw new SecurityException("Cannot grant system fixed permission "
   5688                         + name + " for package " + packageName);
   5689             }
   5690             if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
   5691                 throw new SecurityException("Cannot grant policy fixed permission "
   5692                         + name + " for package " + packageName);
   5693             }
   5694 
   5695             if (bp.isDevelopment()) {
   5696                 // Development permissions must be handled specially, since they are not
   5697                 // normal runtime permissions.  For now they apply to all users.
   5698                 if (permissionsState.grantInstallPermission(bp) !=
   5699                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
   5700                     scheduleWriteSettingsLocked();
   5701                 }
   5702                 return;
   5703             }
   5704 
   5705             if (ps.getInstantApp(userId) && !bp.isInstant()) {
   5706                 throw new SecurityException("Cannot grant non-ephemeral permission"
   5707                         + name + " for package " + packageName);
   5708             }
   5709 
   5710             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
   5711                 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
   5712                 return;
   5713             }
   5714 
   5715             final int result = permissionsState.grantRuntimePermission(bp, userId);
   5716             switch (result) {
   5717                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
   5718                     return;
   5719                 }
   5720 
   5721                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
   5722                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
   5723                     mHandler.post(new Runnable() {
   5724                         @Override
   5725                         public void run() {
   5726                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
   5727                         }
   5728                     });
   5729                 }
   5730                 break;
   5731             }
   5732 
   5733             if (bp.isRuntime()) {
   5734                 logPermissionGranted(mContext, name, packageName);
   5735             }
   5736 
   5737             mOnPermissionChangeListeners.onPermissionsChanged(uid);
   5738 
   5739             // Not critical if that is lost - app has to request again.
   5740             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   5741         }
   5742 
   5743         // Only need to do this if user is initialized. Otherwise it's a new user
   5744         // and there are no processes running as the user yet and there's no need
   5745         // to make an expensive call to remount processes for the changed permissions.
   5746         if (READ_EXTERNAL_STORAGE.equals(name)
   5747                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
   5748             final long token = Binder.clearCallingIdentity();
   5749             try {
   5750                 if (sUserManager.isInitialized(userId)) {
   5751                     StorageManagerInternal storageManagerInternal = LocalServices.getService(
   5752                             StorageManagerInternal.class);
   5753                     storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
   5754                 }
   5755             } finally {
   5756                 Binder.restoreCallingIdentity(token);
   5757             }
   5758         }
   5759     }
   5760 
   5761     @Override
   5762     public void revokeRuntimePermission(String packageName, String name, int userId) {
   5763         revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
   5764     }
   5765 
   5766     private void revokeRuntimePermission(String packageName, String name, int userId,
   5767             boolean overridePolicy) {
   5768         if (!sUserManager.exists(userId)) {
   5769             Log.e(TAG, "No such user:" + userId);
   5770             return;
   5771         }
   5772 
   5773         mContext.enforceCallingOrSelfPermission(
   5774                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
   5775                 "revokeRuntimePermission");
   5776 
   5777         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   5778                 true /* requireFullPermission */, true /* checkShell */,
   5779                 "revokeRuntimePermission");
   5780 
   5781         final int appId;
   5782 
   5783         synchronized (mPackages) {
   5784             final PackageParser.Package pkg = mPackages.get(packageName);
   5785             if (pkg == null) {
   5786                 throw new IllegalArgumentException("Unknown package: " + packageName);
   5787             }
   5788             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   5789             if (ps == null
   5790                     || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
   5791                 throw new IllegalArgumentException("Unknown package: " + packageName);
   5792             }
   5793             final BasePermission bp = mSettings.mPermissions.get(name);
   5794             if (bp == null) {
   5795                 throw new IllegalArgumentException("Unknown permission: " + name);
   5796             }
   5797 
   5798             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
   5799 
   5800             // If a permission review is required for legacy apps we represent
   5801             // their permissions as always granted runtime ones since we need
   5802             // to keep the review required permission flag per user while an
   5803             // install permission's state is shared across all users.
   5804             if (mPermissionReviewRequired
   5805                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
   5806                     && bp.isRuntime()) {
   5807                 return;
   5808             }
   5809 
   5810             final PermissionsState permissionsState = ps.getPermissionsState();
   5811 
   5812             final int flags = permissionsState.getPermissionFlags(name, userId);
   5813             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
   5814                 throw new SecurityException("Cannot revoke system fixed permission "
   5815                         + name + " for package " + packageName);
   5816             }
   5817             if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
   5818                 throw new SecurityException("Cannot revoke policy fixed permission "
   5819                         + name + " for package " + packageName);
   5820             }
   5821 
   5822             if (bp.isDevelopment()) {
   5823                 // Development permissions must be handled specially, since they are not
   5824                 // normal runtime permissions.  For now they apply to all users.
   5825                 if (permissionsState.revokeInstallPermission(bp) !=
   5826                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
   5827                     scheduleWriteSettingsLocked();
   5828                 }
   5829                 return;
   5830             }
   5831 
   5832             if (permissionsState.revokeRuntimePermission(bp, userId) ==
   5833                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
   5834                 return;
   5835             }
   5836 
   5837             if (bp.isRuntime()) {
   5838                 logPermissionRevoked(mContext, name, packageName);
   5839             }
   5840 
   5841             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
   5842 
   5843             // Critical, after this call app should never have the permission.
   5844             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
   5845 
   5846             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
   5847         }
   5848 
   5849         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
   5850     }
   5851 
   5852     /**
   5853      * Get the first event id for the permission.
   5854      *
   5855      * <p>There are four events for each permission: <ul>
   5856      *     <li>Request permission: first id + 0</li>
   5857      *     <li>Grant permission: first id + 1</li>
   5858      *     <li>Request for permission denied: first id + 2</li>
   5859      *     <li>Revoke permission: first id + 3</li>
   5860      * </ul></p>
   5861      *
   5862      * @param name name of the permission
   5863      *
   5864      * @return The first event id for the permission
   5865      */
   5866     private static int getBaseEventId(@NonNull String name) {
   5867         int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
   5868 
   5869         if (eventIdIndex == -1) {
   5870             if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
   5871                     || Build.IS_USER) {
   5872                 Log.i(TAG, "Unknown permission " + name);
   5873 
   5874                 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
   5875             } else {
   5876                 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
   5877                 //
   5878                 // Also update
   5879                 // - EventLogger#ALL_DANGEROUS_PERMISSIONS
   5880                 // - metrics_constants.proto
   5881                 throw new IllegalStateException("Unknown permission " + name);
   5882             }
   5883         }
   5884 
   5885         return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
   5886     }
   5887 
   5888     /**
   5889      * Log that a permission was revoked.
   5890      *
   5891      * @param context Context of the caller
   5892      * @param name name of the permission
   5893      * @param packageName package permission if for
   5894      */
   5895     private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
   5896             @NonNull String packageName) {
   5897         MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
   5898     }
   5899 
   5900     /**
   5901      * Log that a permission request was granted.
   5902      *
   5903      * @param context Context of the caller
   5904      * @param name name of the permission
   5905      * @param packageName package permission if for
   5906      */
   5907     private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
   5908             @NonNull String packageName) {
   5909         MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
   5910     }
   5911 
   5912     @Override
   5913     public void resetRuntimePermissions() {
   5914         mContext.enforceCallingOrSelfPermission(
   5915                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
   5916                 "revokeRuntimePermission");
   5917 
   5918         int callingUid = Binder.getCallingUid();
   5919         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
   5920             mContext.enforceCallingOrSelfPermission(
   5921                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   5922                     "resetRuntimePermissions");
   5923         }
   5924 
   5925         synchronized (mPackages) {
   5926             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
   5927             for (int userId : UserManagerService.getInstance().getUserIds()) {
   5928                 final int packageCount = mPackages.size();
   5929                 for (int i = 0; i < packageCount; i++) {
   5930                     PackageParser.Package pkg = mPackages.valueAt(i);
   5931                     if (!(pkg.mExtras instanceof PackageSetting)) {
   5932                         continue;
   5933                     }
   5934                     PackageSetting ps = (PackageSetting) pkg.mExtras;
   5935                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
   5936                 }
   5937             }
   5938         }
   5939     }
   5940 
   5941     @Override
   5942     public int getPermissionFlags(String name, String packageName, int userId) {
   5943         if (!sUserManager.exists(userId)) {
   5944             return 0;
   5945         }
   5946 
   5947         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
   5948 
   5949         final int callingUid = Binder.getCallingUid();
   5950         enforceCrossUserPermission(callingUid, userId,
   5951                 true /* requireFullPermission */, false /* checkShell */,
   5952                 "getPermissionFlags");
   5953 
   5954         synchronized (mPackages) {
   5955             final PackageParser.Package pkg = mPackages.get(packageName);
   5956             if (pkg == null) {
   5957                 return 0;
   5958             }
   5959             final BasePermission bp = mSettings.mPermissions.get(name);
   5960             if (bp == null) {
   5961                 return 0;
   5962             }
   5963             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   5964             if (ps == null
   5965                     || filterAppAccessLPr(ps, callingUid, userId)) {
   5966                 return 0;
   5967             }
   5968             PermissionsState permissionsState = ps.getPermissionsState();
   5969             return permissionsState.getPermissionFlags(name, userId);
   5970         }
   5971     }
   5972 
   5973     @Override
   5974     public void updatePermissionFlags(String name, String packageName, int flagMask,
   5975             int flagValues, int userId) {
   5976         if (!sUserManager.exists(userId)) {
   5977             return;
   5978         }
   5979 
   5980         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
   5981 
   5982         final int callingUid = Binder.getCallingUid();
   5983         enforceCrossUserPermission(callingUid, userId,
   5984                 true /* requireFullPermission */, true /* checkShell */,
   5985                 "updatePermissionFlags");
   5986 
   5987         // Only the system can change these flags and nothing else.
   5988         if (getCallingUid() != Process.SYSTEM_UID) {
   5989             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
   5990             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
   5991             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
   5992             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
   5993             flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
   5994         }
   5995 
   5996         synchronized (mPackages) {
   5997             final PackageParser.Package pkg = mPackages.get(packageName);
   5998             if (pkg == null) {
   5999                 throw new IllegalArgumentException("Unknown package: " + packageName);
   6000             }
   6001             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   6002             if (ps == null
   6003                     || filterAppAccessLPr(ps, callingUid, userId)) {
   6004                 throw new IllegalArgumentException("Unknown package: " + packageName);
   6005             }
   6006 
   6007             final BasePermission bp = mSettings.mPermissions.get(name);
   6008             if (bp == null) {
   6009                 throw new IllegalArgumentException("Unknown permission: " + name);
   6010             }
   6011 
   6012             PermissionsState permissionsState = ps.getPermissionsState();
   6013 
   6014             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
   6015 
   6016             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
   6017                 // Install and runtime permissions are stored in different places,
   6018                 // so figure out what permission changed and persist the change.
   6019                 if (permissionsState.getInstallPermissionState(name) != null) {
   6020                     scheduleWriteSettingsLocked();
   6021                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
   6022                         || hadState) {
   6023                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   6024                 }
   6025             }
   6026         }
   6027     }
   6028 
   6029     /**
   6030      * Update the permission flags for all packages and runtime permissions of a user in order
   6031      * to allow device or profile owner to remove POLICY_FIXED.
   6032      */
   6033     @Override
   6034     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
   6035         if (!sUserManager.exists(userId)) {
   6036             return;
   6037         }
   6038 
   6039         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
   6040 
   6041         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   6042                 true /* requireFullPermission */, true /* checkShell */,
   6043                 "updatePermissionFlagsForAllApps");
   6044 
   6045         // Only the system can change system fixed flags.
   6046         if (getCallingUid() != Process.SYSTEM_UID) {
   6047             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
   6048             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
   6049         }
   6050 
   6051         synchronized (mPackages) {
   6052             boolean changed = false;
   6053             final int packageCount = mPackages.size();
   6054             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
   6055                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
   6056                 final PackageSetting ps = (PackageSetting) pkg.mExtras;
   6057                 if (ps == null) {
   6058                     continue;
   6059                 }
   6060                 PermissionsState permissionsState = ps.getPermissionsState();
   6061                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
   6062                         userId, flagMask, flagValues);
   6063             }
   6064             if (changed) {
   6065                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   6066             }
   6067         }
   6068     }
   6069 
   6070     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
   6071         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
   6072                 != PackageManager.PERMISSION_GRANTED
   6073             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
   6074                 != PackageManager.PERMISSION_GRANTED) {
   6075             throw new SecurityException(message + " requires "
   6076                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
   6077                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
   6078         }
   6079     }
   6080 
   6081     @Override
   6082     public boolean shouldShowRequestPermissionRationale(String permissionName,
   6083             String packageName, int userId) {
   6084         if (UserHandle.getCallingUserId() != userId) {
   6085             mContext.enforceCallingPermission(
   6086                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   6087                     "canShowRequestPermissionRationale for user " + userId);
   6088         }
   6089 
   6090         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
   6091         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
   6092             return false;
   6093         }
   6094 
   6095         if (checkPermission(permissionName, packageName, userId)
   6096                 == PackageManager.PERMISSION_GRANTED) {
   6097             return false;
   6098         }
   6099 
   6100         final int flags;
   6101 
   6102         final long identity = Binder.clearCallingIdentity();
   6103         try {
   6104             flags = getPermissionFlags(permissionName,
   6105                     packageName, userId);
   6106         } finally {
   6107             Binder.restoreCallingIdentity(identity);
   6108         }
   6109 
   6110         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
   6111                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
   6112                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
   6113 
   6114         if ((flags & fixedFlags) != 0) {
   6115             return false;
   6116         }
   6117 
   6118         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
   6119     }
   6120 
   6121     @Override
   6122     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
   6123         mContext.enforceCallingOrSelfPermission(
   6124                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
   6125                 "addOnPermissionsChangeListener");
   6126 
   6127         synchronized (mPackages) {
   6128             mOnPermissionChangeListeners.addListenerLocked(listener);
   6129         }
   6130     }
   6131 
   6132     @Override
   6133     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
   6134         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6135             throw new SecurityException("Instant applications don't have access to this method");
   6136         }
   6137         synchronized (mPackages) {
   6138             mOnPermissionChangeListeners.removeListenerLocked(listener);
   6139         }
   6140     }
   6141 
   6142     @Override
   6143     public boolean isProtectedBroadcast(String actionName) {
   6144         // allow instant applications
   6145         synchronized (mProtectedBroadcasts) {
   6146             if (mProtectedBroadcasts.contains(actionName)) {
   6147                 return true;
   6148             } else if (actionName != null) {
   6149                 // TODO: remove these terrible hacks
   6150                 if (actionName.startsWith("android.net.netmon.lingerExpired")
   6151                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
   6152                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
   6153                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
   6154                     return true;
   6155                 }
   6156             }
   6157         }
   6158         return false;
   6159     }
   6160 
   6161     @Override
   6162     public int checkSignatures(String pkg1, String pkg2) {
   6163         synchronized (mPackages) {
   6164             final PackageParser.Package p1 = mPackages.get(pkg1);
   6165             final PackageParser.Package p2 = mPackages.get(pkg2);
   6166             if (p1 == null || p1.mExtras == null
   6167                     || p2 == null || p2.mExtras == null) {
   6168                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6169             }
   6170             final int callingUid = Binder.getCallingUid();
   6171             final int callingUserId = UserHandle.getUserId(callingUid);
   6172             final PackageSetting ps1 = (PackageSetting) p1.mExtras;
   6173             final PackageSetting ps2 = (PackageSetting) p2.mExtras;
   6174             if (filterAppAccessLPr(ps1, callingUid, callingUserId)
   6175                     || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
   6176                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6177             }
   6178             return compareSignatures(p1.mSignatures, p2.mSignatures);
   6179         }
   6180     }
   6181 
   6182     @Override
   6183     public int checkUidSignatures(int uid1, int uid2) {
   6184         final int callingUid = Binder.getCallingUid();
   6185         final int callingUserId = UserHandle.getUserId(callingUid);
   6186         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
   6187         // Map to base uids.
   6188         uid1 = UserHandle.getAppId(uid1);
   6189         uid2 = UserHandle.getAppId(uid2);
   6190         // reader
   6191         synchronized (mPackages) {
   6192             Signature[] s1;
   6193             Signature[] s2;
   6194             Object obj = mSettings.getUserIdLPr(uid1);
   6195             if (obj != null) {
   6196                 if (obj instanceof SharedUserSetting) {
   6197                     if (isCallerInstantApp) {
   6198                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6199                     }
   6200                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
   6201                 } else if (obj instanceof PackageSetting) {
   6202                     final PackageSetting ps = (PackageSetting) obj;
   6203                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   6204                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6205                     }
   6206                     s1 = ps.signatures.mSignatures;
   6207                 } else {
   6208                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6209                 }
   6210             } else {
   6211                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6212             }
   6213             obj = mSettings.getUserIdLPr(uid2);
   6214             if (obj != null) {
   6215                 if (obj instanceof SharedUserSetting) {
   6216                     if (isCallerInstantApp) {
   6217                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6218                     }
   6219                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
   6220                 } else if (obj instanceof PackageSetting) {
   6221                     final PackageSetting ps = (PackageSetting) obj;
   6222                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   6223                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6224                     }
   6225                     s2 = ps.signatures.mSignatures;
   6226                 } else {
   6227                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6228                 }
   6229             } else {
   6230                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   6231             }
   6232             return compareSignatures(s1, s2);
   6233         }
   6234     }
   6235 
   6236     /**
   6237      * This method should typically only be used when granting or revoking
   6238      * permissions, since the app may immediately restart after this call.
   6239      * <p>
   6240      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
   6241      * guard your work against the app being relaunched.
   6242      */
   6243     private void killUid(int appId, int userId, String reason) {
   6244         final long identity = Binder.clearCallingIdentity();
   6245         try {
   6246             IActivityManager am = ActivityManager.getService();
   6247             if (am != null) {
   6248                 try {
   6249                     am.killUid(appId, userId, reason);
   6250                 } catch (RemoteException e) {
   6251                     /* ignore - same process */
   6252                 }
   6253             }
   6254         } finally {
   6255             Binder.restoreCallingIdentity(identity);
   6256         }
   6257     }
   6258 
   6259     /**
   6260      * Compares two sets of signatures. Returns:
   6261      * <br />
   6262      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
   6263      * <br />
   6264      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
   6265      * <br />
   6266      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
   6267      * <br />
   6268      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
   6269      * <br />
   6270      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
   6271      */
   6272     static int compareSignatures(Signature[] s1, Signature[] s2) {
   6273         if (s1 == null) {
   6274             return s2 == null
   6275                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
   6276                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
   6277         }
   6278 
   6279         if (s2 == null) {
   6280             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
   6281         }
   6282 
   6283         if (s1.length != s2.length) {
   6284             return PackageManager.SIGNATURE_NO_MATCH;
   6285         }
   6286 
   6287         // Since both signature sets are of size 1, we can compare without HashSets.
   6288         if (s1.length == 1) {
   6289             return s1[0].equals(s2[0]) ?
   6290                     PackageManager.SIGNATURE_MATCH :
   6291                     PackageManager.SIGNATURE_NO_MATCH;
   6292         }
   6293 
   6294         ArraySet<Signature> set1 = new ArraySet<Signature>();
   6295         for (Signature sig : s1) {
   6296             set1.add(sig);
   6297         }
   6298         ArraySet<Signature> set2 = new ArraySet<Signature>();
   6299         for (Signature sig : s2) {
   6300             set2.add(sig);
   6301         }
   6302         // Make sure s2 contains all signatures in s1.
   6303         if (set1.equals(set2)) {
   6304             return PackageManager.SIGNATURE_MATCH;
   6305         }
   6306         return PackageManager.SIGNATURE_NO_MATCH;
   6307     }
   6308 
   6309     /**
   6310      * If the database version for this type of package (internal storage or
   6311      * external storage) is less than the version where package signatures
   6312      * were updated, return true.
   6313      */
   6314     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
   6315         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
   6316         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
   6317     }
   6318 
   6319     /**
   6320      * Used for backward compatibility to make sure any packages with
   6321      * certificate chains get upgraded to the new style. {@code existingSigs}
   6322      * will be in the old format (since they were stored on disk from before the
   6323      * system upgrade) and {@code scannedSigs} will be in the newer format.
   6324      */
   6325     private int compareSignaturesCompat(PackageSignatures existingSigs,
   6326             PackageParser.Package scannedPkg) {
   6327         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
   6328             return PackageManager.SIGNATURE_NO_MATCH;
   6329         }
   6330 
   6331         ArraySet<Signature> existingSet = new ArraySet<Signature>();
   6332         for (Signature sig : existingSigs.mSignatures) {
   6333             existingSet.add(sig);
   6334         }
   6335         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
   6336         for (Signature sig : scannedPkg.mSignatures) {
   6337             try {
   6338                 Signature[] chainSignatures = sig.getChainSignatures();
   6339                 for (Signature chainSig : chainSignatures) {
   6340                     scannedCompatSet.add(chainSig);
   6341                 }
   6342             } catch (CertificateEncodingException e) {
   6343                 scannedCompatSet.add(sig);
   6344             }
   6345         }
   6346         /*
   6347          * Make sure the expanded scanned set contains all signatures in the
   6348          * existing one.
   6349          */
   6350         if (scannedCompatSet.equals(existingSet)) {
   6351             // Migrate the old signatures to the new scheme.
   6352             existingSigs.assignSignatures(scannedPkg.mSignatures);
   6353             // The new KeySets will be re-added later in the scanning process.
   6354             synchronized (mPackages) {
   6355                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
   6356             }
   6357             return PackageManager.SIGNATURE_MATCH;
   6358         }
   6359         return PackageManager.SIGNATURE_NO_MATCH;
   6360     }
   6361 
   6362     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
   6363         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
   6364         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
   6365     }
   6366 
   6367     private int compareSignaturesRecover(PackageSignatures existingSigs,
   6368             PackageParser.Package scannedPkg) {
   6369         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
   6370             return PackageManager.SIGNATURE_NO_MATCH;
   6371         }
   6372 
   6373         String msg = null;
   6374         try {
   6375             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
   6376                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
   6377                         + scannedPkg.packageName);
   6378                 return PackageManager.SIGNATURE_MATCH;
   6379             }
   6380         } catch (CertificateException e) {
   6381             msg = e.getMessage();
   6382         }
   6383 
   6384         logCriticalInfo(Log.INFO,
   6385                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
   6386         return PackageManager.SIGNATURE_NO_MATCH;
   6387     }
   6388 
   6389     @Override
   6390     public List<String> getAllPackages() {
   6391         final int callingUid = Binder.getCallingUid();
   6392         final int callingUserId = UserHandle.getUserId(callingUid);
   6393         synchronized (mPackages) {
   6394             if (canViewInstantApps(callingUid, callingUserId)) {
   6395                 return new ArrayList<String>(mPackages.keySet());
   6396             }
   6397             final String instantAppPkgName = getInstantAppPackageName(callingUid);
   6398             final List<String> result = new ArrayList<>();
   6399             if (instantAppPkgName != null) {
   6400                 // caller is an instant application; filter unexposed applications
   6401                 for (PackageParser.Package pkg : mPackages.values()) {
   6402                     if (!pkg.visibleToInstantApps) {
   6403                         continue;
   6404                     }
   6405                     result.add(pkg.packageName);
   6406                 }
   6407             } else {
   6408                 // caller is a normal application; filter instant applications
   6409                 for (PackageParser.Package pkg : mPackages.values()) {
   6410                     final PackageSetting ps =
   6411                             pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
   6412                     if (ps != null
   6413                             && ps.getInstantApp(callingUserId)
   6414                             && !mInstantAppRegistry.isInstantAccessGranted(
   6415                                     callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
   6416                         continue;
   6417                     }
   6418                     result.add(pkg.packageName);
   6419                 }
   6420             }
   6421             return result;
   6422         }
   6423     }
   6424 
   6425     @Override
   6426     public String[] getPackagesForUid(int uid) {
   6427         final int callingUid = Binder.getCallingUid();
   6428         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
   6429         final int userId = UserHandle.getUserId(uid);
   6430         uid = UserHandle.getAppId(uid);
   6431         // reader
   6432         synchronized (mPackages) {
   6433             Object obj = mSettings.getUserIdLPr(uid);
   6434             if (obj instanceof SharedUserSetting) {
   6435                 if (isCallerInstantApp) {
   6436                     return null;
   6437                 }
   6438                 final SharedUserSetting sus = (SharedUserSetting) obj;
   6439                 final int N = sus.packages.size();
   6440                 String[] res = new String[N];
   6441                 final Iterator<PackageSetting> it = sus.packages.iterator();
   6442                 int i = 0;
   6443                 while (it.hasNext()) {
   6444                     PackageSetting ps = it.next();
   6445                     if (ps.getInstalled(userId)) {
   6446                         res[i++] = ps.name;
   6447                     } else {
   6448                         res = ArrayUtils.removeElement(String.class, res, res[i]);
   6449                     }
   6450                 }
   6451                 return res;
   6452             } else if (obj instanceof PackageSetting) {
   6453                 final PackageSetting ps = (PackageSetting) obj;
   6454                 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
   6455                     return new String[]{ps.name};
   6456                 }
   6457             }
   6458         }
   6459         return null;
   6460     }
   6461 
   6462     @Override
   6463     public String getNameForUid(int uid) {
   6464         final int callingUid = Binder.getCallingUid();
   6465         if (getInstantAppPackageName(callingUid) != null) {
   6466             return null;
   6467         }
   6468         synchronized (mPackages) {
   6469             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   6470             if (obj instanceof SharedUserSetting) {
   6471                 final SharedUserSetting sus = (SharedUserSetting) obj;
   6472                 return sus.name + ":" + sus.userId;
   6473             } else if (obj instanceof PackageSetting) {
   6474                 final PackageSetting ps = (PackageSetting) obj;
   6475                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   6476                     return null;
   6477                 }
   6478                 return ps.name;
   6479             }
   6480             return null;
   6481         }
   6482     }
   6483 
   6484     @Override
   6485     public String[] getNamesForUids(int[] uids) {
   6486         if (uids == null || uids.length == 0) {
   6487             return null;
   6488         }
   6489         final int callingUid = Binder.getCallingUid();
   6490         if (getInstantAppPackageName(callingUid) != null) {
   6491             return null;
   6492         }
   6493         final String[] names = new String[uids.length];
   6494         synchronized (mPackages) {
   6495             for (int i = uids.length - 1; i >= 0; i--) {
   6496                 final int uid = uids[i];
   6497                 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   6498                 if (obj instanceof SharedUserSetting) {
   6499                     final SharedUserSetting sus = (SharedUserSetting) obj;
   6500                     names[i] = "shared:" + sus.name;
   6501                 } else if (obj instanceof PackageSetting) {
   6502                     final PackageSetting ps = (PackageSetting) obj;
   6503                     if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   6504                         names[i] = null;
   6505                     } else {
   6506                         names[i] = ps.name;
   6507                     }
   6508                 } else {
   6509                     names[i] = null;
   6510                 }
   6511             }
   6512         }
   6513         return names;
   6514     }
   6515 
   6516     @Override
   6517     public int getUidForSharedUser(String sharedUserName) {
   6518         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6519             return -1;
   6520         }
   6521         if (sharedUserName == null) {
   6522             return -1;
   6523         }
   6524         // reader
   6525         synchronized (mPackages) {
   6526             SharedUserSetting suid;
   6527             try {
   6528                 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
   6529                 if (suid != null) {
   6530                     return suid.userId;
   6531                 }
   6532             } catch (PackageManagerException ignore) {
   6533                 // can't happen, but, still need to catch it
   6534             }
   6535             return -1;
   6536         }
   6537     }
   6538 
   6539     @Override
   6540     public int getFlagsForUid(int uid) {
   6541         final int callingUid = Binder.getCallingUid();
   6542         if (getInstantAppPackageName(callingUid) != null) {
   6543             return 0;
   6544         }
   6545         synchronized (mPackages) {
   6546             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   6547             if (obj instanceof SharedUserSetting) {
   6548                 final SharedUserSetting sus = (SharedUserSetting) obj;
   6549                 return sus.pkgFlags;
   6550             } else if (obj instanceof PackageSetting) {
   6551                 final PackageSetting ps = (PackageSetting) obj;
   6552                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   6553                     return 0;
   6554                 }
   6555                 return ps.pkgFlags;
   6556             }
   6557         }
   6558         return 0;
   6559     }
   6560 
   6561     @Override
   6562     public int getPrivateFlagsForUid(int uid) {
   6563         final int callingUid = Binder.getCallingUid();
   6564         if (getInstantAppPackageName(callingUid) != null) {
   6565             return 0;
   6566         }
   6567         synchronized (mPackages) {
   6568             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   6569             if (obj instanceof SharedUserSetting) {
   6570                 final SharedUserSetting sus = (SharedUserSetting) obj;
   6571                 return sus.pkgPrivateFlags;
   6572             } else if (obj instanceof PackageSetting) {
   6573                 final PackageSetting ps = (PackageSetting) obj;
   6574                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   6575                     return 0;
   6576                 }
   6577                 return ps.pkgPrivateFlags;
   6578             }
   6579         }
   6580         return 0;
   6581     }
   6582 
   6583     @Override
   6584     public boolean isUidPrivileged(int uid) {
   6585         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6586             return false;
   6587         }
   6588         uid = UserHandle.getAppId(uid);
   6589         // reader
   6590         synchronized (mPackages) {
   6591             Object obj = mSettings.getUserIdLPr(uid);
   6592             if (obj instanceof SharedUserSetting) {
   6593                 final SharedUserSetting sus = (SharedUserSetting) obj;
   6594                 final Iterator<PackageSetting> it = sus.packages.iterator();
   6595                 while (it.hasNext()) {
   6596                     if (it.next().isPrivileged()) {
   6597                         return true;
   6598                     }
   6599                 }
   6600             } else if (obj instanceof PackageSetting) {
   6601                 final PackageSetting ps = (PackageSetting) obj;
   6602                 return ps.isPrivileged();
   6603             }
   6604         }
   6605         return false;
   6606     }
   6607 
   6608     @Override
   6609     public String[] getAppOpPermissionPackages(String permissionName) {
   6610         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6611             return null;
   6612         }
   6613         synchronized (mPackages) {
   6614             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
   6615             if (pkgs == null) {
   6616                 return null;
   6617             }
   6618             return pkgs.toArray(new String[pkgs.size()]);
   6619         }
   6620     }
   6621 
   6622     @Override
   6623     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
   6624             int flags, int userId) {
   6625         return resolveIntentInternal(
   6626                 intent, resolvedType, flags, userId, false /*includeInstantApps*/);
   6627     }
   6628 
   6629     private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
   6630             int flags, int userId, boolean resolveForStart) {
   6631         try {
   6632             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
   6633 
   6634             if (!sUserManager.exists(userId)) return null;
   6635             final int callingUid = Binder.getCallingUid();
   6636             flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
   6637             enforceCrossUserPermission(callingUid, userId,
   6638                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
   6639 
   6640             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
   6641             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
   6642                     flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
   6643             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   6644 
   6645             final ResolveInfo bestChoice =
   6646                     chooseBestActivity(intent, resolvedType, flags, query, userId);
   6647             return bestChoice;
   6648         } finally {
   6649             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   6650         }
   6651     }
   6652 
   6653     @Override
   6654     public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
   6655         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
   6656             throw new SecurityException(
   6657                     "findPersistentPreferredActivity can only be run by the system");
   6658         }
   6659         if (!sUserManager.exists(userId)) {
   6660             return null;
   6661         }
   6662         final int callingUid = Binder.getCallingUid();
   6663         intent = updateIntentForResolve(intent);
   6664         final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
   6665         final int flags = updateFlagsForResolve(
   6666                 0, userId, intent, callingUid, false /*includeInstantApps*/);
   6667         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
   6668                 userId);
   6669         synchronized (mPackages) {
   6670             return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
   6671                     userId);
   6672         }
   6673     }
   6674 
   6675     @Override
   6676     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
   6677             IntentFilter filter, int match, ComponentName activity) {
   6678         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6679             return;
   6680         }
   6681         final int userId = UserHandle.getCallingUserId();
   6682         if (DEBUG_PREFERRED) {
   6683             Log.v(TAG, "setLastChosenActivity intent=" + intent
   6684                 + " resolvedType=" + resolvedType
   6685                 + " flags=" + flags
   6686                 + " filter=" + filter
   6687                 + " match=" + match
   6688                 + " activity=" + activity);
   6689             filter.dump(new PrintStreamPrinter(System.out), "    ");
   6690         }
   6691         intent.setComponent(null);
   6692         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
   6693                 userId);
   6694         // Find any earlier preferred or last chosen entries and nuke them
   6695         findPreferredActivity(intent, resolvedType,
   6696                 flags, query, 0, false, true, false, userId);
   6697         // Add the new activity as the last chosen for this filter
   6698         addPreferredActivityInternal(filter, match, null, activity, false, userId,
   6699                 "Setting last chosen");
   6700     }
   6701 
   6702     @Override
   6703     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
   6704         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6705             return null;
   6706         }
   6707         final int userId = UserHandle.getCallingUserId();
   6708         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
   6709         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
   6710                 userId);
   6711         return findPreferredActivity(intent, resolvedType, flags, query, 0,
   6712                 false, false, false, userId);
   6713     }
   6714 
   6715     /**
   6716      * Returns whether or not instant apps have been disabled remotely.
   6717      */
   6718     private boolean isEphemeralDisabled() {
   6719         return mEphemeralAppsDisabled;
   6720     }
   6721 
   6722     private boolean isInstantAppAllowed(
   6723             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
   6724             boolean skipPackageCheck) {
   6725         if (mInstantAppResolverConnection == null) {
   6726             return false;
   6727         }
   6728         if (mInstantAppInstallerActivity == null) {
   6729             return false;
   6730         }
   6731         if (intent.getComponent() != null) {
   6732             return false;
   6733         }
   6734         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
   6735             return false;
   6736         }
   6737         if (!skipPackageCheck && intent.getPackage() != null) {
   6738             return false;
   6739         }
   6740         final boolean isWebUri = hasWebURI(intent);
   6741         if (!isWebUri || intent.getData().getHost() == null) {
   6742             return false;
   6743         }
   6744         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
   6745         // Or if there's already an ephemeral app installed that handles the action
   6746         synchronized (mPackages) {
   6747             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
   6748             for (int n = 0; n < count; n++) {
   6749                 final ResolveInfo info = resolvedActivities.get(n);
   6750                 final String packageName = info.activityInfo.packageName;
   6751                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   6752                 if (ps != null) {
   6753                     // only check domain verification status if the app is not a browser
   6754                     if (!info.handleAllWebDataURI) {
   6755                         // Try to get the status from User settings first
   6756                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   6757                         final int status = (int) (packedStatus >> 32);
   6758                         if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
   6759                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
   6760                             if (DEBUG_EPHEMERAL) {
   6761                                 Slog.v(TAG, "DENY instant app;"
   6762                                     + " pkg: " + packageName + ", status: " + status);
   6763                             }
   6764                             return false;
   6765                         }
   6766                     }
   6767                     if (ps.getInstantApp(userId)) {
   6768                         if (DEBUG_EPHEMERAL) {
   6769                             Slog.v(TAG, "DENY instant app installed;"
   6770                                     + " pkg: " + packageName);
   6771                         }
   6772                         return false;
   6773                     }
   6774                 }
   6775             }
   6776         }
   6777         // We've exhausted all ways to deny ephemeral application; let the system look for them.
   6778         return true;
   6779     }
   6780 
   6781     private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
   6782             Intent origIntent, String resolvedType, String callingPackage,
   6783             Bundle verificationBundle, int userId) {
   6784         final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
   6785                 new InstantAppRequest(responseObj, origIntent, resolvedType,
   6786                         callingPackage, userId, verificationBundle, false /*resolveForStart*/));
   6787         mHandler.sendMessage(msg);
   6788     }
   6789 
   6790     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
   6791             int flags, List<ResolveInfo> query, int userId) {
   6792         if (query != null) {
   6793             final int N = query.size();
   6794             if (N == 1) {
   6795                 return query.get(0);
   6796             } else if (N > 1) {
   6797                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
   6798                 // If there is more than one activity with the same priority,
   6799                 // then let the user decide between them.
   6800                 ResolveInfo r0 = query.get(0);
   6801                 ResolveInfo r1 = query.get(1);
   6802                 if (DEBUG_INTENT_MATCHING || debug) {
   6803                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
   6804                             + r1.activityInfo.name + "=" + r1.priority);
   6805                 }
   6806                 // If the first activity has a higher priority, or a different
   6807                 // default, then it is always desirable to pick it.
   6808                 if (r0.priority != r1.priority
   6809                         || r0.preferredOrder != r1.preferredOrder
   6810                         || r0.isDefault != r1.isDefault) {
   6811                     return query.get(0);
   6812                 }
   6813                 // If we have saved a preference for a preferred activity for
   6814                 // this Intent, use that.
   6815                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
   6816                         flags, query, r0.priority, true, false, debug, userId);
   6817                 if (ri != null) {
   6818                     return ri;
   6819                 }
   6820                 // If we have an ephemeral app, use it
   6821                 for (int i = 0; i < N; i++) {
   6822                     ri = query.get(i);
   6823                     if (ri.activityInfo.applicationInfo.isInstantApp()) {
   6824                         final String packageName = ri.activityInfo.packageName;
   6825                         final PackageSetting ps = mSettings.mPackages.get(packageName);
   6826                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   6827                         final int status = (int)(packedStatus >> 32);
   6828                         if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
   6829                             return ri;
   6830                         }
   6831                     }
   6832                 }
   6833                 ri = new ResolveInfo(mResolveInfo);
   6834                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
   6835                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
   6836                 // If all of the options come from the same package, show the application's
   6837                 // label and icon instead of the generic resolver's.
   6838                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
   6839                 // and then throw away the ResolveInfo itself, meaning that the caller loses
   6840                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
   6841                 // a fallback for this case; we only set the target package's resources on
   6842                 // the ResolveInfo, not the ActivityInfo.
   6843                 final String intentPackage = intent.getPackage();
   6844                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
   6845                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
   6846                     ri.resolvePackageName = intentPackage;
   6847                     if (userNeedsBadging(userId)) {
   6848                         ri.noResourceId = true;
   6849                     } else {
   6850                         ri.icon = appi.icon;
   6851                     }
   6852                     ri.iconResourceId = appi.icon;
   6853                     ri.labelRes = appi.labelRes;
   6854                 }
   6855                 ri.activityInfo.applicationInfo = new ApplicationInfo(
   6856                         ri.activityInfo.applicationInfo);
   6857                 if (userId != 0) {
   6858                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
   6859                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
   6860                 }
   6861                 // Make sure that the resolver is displayable in car mode
   6862                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
   6863                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
   6864                 return ri;
   6865             }
   6866         }
   6867         return null;
   6868     }
   6869 
   6870     /**
   6871      * Return true if the given list is not empty and all of its contents have
   6872      * an activityInfo with the given package name.
   6873      */
   6874     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
   6875         if (ArrayUtils.isEmpty(list)) {
   6876             return false;
   6877         }
   6878         for (int i = 0, N = list.size(); i < N; i++) {
   6879             final ResolveInfo ri = list.get(i);
   6880             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
   6881             if (ai == null || !packageName.equals(ai.packageName)) {
   6882                 return false;
   6883             }
   6884         }
   6885         return true;
   6886     }
   6887 
   6888     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
   6889             int flags, List<ResolveInfo> query, boolean debug, int userId) {
   6890         final int N = query.size();
   6891         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
   6892                 .get(userId);
   6893         // Get the list of persistent preferred activities that handle the intent
   6894         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
   6895         List<PersistentPreferredActivity> pprefs = ppir != null
   6896                 ? ppir.queryIntent(intent, resolvedType,
   6897                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   6898                         userId)
   6899                 : null;
   6900         if (pprefs != null && pprefs.size() > 0) {
   6901             final int M = pprefs.size();
   6902             for (int i=0; i<M; i++) {
   6903                 final PersistentPreferredActivity ppa = pprefs.get(i);
   6904                 if (DEBUG_PREFERRED || debug) {
   6905                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
   6906                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
   6907                             + "\n  component=" + ppa.mComponent);
   6908                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   6909                 }
   6910                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
   6911                         flags | MATCH_DISABLED_COMPONENTS, userId);
   6912                 if (DEBUG_PREFERRED || debug) {
   6913                     Slog.v(TAG, "Found persistent preferred activity:");
   6914                     if (ai != null) {
   6915                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   6916                     } else {
   6917                         Slog.v(TAG, "  null");
   6918                     }
   6919                 }
   6920                 if (ai == null) {
   6921                     // This previously registered persistent preferred activity
   6922                     // component is no longer known. Ignore it and do NOT remove it.
   6923                     continue;
   6924                 }
   6925                 for (int j=0; j<N; j++) {
   6926                     final ResolveInfo ri = query.get(j);
   6927                     if (!ri.activityInfo.applicationInfo.packageName
   6928                             .equals(ai.applicationInfo.packageName)) {
   6929                         continue;
   6930                     }
   6931                     if (!ri.activityInfo.name.equals(ai.name)) {
   6932                         continue;
   6933                     }
   6934                     //  Found a persistent preference that can handle the intent.
   6935                     if (DEBUG_PREFERRED || debug) {
   6936                         Slog.v(TAG, "Returning persistent preferred activity: " +
   6937                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
   6938                     }
   6939                     return ri;
   6940                 }
   6941             }
   6942         }
   6943         return null;
   6944     }
   6945 
   6946     // TODO: handle preferred activities missing while user has amnesia
   6947     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
   6948             List<ResolveInfo> query, int priority, boolean always,
   6949             boolean removeMatches, boolean debug, int userId) {
   6950         if (!sUserManager.exists(userId)) return null;
   6951         final int callingUid = Binder.getCallingUid();
   6952         flags = updateFlagsForResolve(
   6953                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
   6954         intent = updateIntentForResolve(intent);
   6955         // writer
   6956         synchronized (mPackages) {
   6957             // Try to find a matching persistent preferred activity.
   6958             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
   6959                     debug, userId);
   6960 
   6961             // If a persistent preferred activity matched, use it.
   6962             if (pri != null) {
   6963                 return pri;
   6964             }
   6965 
   6966             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   6967             // Get the list of preferred activities that handle the intent
   6968             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
   6969             List<PreferredActivity> prefs = pir != null
   6970                     ? pir.queryIntent(intent, resolvedType,
   6971                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   6972                             userId)
   6973                     : null;
   6974             if (prefs != null && prefs.size() > 0) {
   6975                 boolean changed = false;
   6976                 try {
   6977                     // First figure out how good the original match set is.
   6978                     // We will only allow preferred activities that came
   6979                     // from the same match quality.
   6980                     int match = 0;
   6981 
   6982                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
   6983 
   6984                     final int N = query.size();
   6985                     for (int j=0; j<N; j++) {
   6986                         final ResolveInfo ri = query.get(j);
   6987                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
   6988                                 + ": 0x" + Integer.toHexString(match));
   6989                         if (ri.match > match) {
   6990                             match = ri.match;
   6991                         }
   6992                     }
   6993 
   6994                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
   6995                             + Integer.toHexString(match));
   6996 
   6997                     match &= IntentFilter.MATCH_CATEGORY_MASK;
   6998                     final int M = prefs.size();
   6999                     for (int i=0; i<M; i++) {
   7000                         final PreferredActivity pa = prefs.get(i);
   7001                         if (DEBUG_PREFERRED || debug) {
   7002                             Slog.v(TAG, "Checking PreferredActivity ds="
   7003                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
   7004                                     + "\n  component=" + pa.mPref.mComponent);
   7005                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   7006                         }
   7007                         if (pa.mPref.mMatch != match) {
   7008                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
   7009                                     + Integer.toHexString(pa.mPref.mMatch));
   7010                             continue;
   7011                         }
   7012                         // If it's not an "always" type preferred activity and that's what we're
   7013                         // looking for, skip it.
   7014                         if (always && !pa.mPref.mAlways) {
   7015                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
   7016                             continue;
   7017                         }
   7018                         final ActivityInfo ai = getActivityInfo(
   7019                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
   7020                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   7021                                 userId);
   7022                         if (DEBUG_PREFERRED || debug) {
   7023                             Slog.v(TAG, "Found preferred activity:");
   7024                             if (ai != null) {
   7025                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   7026                             } else {
   7027                                 Slog.v(TAG, "  null");
   7028                             }
   7029                         }
   7030                         if (ai == null) {
   7031                             // This previously registered preferred activity
   7032                             // component is no longer known.  Most likely an update
   7033                             // to the app was installed and in the new version this
   7034                             // component no longer exists.  Clean it up by removing
   7035                             // it from the preferred activities list, and skip it.
   7036                             Slog.w(TAG, "Removing dangling preferred activity: "
   7037                                     + pa.mPref.mComponent);
   7038                             pir.removeFilter(pa);
   7039                             changed = true;
   7040                             continue;
   7041                         }
   7042                         for (int j=0; j<N; j++) {
   7043                             final ResolveInfo ri = query.get(j);
   7044                             if (!ri.activityInfo.applicationInfo.packageName
   7045                                     .equals(ai.applicationInfo.packageName)) {
   7046                                 continue;
   7047                             }
   7048                             if (!ri.activityInfo.name.equals(ai.name)) {
   7049                                 continue;
   7050                             }
   7051 
   7052                             if (removeMatches) {
   7053                                 pir.removeFilter(pa);
   7054                                 changed = true;
   7055                                 if (DEBUG_PREFERRED) {
   7056                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
   7057                                 }
   7058                                 break;
   7059                             }
   7060 
   7061                             // Okay we found a previously set preferred or last chosen app.
   7062                             // If the result set is different from when this
   7063                             // was created, and is not a subset of the preferred set, we need to
   7064                             // clear it and re-ask the user their preference, if we're looking for
   7065                             // an "always" type entry.
   7066                             if (always && !pa.mPref.sameSet(query)) {
   7067                                 if (pa.mPref.isSuperset(query)) {
   7068                                     // some components of the set are no longer present in
   7069                                     // the query, but the preferred activity can still be reused
   7070                                     if (DEBUG_PREFERRED) {
   7071                                         Slog.i(TAG, "Result set changed, but PreferredActivity is"
   7072                                                 + " still valid as only non-preferred components"
   7073                                                 + " were removed for " + intent + " type "
   7074                                                 + resolvedType);
   7075                                     }
   7076                                     // remove obsolete components and re-add the up-to-date filter
   7077                                     PreferredActivity freshPa = new PreferredActivity(pa,
   7078                                             pa.mPref.mMatch,
   7079                                             pa.mPref.discardObsoleteComponents(query),
   7080                                             pa.mPref.mComponent,
   7081                                             pa.mPref.mAlways);
   7082                                     pir.removeFilter(pa);
   7083                                     pir.addFilter(freshPa);
   7084                                     changed = true;
   7085                                 } else {
   7086                                     Slog.i(TAG,
   7087                                             "Result set changed, dropping preferred activity for "
   7088                                                     + intent + " type " + resolvedType);
   7089                                     if (DEBUG_PREFERRED) {
   7090                                         Slog.v(TAG, "Removing preferred activity since set changed "
   7091                                                 + pa.mPref.mComponent);
   7092                                     }
   7093                                     pir.removeFilter(pa);
   7094                                     // Re-add the filter as a "last chosen" entry (!always)
   7095                                     PreferredActivity lastChosen = new PreferredActivity(
   7096                                             pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
   7097                                     pir.addFilter(lastChosen);
   7098                                     changed = true;
   7099                                     return null;
   7100                                 }
   7101                             }
   7102 
   7103                             // Yay! Either the set matched or we're looking for the last chosen
   7104                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
   7105                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
   7106                             return ri;
   7107                         }
   7108                     }
   7109                 } finally {
   7110                     if (changed) {
   7111                         if (DEBUG_PREFERRED) {
   7112                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
   7113                         }
   7114                         scheduleWritePackageRestrictionsLocked(userId);
   7115                     }
   7116                 }
   7117             }
   7118         }
   7119         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
   7120         return null;
   7121     }
   7122 
   7123     /*
   7124      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
   7125      */
   7126     @Override
   7127     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
   7128             int targetUserId) {
   7129         mContext.enforceCallingOrSelfPermission(
   7130                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   7131         List<CrossProfileIntentFilter> matches =
   7132                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
   7133         if (matches != null) {
   7134             int size = matches.size();
   7135             for (int i = 0; i < size; i++) {
   7136                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
   7137             }
   7138         }
   7139         if (hasWebURI(intent)) {
   7140             // cross-profile app linking works only towards the parent.
   7141             final int callingUid = Binder.getCallingUid();
   7142             final UserInfo parent = getProfileParent(sourceUserId);
   7143             synchronized(mPackages) {
   7144                 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
   7145                         false /*includeInstantApps*/);
   7146                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
   7147                         intent, resolvedType, flags, sourceUserId, parent.id);
   7148                 return xpDomainInfo != null;
   7149             }
   7150         }
   7151         return false;
   7152     }
   7153 
   7154     private UserInfo getProfileParent(int userId) {
   7155         final long identity = Binder.clearCallingIdentity();
   7156         try {
   7157             return sUserManager.getProfileParent(userId);
   7158         } finally {
   7159             Binder.restoreCallingIdentity(identity);
   7160         }
   7161     }
   7162 
   7163     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
   7164             String resolvedType, int userId) {
   7165         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
   7166         if (resolver != null) {
   7167             return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
   7168         }
   7169         return null;
   7170     }
   7171 
   7172     @Override
   7173     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
   7174             String resolvedType, int flags, int userId) {
   7175         try {
   7176             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
   7177 
   7178             return new ParceledListSlice<>(
   7179                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
   7180         } finally {
   7181             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   7182         }
   7183     }
   7184 
   7185     /**
   7186      * Returns the package name of the calling Uid if it's an instant app. If it isn't
   7187      * instant, returns {@code null}.
   7188      */
   7189     private String getInstantAppPackageName(int callingUid) {
   7190         synchronized (mPackages) {
   7191             // If the caller is an isolated app use the owner's uid for the lookup.
   7192             if (Process.isIsolated(callingUid)) {
   7193                 callingUid = mIsolatedOwners.get(callingUid);
   7194             }
   7195             final int appId = UserHandle.getAppId(callingUid);
   7196             final Object obj = mSettings.getUserIdLPr(appId);
   7197             if (obj instanceof PackageSetting) {
   7198                 final PackageSetting ps = (PackageSetting) obj;
   7199                 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
   7200                 return isInstantApp ? ps.pkg.packageName : null;
   7201             }
   7202         }
   7203         return null;
   7204     }
   7205 
   7206     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
   7207             String resolvedType, int flags, int userId) {
   7208         return queryIntentActivitiesInternal(
   7209                 intent, resolvedType, flags, Binder.getCallingUid(), userId,
   7210                 false /*resolveForStart*/, true /*allowDynamicSplits*/);
   7211     }
   7212 
   7213     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
   7214             String resolvedType, int flags, int filterCallingUid, int userId,
   7215             boolean resolveForStart, boolean allowDynamicSplits) {
   7216         if (!sUserManager.exists(userId)) return Collections.emptyList();
   7217         final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
   7218         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   7219                 false /* requireFullPermission */, false /* checkShell */,
   7220                 "query intent activities");
   7221         final String pkgName = intent.getPackage();
   7222         ComponentName comp = intent.getComponent();
   7223         if (comp == null) {
   7224             if (intent.getSelector() != null) {
   7225                 intent = intent.getSelector();
   7226                 comp = intent.getComponent();
   7227             }
   7228         }
   7229 
   7230         flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
   7231                 comp != null || pkgName != null /*onlyExposedExplicitly*/);
   7232         if (comp != null) {
   7233             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   7234             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
   7235             if (ai != null) {
   7236                 // When specifying an explicit component, we prevent the activity from being
   7237                 // used when either 1) the calling package is normal and the activity is within
   7238                 // an ephemeral application or 2) the calling package is ephemeral and the
   7239                 // activity is not visible to ephemeral applications.
   7240                 final boolean matchInstantApp =
   7241                         (flags & PackageManager.MATCH_INSTANT) != 0;
   7242                 final boolean matchVisibleToInstantAppOnly =
   7243                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   7244                 final boolean matchExplicitlyVisibleOnly =
   7245                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
   7246                 final boolean isCallerInstantApp =
   7247                         instantAppPkgName != null;
   7248                 final boolean isTargetSameInstantApp =
   7249                         comp.getPackageName().equals(instantAppPkgName);
   7250                 final boolean isTargetInstantApp =
   7251                         (ai.applicationInfo.privateFlags
   7252                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   7253                 final boolean isTargetVisibleToInstantApp =
   7254                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
   7255                 final boolean isTargetExplicitlyVisibleToInstantApp =
   7256                         isTargetVisibleToInstantApp
   7257                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
   7258                 final boolean isTargetHiddenFromInstantApp =
   7259                         !isTargetVisibleToInstantApp
   7260                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
   7261                 final boolean blockResolution =
   7262                         !isTargetSameInstantApp
   7263                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   7264                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   7265                                         && isTargetHiddenFromInstantApp));
   7266                 if (!blockResolution) {
   7267                     final ResolveInfo ri = new ResolveInfo();
   7268                     ri.activityInfo = ai;
   7269                     list.add(ri);
   7270                 }
   7271             }
   7272             return applyPostResolutionFilter(
   7273                     list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
   7274         }
   7275 
   7276         // reader
   7277         boolean sortResult = false;
   7278         boolean addEphemeral = false;
   7279         List<ResolveInfo> result;
   7280         final boolean ephemeralDisabled = isEphemeralDisabled();
   7281         synchronized (mPackages) {
   7282             if (pkgName == null) {
   7283                 List<CrossProfileIntentFilter> matchingFilters =
   7284                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
   7285                 // Check for results that need to skip the current profile.
   7286                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
   7287                         resolvedType, flags, userId);
   7288                 if (xpResolveInfo != null) {
   7289                     List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
   7290                     xpResult.add(xpResolveInfo);
   7291                     return applyPostResolutionFilter(
   7292                             filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
   7293                             allowDynamicSplits, filterCallingUid, userId);
   7294                 }
   7295 
   7296                 // Check for results in the current profile.
   7297                 result = filterIfNotSystemUser(mActivities.queryIntent(
   7298                         intent, resolvedType, flags, userId), userId);
   7299                 addEphemeral = !ephemeralDisabled
   7300                         && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
   7301                 // Check for cross profile results.
   7302                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
   7303                 xpResolveInfo = queryCrossProfileIntents(
   7304                         matchingFilters, intent, resolvedType, flags, userId,
   7305                         hasNonNegativePriorityResult);
   7306                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
   7307                     boolean isVisibleToUser = filterIfNotSystemUser(
   7308                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
   7309                     if (isVisibleToUser) {
   7310                         result.add(xpResolveInfo);
   7311                         sortResult = true;
   7312                     }
   7313                 }
   7314                 if (hasWebURI(intent)) {
   7315                     CrossProfileDomainInfo xpDomainInfo = null;
   7316                     final UserInfo parent = getProfileParent(userId);
   7317                     if (parent != null) {
   7318                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
   7319                                 flags, userId, parent.id);
   7320                     }
   7321                     if (xpDomainInfo != null) {
   7322                         if (xpResolveInfo != null) {
   7323                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
   7324                             // in the result.
   7325                             result.remove(xpResolveInfo);
   7326                         }
   7327                         if (result.size() == 0 && !addEphemeral) {
   7328                             // No result in current profile, but found candidate in parent user.
   7329                             // And we are not going to add emphemeral app, so we can return the
   7330                             // result straight away.
   7331                             result.add(xpDomainInfo.resolveInfo);
   7332                             return applyPostResolutionFilter(result, instantAppPkgName,
   7333                                     allowDynamicSplits, filterCallingUid, userId);
   7334                         }
   7335                     } else if (result.size() <= 1 && !addEphemeral) {
   7336                         // No result in parent user and <= 1 result in current profile, and we
   7337                         // are not going to add emphemeral app, so we can return the result without
   7338                         // further processing.
   7339                         return applyPostResolutionFilter(result, instantAppPkgName,
   7340                                 allowDynamicSplits, filterCallingUid, userId);
   7341                     }
   7342                     // We have more than one candidate (combining results from current and parent
   7343                     // profile), so we need filtering and sorting.
   7344                     result = filterCandidatesWithDomainPreferredActivitiesLPr(
   7345                             intent, flags, result, xpDomainInfo, userId);
   7346                     sortResult = true;
   7347                 }
   7348             } else {
   7349                 final PackageParser.Package pkg = mPackages.get(pkgName);
   7350                 result = null;
   7351                 if (pkg != null) {
   7352                     result = filterIfNotSystemUser(
   7353                             mActivities.queryIntentForPackage(
   7354                                     intent, resolvedType, flags, pkg.activities, userId),
   7355                             userId);
   7356                 }
   7357                 if (result == null || result.size() == 0) {
   7358                     // the caller wants to resolve for a particular package; however, there
   7359                     // were no installed results, so, try to find an ephemeral result
   7360                     addEphemeral = !ephemeralDisabled
   7361                             && isInstantAppAllowed(
   7362                                     intent, null /*result*/, userId, true /*skipPackageCheck*/);
   7363                     if (result == null) {
   7364                         result = new ArrayList<>();
   7365                     }
   7366                 }
   7367             }
   7368         }
   7369         if (addEphemeral) {
   7370             result = maybeAddInstantAppInstaller(
   7371                     result, intent, resolvedType, flags, userId, resolveForStart);
   7372         }
   7373         if (sortResult) {
   7374             Collections.sort(result, mResolvePrioritySorter);
   7375         }
   7376         return applyPostResolutionFilter(
   7377                 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
   7378     }
   7379 
   7380     private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
   7381             String resolvedType, int flags, int userId, boolean resolveForStart) {
   7382         // first, check to see if we've got an instant app already installed
   7383         final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
   7384         ResolveInfo localInstantApp = null;
   7385         boolean blockResolution = false;
   7386         if (!alreadyResolvedLocally) {
   7387             final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
   7388                     flags
   7389                         | PackageManager.GET_RESOLVED_FILTER
   7390                         | PackageManager.MATCH_INSTANT
   7391                         | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
   7392                     userId);
   7393             for (int i = instantApps.size() - 1; i >= 0; --i) {
   7394                 final ResolveInfo info = instantApps.get(i);
   7395                 final String packageName = info.activityInfo.packageName;
   7396                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   7397                 if (ps.getInstantApp(userId)) {
   7398                     final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   7399                     final int status = (int)(packedStatus >> 32);
   7400                     final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
   7401                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   7402                         // there's a local instant application installed, but, the user has
   7403                         // chosen to never use it; skip resolution and don't acknowledge
   7404                         // an instant application is even available
   7405                         if (DEBUG_EPHEMERAL) {
   7406                             Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
   7407                         }
   7408                         blockResolution = true;
   7409                         break;
   7410                     } else {
   7411                         // we have a locally installed instant application; skip resolution
   7412                         // but acknowledge there's an instant application available
   7413                         if (DEBUG_EPHEMERAL) {
   7414                             Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
   7415                         }
   7416                         localInstantApp = info;
   7417                         break;
   7418                     }
   7419                 }
   7420             }
   7421         }
   7422         // no app installed, let's see if one's available
   7423         AuxiliaryResolveInfo auxiliaryResponse = null;
   7424         if (!blockResolution) {
   7425             if (localInstantApp == null) {
   7426                 // we don't have an instant app locally, resolve externally
   7427                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
   7428                 final InstantAppRequest requestObject = new InstantAppRequest(
   7429                         null /*responseObj*/, intent /*origIntent*/, resolvedType,
   7430                         null /*callingPackage*/, userId, null /*verificationBundle*/,
   7431                         resolveForStart);
   7432                 auxiliaryResponse =
   7433                         InstantAppResolver.doInstantAppResolutionPhaseOne(
   7434                                 mContext, mInstantAppResolverConnection, requestObject);
   7435                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   7436             } else {
   7437                 // we have an instant application locally, but, we can't admit that since
   7438                 // callers shouldn't be able to determine prior browsing. create a dummy
   7439                 // auxiliary response so the downstream code behaves as if there's an
   7440                 // instant application available externally. when it comes time to start
   7441                 // the instant application, we'll do the right thing.
   7442                 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
   7443                 auxiliaryResponse = new AuxiliaryResolveInfo(
   7444                         ai.packageName, null /*splitName*/, null /*failureActivity*/,
   7445                         ai.versionCode, null /*failureIntent*/);
   7446             }
   7447         }
   7448         if (auxiliaryResponse != null) {
   7449             if (DEBUG_EPHEMERAL) {
   7450                 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
   7451             }
   7452             final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
   7453             final PackageSetting ps =
   7454                     mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
   7455             if (ps != null) {
   7456                 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
   7457                         mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
   7458                 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
   7459                 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
   7460                 // make sure this resolver is the default
   7461                 ephemeralInstaller.isDefault = true;
   7462                 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
   7463                         | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
   7464                 // add a non-generic filter
   7465                 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
   7466                 ephemeralInstaller.filter.addDataPath(
   7467                         intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
   7468                 ephemeralInstaller.isInstantAppAvailable = true;
   7469                 result.add(ephemeralInstaller);
   7470             }
   7471         }
   7472         return result;
   7473     }
   7474 
   7475     private static class CrossProfileDomainInfo {
   7476         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
   7477         ResolveInfo resolveInfo;
   7478         /* Best domain verification status of the activities found in the other profile */
   7479         int bestDomainVerificationStatus;
   7480     }
   7481 
   7482     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
   7483             String resolvedType, int flags, int sourceUserId, int parentUserId) {
   7484         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
   7485                 sourceUserId)) {
   7486             return null;
   7487         }
   7488         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
   7489                 resolvedType, flags, parentUserId);
   7490 
   7491         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
   7492             return null;
   7493         }
   7494         CrossProfileDomainInfo result = null;
   7495         int size = resultTargetUser.size();
   7496         for (int i = 0; i < size; i++) {
   7497             ResolveInfo riTargetUser = resultTargetUser.get(i);
   7498             // Intent filter verification is only for filters that specify a host. So don't return
   7499             // those that handle all web uris.
   7500             if (riTargetUser.handleAllWebDataURI) {
   7501                 continue;
   7502             }
   7503             String packageName = riTargetUser.activityInfo.packageName;
   7504             PackageSetting ps = mSettings.mPackages.get(packageName);
   7505             if (ps == null) {
   7506                 continue;
   7507             }
   7508             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
   7509             int status = (int)(verificationState >> 32);
   7510             if (result == null) {
   7511                 result = new CrossProfileDomainInfo();
   7512                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
   7513                         sourceUserId, parentUserId);
   7514                 result.bestDomainVerificationStatus = status;
   7515             } else {
   7516                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
   7517                         result.bestDomainVerificationStatus);
   7518             }
   7519         }
   7520         // Don't consider matches with status NEVER across profiles.
   7521         if (result != null && result.bestDomainVerificationStatus
   7522                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   7523             return null;
   7524         }
   7525         return result;
   7526     }
   7527 
   7528     /**
   7529      * Verification statuses are ordered from the worse to the best, except for
   7530      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
   7531      */
   7532     private int bestDomainVerificationStatus(int status1, int status2) {
   7533         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   7534             return status2;
   7535         }
   7536         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   7537             return status1;
   7538         }
   7539         return (int) MathUtils.max(status1, status2);
   7540     }
   7541 
   7542     private boolean isUserEnabled(int userId) {
   7543         long callingId = Binder.clearCallingIdentity();
   7544         try {
   7545             UserInfo userInfo = sUserManager.getUserInfo(userId);
   7546             return userInfo != null && userInfo.isEnabled();
   7547         } finally {
   7548             Binder.restoreCallingIdentity(callingId);
   7549         }
   7550     }
   7551 
   7552     /**
   7553      * Filter out activities with systemUserOnly flag set, when current user is not System.
   7554      *
   7555      * @return filtered list
   7556      */
   7557     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
   7558         if (userId == UserHandle.USER_SYSTEM) {
   7559             return resolveInfos;
   7560         }
   7561         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   7562             ResolveInfo info = resolveInfos.get(i);
   7563             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
   7564                 resolveInfos.remove(i);
   7565             }
   7566         }
   7567         return resolveInfos;
   7568     }
   7569 
   7570     /**
   7571      * Filters out ephemeral activities.
   7572      * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
   7573      * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
   7574      *
   7575      * @param resolveInfos The pre-filtered list of resolved activities
   7576      * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
   7577      *          is performed.
   7578      * @return A filtered list of resolved activities.
   7579      */
   7580     private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
   7581             String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
   7582         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   7583             final ResolveInfo info = resolveInfos.get(i);
   7584             // allow activities that are defined in the provided package
   7585             if (allowDynamicSplits
   7586                     && info.activityInfo.splitName != null
   7587                     && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
   7588                             info.activityInfo.splitName)) {
   7589                 if (mInstantAppInstallerInfo == null) {
   7590                     if (DEBUG_INSTALL) {
   7591                         Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
   7592                     }
   7593                     resolveInfos.remove(i);
   7594                     continue;
   7595                 }
   7596                 // requested activity is defined in a split that hasn't been installed yet.
   7597                 // add the installer to the resolve list
   7598                 if (DEBUG_INSTALL) {
   7599                     Slog.v(TAG, "Adding installer to the ResolveInfo list");
   7600                 }
   7601                 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
   7602                 final ComponentName installFailureActivity = findInstallFailureActivity(
   7603                         info.activityInfo.packageName,  filterCallingUid, userId);
   7604                 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
   7605                         info.activityInfo.packageName, info.activityInfo.splitName,
   7606                         installFailureActivity,
   7607                         info.activityInfo.applicationInfo.versionCode,
   7608                         null /*failureIntent*/);
   7609                 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
   7610                         | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
   7611                 // add a non-generic filter
   7612                 installerInfo.filter = new IntentFilter();
   7613 
   7614                 // This resolve info may appear in the chooser UI, so let us make it
   7615                 // look as the one it replaces as far as the user is concerned which
   7616                 // requires loading the correct label and icon for the resolve info.
   7617                 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
   7618                 installerInfo.labelRes = info.resolveLabelResId();
   7619                 installerInfo.icon = info.resolveIconResId();
   7620 
   7621                 // propagate priority/preferred order/default
   7622                 installerInfo.priority = info.priority;
   7623                 installerInfo.preferredOrder = info.preferredOrder;
   7624                 installerInfo.isDefault = info.isDefault;
   7625                 resolveInfos.set(i, installerInfo);
   7626                 continue;
   7627             }
   7628             // caller is a full app, don't need to apply any other filtering
   7629             if (ephemeralPkgName == null) {
   7630                 continue;
   7631             } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
   7632                 // caller is same app; don't need to apply any other filtering
   7633                 continue;
   7634             }
   7635             // allow activities that have been explicitly exposed to ephemeral apps
   7636             final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
   7637             if (!isEphemeralApp
   7638                     && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
   7639                 continue;
   7640             }
   7641             resolveInfos.remove(i);
   7642         }
   7643         return resolveInfos;
   7644     }
   7645 
   7646     /**
   7647      * Returns the activity component that can handle install failures.
   7648      * <p>By default, the instant application installer handles failures. However, an
   7649      * application may want to handle failures on its own. Applications do this by
   7650      * creating an activity with an intent filter that handles the action
   7651      * {@link Intent#ACTION_INSTALL_FAILURE}.
   7652      */
   7653     private @Nullable ComponentName findInstallFailureActivity(
   7654             String packageName, int filterCallingUid, int userId) {
   7655         final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
   7656         failureActivityIntent.setPackage(packageName);
   7657         // IMPORTANT: disallow dynamic splits to avoid an infinite loop
   7658         final List<ResolveInfo> result = queryIntentActivitiesInternal(
   7659                 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
   7660                 false /*resolveForStart*/, false /*allowDynamicSplits*/);
   7661         final int NR = result.size();
   7662         if (NR > 0) {
   7663             for (int i = 0; i < NR; i++) {
   7664                 final ResolveInfo info = result.get(i);
   7665                 if (info.activityInfo.splitName != null) {
   7666                     continue;
   7667                 }
   7668                 return new ComponentName(packageName, info.activityInfo.name);
   7669             }
   7670         }
   7671         return null;
   7672     }
   7673 
   7674     /**
   7675      * @param resolveInfos list of resolve infos in descending priority order
   7676      * @return if the list contains a resolve info with non-negative priority
   7677      */
   7678     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
   7679         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
   7680     }
   7681 
   7682     private static boolean hasWebURI(Intent intent) {
   7683         if (intent.getData() == null) {
   7684             return false;
   7685         }
   7686         final String scheme = intent.getScheme();
   7687         if (TextUtils.isEmpty(scheme)) {
   7688             return false;
   7689         }
   7690         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
   7691     }
   7692 
   7693     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
   7694             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
   7695             int userId) {
   7696         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
   7697 
   7698         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
   7699             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
   7700                     candidates.size());
   7701         }
   7702 
   7703         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
   7704         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
   7705         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
   7706         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
   7707         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
   7708         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
   7709 
   7710         synchronized (mPackages) {
   7711             final int count = candidates.size();
   7712             // First, try to use linked apps. Partition the candidates into four lists:
   7713             // one for the final results, one for the "do not use ever", one for "undefined status"
   7714             // and finally one for "browser app type".
   7715             for (int n=0; n<count; n++) {
   7716                 ResolveInfo info = candidates.get(n);
   7717                 String packageName = info.activityInfo.packageName;
   7718                 PackageSetting ps = mSettings.mPackages.get(packageName);
   7719                 if (ps != null) {
   7720                     // Add to the special match all list (Browser use case)
   7721                     if (info.handleAllWebDataURI) {
   7722                         matchAllList.add(info);
   7723                         continue;
   7724                     }
   7725                     // Try to get the status from User settings first
   7726                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   7727                     int status = (int)(packedStatus >> 32);
   7728                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
   7729                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
   7730                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7731                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
   7732                                     + " : linkgen=" + linkGeneration);
   7733                         }
   7734                         // Use link-enabled generation as preferredOrder, i.e.
   7735                         // prefer newly-enabled over earlier-enabled.
   7736                         info.preferredOrder = linkGeneration;
   7737                         alwaysList.add(info);
   7738                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   7739                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7740                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
   7741                         }
   7742                         neverList.add(info);
   7743                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
   7744                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7745                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
   7746                         }
   7747                         alwaysAskList.add(info);
   7748                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
   7749                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
   7750                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7751                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
   7752                         }
   7753                         undefinedList.add(info);
   7754                     }
   7755                 }
   7756             }
   7757 
   7758             // We'll want to include browser possibilities in a few cases
   7759             boolean includeBrowser = false;
   7760 
   7761             // First try to add the "always" resolution(s) for the current user, if any
   7762             if (alwaysList.size() > 0) {
   7763                 result.addAll(alwaysList);
   7764             } else {
   7765                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
   7766                 result.addAll(undefinedList);
   7767                 // Maybe add one for the other profile.
   7768                 if (xpDomainInfo != null && (
   7769                         xpDomainInfo.bestDomainVerificationStatus
   7770                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
   7771                     result.add(xpDomainInfo.resolveInfo);
   7772                 }
   7773                 includeBrowser = true;
   7774             }
   7775 
   7776             // The presence of any 'always ask' alternatives means we'll also offer browsers.
   7777             // If there were 'always' entries their preferred order has been set, so we also
   7778             // back that off to make the alternatives equivalent
   7779             if (alwaysAskList.size() > 0) {
   7780                 for (ResolveInfo i : result) {
   7781                     i.preferredOrder = 0;
   7782                 }
   7783                 result.addAll(alwaysAskList);
   7784                 includeBrowser = true;
   7785             }
   7786 
   7787             if (includeBrowser) {
   7788                 // Also add browsers (all of them or only the default one)
   7789                 if (DEBUG_DOMAIN_VERIFICATION) {
   7790                     Slog.v(TAG, "   ...including browsers in candidate set");
   7791                 }
   7792                 if ((matchFlags & MATCH_ALL) != 0) {
   7793                     result.addAll(matchAllList);
   7794                 } else {
   7795                     // Browser/generic handling case.  If there's a default browser, go straight
   7796                     // to that (but only if there is no other higher-priority match).
   7797                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
   7798                     int maxMatchPrio = 0;
   7799                     ResolveInfo defaultBrowserMatch = null;
   7800                     final int numCandidates = matchAllList.size();
   7801                     for (int n = 0; n < numCandidates; n++) {
   7802                         ResolveInfo info = matchAllList.get(n);
   7803                         // track the highest overall match priority...
   7804                         if (info.priority > maxMatchPrio) {
   7805                             maxMatchPrio = info.priority;
   7806                         }
   7807                         // ...and the highest-priority default browser match
   7808                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
   7809                             if (defaultBrowserMatch == null
   7810                                     || (defaultBrowserMatch.priority < info.priority)) {
   7811                                 if (debug) {
   7812                                     Slog.v(TAG, "Considering default browser match " + info);
   7813                                 }
   7814                                 defaultBrowserMatch = info;
   7815                             }
   7816                         }
   7817                     }
   7818                     if (defaultBrowserMatch != null
   7819                             && defaultBrowserMatch.priority >= maxMatchPrio
   7820                             && !TextUtils.isEmpty(defaultBrowserPackageName))
   7821                     {
   7822                         if (debug) {
   7823                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
   7824                         }
   7825                         result.add(defaultBrowserMatch);
   7826                     } else {
   7827                         result.addAll(matchAllList);
   7828                     }
   7829                 }
   7830 
   7831                 // If there is nothing selected, add all candidates and remove the ones that the user
   7832                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
   7833                 if (result.size() == 0) {
   7834                     result.addAll(candidates);
   7835                     result.removeAll(neverList);
   7836                 }
   7837             }
   7838         }
   7839         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
   7840             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
   7841                     result.size());
   7842             for (ResolveInfo info : result) {
   7843                 Slog.v(TAG, "  + " + info.activityInfo);
   7844             }
   7845         }
   7846         return result;
   7847     }
   7848 
   7849     // Returns a packed value as a long:
   7850     //
   7851     // high 'int'-sized word: link status: undefined/ask/never/always.
   7852     // low 'int'-sized word: relative priority among 'always' results.
   7853     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
   7854         long result = ps.getDomainVerificationStatusForUser(userId);
   7855         // if none available, get the master status
   7856         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
   7857             if (ps.getIntentFilterVerificationInfo() != null) {
   7858                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
   7859             }
   7860         }
   7861         return result;
   7862     }
   7863 
   7864     private ResolveInfo querySkipCurrentProfileIntents(
   7865             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
   7866             int flags, int sourceUserId) {
   7867         if (matchingFilters != null) {
   7868             int size = matchingFilters.size();
   7869             for (int i = 0; i < size; i ++) {
   7870                 CrossProfileIntentFilter filter = matchingFilters.get(i);
   7871                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
   7872                     // Checking if there are activities in the target user that can handle the
   7873                     // intent.
   7874                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
   7875                             resolvedType, flags, sourceUserId);
   7876                     if (resolveInfo != null) {
   7877                         return resolveInfo;
   7878                     }
   7879                 }
   7880             }
   7881         }
   7882         return null;
   7883     }
   7884 
   7885     // Return matching ResolveInfo in target user if any.
   7886     private ResolveInfo queryCrossProfileIntents(
   7887             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
   7888             int flags, int sourceUserId, boolean matchInCurrentProfile) {
   7889         if (matchingFilters != null) {
   7890             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
   7891             // match the same intent. For performance reasons, it is better not to
   7892             // run queryIntent twice for the same userId
   7893             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
   7894             int size = matchingFilters.size();
   7895             for (int i = 0; i < size; i++) {
   7896                 CrossProfileIntentFilter filter = matchingFilters.get(i);
   7897                 int targetUserId = filter.getTargetUserId();
   7898                 boolean skipCurrentProfile =
   7899                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
   7900                 boolean skipCurrentProfileIfNoMatchFound =
   7901                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
   7902                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
   7903                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
   7904                     // Checking if there are activities in the target user that can handle the
   7905                     // intent.
   7906                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
   7907                             resolvedType, flags, sourceUserId);
   7908                     if (resolveInfo != null) return resolveInfo;
   7909                     alreadyTriedUserIds.put(targetUserId, true);
   7910                 }
   7911             }
   7912         }
   7913         return null;
   7914     }
   7915 
   7916     /**
   7917      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
   7918      * will forward the intent to the filter's target user.
   7919      * Otherwise, returns null.
   7920      */
   7921     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
   7922             String resolvedType, int flags, int sourceUserId) {
   7923         int targetUserId = filter.getTargetUserId();
   7924         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
   7925                 resolvedType, flags, targetUserId);
   7926         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
   7927             // If all the matches in the target profile are suspended, return null.
   7928             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
   7929                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
   7930                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
   7931                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
   7932                             targetUserId);
   7933                 }
   7934             }
   7935         }
   7936         return null;
   7937     }
   7938 
   7939     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
   7940             int sourceUserId, int targetUserId) {
   7941         ResolveInfo forwardingResolveInfo = new ResolveInfo();
   7942         long ident = Binder.clearCallingIdentity();
   7943         boolean targetIsProfile;
   7944         try {
   7945             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
   7946         } finally {
   7947             Binder.restoreCallingIdentity(ident);
   7948         }
   7949         String className;
   7950         if (targetIsProfile) {
   7951             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
   7952         } else {
   7953             className = FORWARD_INTENT_TO_PARENT;
   7954         }
   7955         ComponentName forwardingActivityComponentName = new ComponentName(
   7956                 mAndroidApplication.packageName, className);
   7957         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
   7958                 sourceUserId);
   7959         if (!targetIsProfile) {
   7960             forwardingActivityInfo.showUserIcon = targetUserId;
   7961             forwardingResolveInfo.noResourceId = true;
   7962         }
   7963         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
   7964         forwardingResolveInfo.priority = 0;
   7965         forwardingResolveInfo.preferredOrder = 0;
   7966         forwardingResolveInfo.match = 0;
   7967         forwardingResolveInfo.isDefault = true;
   7968         forwardingResolveInfo.filter = filter;
   7969         forwardingResolveInfo.targetUserId = targetUserId;
   7970         return forwardingResolveInfo;
   7971     }
   7972 
   7973     @Override
   7974     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
   7975             Intent[] specifics, String[] specificTypes, Intent intent,
   7976             String resolvedType, int flags, int userId) {
   7977         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
   7978                 specificTypes, intent, resolvedType, flags, userId));
   7979     }
   7980 
   7981     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
   7982             Intent[] specifics, String[] specificTypes, Intent intent,
   7983             String resolvedType, int flags, int userId) {
   7984         if (!sUserManager.exists(userId)) return Collections.emptyList();
   7985         final int callingUid = Binder.getCallingUid();
   7986         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
   7987                 false /*includeInstantApps*/);
   7988         enforceCrossUserPermission(callingUid, userId,
   7989                 false /*requireFullPermission*/, false /*checkShell*/,
   7990                 "query intent activity options");
   7991         final String resultsAction = intent.getAction();
   7992 
   7993         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
   7994                 | PackageManager.GET_RESOLVED_FILTER, userId);
   7995 
   7996         if (DEBUG_INTENT_MATCHING) {
   7997             Log.v(TAG, "Query " + intent + ": " + results);
   7998         }
   7999 
   8000         int specificsPos = 0;
   8001         int N;
   8002 
   8003         // todo: note that the algorithm used here is O(N^2).  This
   8004         // isn't a problem in our current environment, but if we start running
   8005         // into situations where we have more than 5 or 10 matches then this
   8006         // should probably be changed to something smarter...
   8007 
   8008         // First we go through and resolve each of the specific items
   8009         // that were supplied, taking care of removing any corresponding
   8010         // duplicate items in the generic resolve list.
   8011         if (specifics != null) {
   8012             for (int i=0; i<specifics.length; i++) {
   8013                 final Intent sintent = specifics[i];
   8014                 if (sintent == null) {
   8015                     continue;
   8016                 }
   8017 
   8018                 if (DEBUG_INTENT_MATCHING) {
   8019                     Log.v(TAG, "Specific #" + i + ": " + sintent);
   8020                 }
   8021 
   8022                 String action = sintent.getAction();
   8023                 if (resultsAction != null && resultsAction.equals(action)) {
   8024                     // If this action was explicitly requested, then don't
   8025                     // remove things that have it.
   8026                     action = null;
   8027                 }
   8028 
   8029                 ResolveInfo ri = null;
   8030                 ActivityInfo ai = null;
   8031 
   8032                 ComponentName comp = sintent.getComponent();
   8033                 if (comp == null) {
   8034                     ri = resolveIntent(
   8035                         sintent,
   8036                         specificTypes != null ? specificTypes[i] : null,
   8037                             flags, userId);
   8038                     if (ri == null) {
   8039                         continue;
   8040                     }
   8041                     if (ri == mResolveInfo) {
   8042                         // ACK!  Must do something better with this.
   8043                     }
   8044                     ai = ri.activityInfo;
   8045                     comp = new ComponentName(ai.applicationInfo.packageName,
   8046                             ai.name);
   8047                 } else {
   8048                     ai = getActivityInfo(comp, flags, userId);
   8049                     if (ai == null) {
   8050                         continue;
   8051                     }
   8052                 }
   8053 
   8054                 // Look for any generic query activities that are duplicates
   8055                 // of this specific one, and remove them from the results.
   8056                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
   8057                 N = results.size();
   8058                 int j;
   8059                 for (j=specificsPos; j<N; j++) {
   8060                     ResolveInfo sri = results.get(j);
   8061                     if ((sri.activityInfo.name.equals(comp.getClassName())
   8062                             && sri.activityInfo.applicationInfo.packageName.equals(
   8063                                     comp.getPackageName()))
   8064                         || (action != null && sri.filter.matchAction(action))) {
   8065                         results.remove(j);
   8066                         if (DEBUG_INTENT_MATCHING) Log.v(
   8067                             TAG, "Removing duplicate item from " + j
   8068                             + " due to specific " + specificsPos);
   8069                         if (ri == null) {
   8070                             ri = sri;
   8071                         }
   8072                         j--;
   8073                         N--;
   8074                     }
   8075                 }
   8076 
   8077                 // Add this specific item to its proper place.
   8078                 if (ri == null) {
   8079                     ri = new ResolveInfo();
   8080                     ri.activityInfo = ai;
   8081                 }
   8082                 results.add(specificsPos, ri);
   8083                 ri.specificIndex = i;
   8084                 specificsPos++;
   8085             }
   8086         }
   8087 
   8088         // Now we go through the remaining generic results and remove any
   8089         // duplicate actions that are found here.
   8090         N = results.size();
   8091         for (int i=specificsPos; i<N-1; i++) {
   8092             final ResolveInfo rii = results.get(i);
   8093             if (rii.filter == null) {
   8094                 continue;
   8095             }
   8096 
   8097             // Iterate over all of the actions of this result's intent
   8098             // filter...  typically this should be just one.
   8099             final Iterator<String> it = rii.filter.actionsIterator();
   8100             if (it == null) {
   8101                 continue;
   8102             }
   8103             while (it.hasNext()) {
   8104                 final String action = it.next();
   8105                 if (resultsAction != null && resultsAction.equals(action)) {
   8106                     // If this action was explicitly requested, then don't
   8107                     // remove things that have it.
   8108                     continue;
   8109                 }
   8110                 for (int j=i+1; j<N; j++) {
   8111                     final ResolveInfo rij = results.get(j);
   8112                     if (rij.filter != null && rij.filter.hasAction(action)) {
   8113                         results.remove(j);
   8114                         if (DEBUG_INTENT_MATCHING) Log.v(
   8115                             TAG, "Removing duplicate item from " + j
   8116                             + " due to action " + action + " at " + i);
   8117                         j--;
   8118                         N--;
   8119                     }
   8120                 }
   8121             }
   8122 
   8123             // If the caller didn't request filter information, drop it now
   8124             // so we don't have to marshall/unmarshall it.
   8125             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
   8126                 rii.filter = null;
   8127             }
   8128         }
   8129 
   8130         // Filter out the caller activity if so requested.
   8131         if (caller != null) {
   8132             N = results.size();
   8133             for (int i=0; i<N; i++) {
   8134                 ActivityInfo ainfo = results.get(i).activityInfo;
   8135                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
   8136                         && caller.getClassName().equals(ainfo.name)) {
   8137                     results.remove(i);
   8138                     break;
   8139                 }
   8140             }
   8141         }
   8142 
   8143         // If the caller didn't request filter information,
   8144         // drop them now so we don't have to
   8145         // marshall/unmarshall it.
   8146         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
   8147             N = results.size();
   8148             for (int i=0; i<N; i++) {
   8149                 results.get(i).filter = null;
   8150             }
   8151         }
   8152 
   8153         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
   8154         return results;
   8155     }
   8156 
   8157     @Override
   8158     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
   8159             String resolvedType, int flags, int userId) {
   8160         return new ParceledListSlice<>(
   8161                 queryIntentReceiversInternal(intent, resolvedType, flags, userId,
   8162                         false /*allowDynamicSplits*/));
   8163     }
   8164 
   8165     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
   8166             String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
   8167         if (!sUserManager.exists(userId)) return Collections.emptyList();
   8168         final int callingUid = Binder.getCallingUid();
   8169         enforceCrossUserPermission(callingUid, userId,
   8170                 false /*requireFullPermission*/, false /*checkShell*/,
   8171                 "query intent receivers");
   8172         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   8173         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
   8174                 false /*includeInstantApps*/);
   8175         ComponentName comp = intent.getComponent();
   8176         if (comp == null) {
   8177             if (intent.getSelector() != null) {
   8178                 intent = intent.getSelector();
   8179                 comp = intent.getComponent();
   8180             }
   8181         }
   8182         if (comp != null) {
   8183             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   8184             final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
   8185             if (ai != null) {
   8186                 // When specifying an explicit component, we prevent the activity from being
   8187                 // used when either 1) the calling package is normal and the activity is within
   8188                 // an instant application or 2) the calling package is ephemeral and the
   8189                 // activity is not visible to instant applications.
   8190                 final boolean matchInstantApp =
   8191                         (flags & PackageManager.MATCH_INSTANT) != 0;
   8192                 final boolean matchVisibleToInstantAppOnly =
   8193                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   8194                 final boolean matchExplicitlyVisibleOnly =
   8195                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
   8196                 final boolean isCallerInstantApp =
   8197                         instantAppPkgName != null;
   8198                 final boolean isTargetSameInstantApp =
   8199                         comp.getPackageName().equals(instantAppPkgName);
   8200                 final boolean isTargetInstantApp =
   8201                         (ai.applicationInfo.privateFlags
   8202                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   8203                 final boolean isTargetVisibleToInstantApp =
   8204                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
   8205                 final boolean isTargetExplicitlyVisibleToInstantApp =
   8206                         isTargetVisibleToInstantApp
   8207                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
   8208                 final boolean isTargetHiddenFromInstantApp =
   8209                         !isTargetVisibleToInstantApp
   8210                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
   8211                 final boolean blockResolution =
   8212                         !isTargetSameInstantApp
   8213                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   8214                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   8215                                         && isTargetHiddenFromInstantApp));
   8216                 if (!blockResolution) {
   8217                     ResolveInfo ri = new ResolveInfo();
   8218                     ri.activityInfo = ai;
   8219                     list.add(ri);
   8220                 }
   8221             }
   8222             return applyPostResolutionFilter(
   8223                     list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
   8224         }
   8225 
   8226         // reader
   8227         synchronized (mPackages) {
   8228             String pkgName = intent.getPackage();
   8229             if (pkgName == null) {
   8230                 final List<ResolveInfo> result =
   8231                         mReceivers.queryIntent(intent, resolvedType, flags, userId);
   8232                 return applyPostResolutionFilter(
   8233                         result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
   8234             }
   8235             final PackageParser.Package pkg = mPackages.get(pkgName);
   8236             if (pkg != null) {
   8237                 final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
   8238                         intent, resolvedType, flags, pkg.receivers, userId);
   8239                 return applyPostResolutionFilter(
   8240                         result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
   8241             }
   8242             return Collections.emptyList();
   8243         }
   8244     }
   8245 
   8246     @Override
   8247     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
   8248         final int callingUid = Binder.getCallingUid();
   8249         return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
   8250     }
   8251 
   8252     private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
   8253             int userId, int callingUid) {
   8254         if (!sUserManager.exists(userId)) return null;
   8255         flags = updateFlagsForResolve(
   8256                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
   8257         List<ResolveInfo> query = queryIntentServicesInternal(
   8258                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
   8259         if (query != null) {
   8260             if (query.size() >= 1) {
   8261                 // If there is more than one service with the same priority,
   8262                 // just arbitrarily pick the first one.
   8263                 return query.get(0);
   8264             }
   8265         }
   8266         return null;
   8267     }
   8268 
   8269     @Override
   8270     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
   8271             String resolvedType, int flags, int userId) {
   8272         final int callingUid = Binder.getCallingUid();
   8273         return new ParceledListSlice<>(queryIntentServicesInternal(
   8274                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
   8275     }
   8276 
   8277     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
   8278             String resolvedType, int flags, int userId, int callingUid,
   8279             boolean includeInstantApps) {
   8280         if (!sUserManager.exists(userId)) return Collections.emptyList();
   8281         enforceCrossUserPermission(callingUid, userId,
   8282                 false /*requireFullPermission*/, false /*checkShell*/,
   8283                 "query intent receivers");
   8284         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   8285         flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
   8286         ComponentName comp = intent.getComponent();
   8287         if (comp == null) {
   8288             if (intent.getSelector() != null) {
   8289                 intent = intent.getSelector();
   8290                 comp = intent.getComponent();
   8291             }
   8292         }
   8293         if (comp != null) {
   8294             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   8295             final ServiceInfo si = getServiceInfo(comp, flags, userId);
   8296             if (si != null) {
   8297                 // When specifying an explicit component, we prevent the service from being
   8298                 // used when either 1) the service is in an instant application and the
   8299                 // caller is not the same instant application or 2) the calling package is
   8300                 // ephemeral and the activity is not visible to ephemeral applications.
   8301                 final boolean matchInstantApp =
   8302                         (flags & PackageManager.MATCH_INSTANT) != 0;
   8303                 final boolean matchVisibleToInstantAppOnly =
   8304                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   8305                 final boolean isCallerInstantApp =
   8306                         instantAppPkgName != null;
   8307                 final boolean isTargetSameInstantApp =
   8308                         comp.getPackageName().equals(instantAppPkgName);
   8309                 final boolean isTargetInstantApp =
   8310                         (si.applicationInfo.privateFlags
   8311                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   8312                 final boolean isTargetHiddenFromInstantApp =
   8313                         (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
   8314                 final boolean blockResolution =
   8315                         !isTargetSameInstantApp
   8316                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   8317                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   8318                                         && isTargetHiddenFromInstantApp));
   8319                 if (!blockResolution) {
   8320                     final ResolveInfo ri = new ResolveInfo();
   8321                     ri.serviceInfo = si;
   8322                     list.add(ri);
   8323                 }
   8324             }
   8325             return list;
   8326         }
   8327 
   8328         // reader
   8329         synchronized (mPackages) {
   8330             String pkgName = intent.getPackage();
   8331             if (pkgName == null) {
   8332                 return applyPostServiceResolutionFilter(
   8333                         mServices.queryIntent(intent, resolvedType, flags, userId),
   8334                         instantAppPkgName);
   8335             }
   8336             final PackageParser.Package pkg = mPackages.get(pkgName);
   8337             if (pkg != null) {
   8338                 return applyPostServiceResolutionFilter(
   8339                         mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
   8340                                 userId),
   8341                         instantAppPkgName);
   8342             }
   8343             return Collections.emptyList();
   8344         }
   8345     }
   8346 
   8347     private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
   8348             String instantAppPkgName) {
   8349         if (instantAppPkgName == null) {
   8350             return resolveInfos;
   8351         }
   8352         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   8353             final ResolveInfo info = resolveInfos.get(i);
   8354             final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
   8355             // allow services that are defined in the provided package
   8356             if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
   8357                 if (info.serviceInfo.splitName != null
   8358                         && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
   8359                                 info.serviceInfo.splitName)) {
   8360                     // requested service is defined in a split that hasn't been installed yet.
   8361                     // add the installer to the resolve list
   8362                     if (DEBUG_EPHEMERAL) {
   8363                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
   8364                     }
   8365                     final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
   8366                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
   8367                             info.serviceInfo.packageName, info.serviceInfo.splitName,
   8368                             null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
   8369                             null /*failureIntent*/);
   8370                     // make sure this resolver is the default
   8371                     installerInfo.isDefault = true;
   8372                     installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
   8373                             | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
   8374                     // add a non-generic filter
   8375                     installerInfo.filter = new IntentFilter();
   8376                     // load resources from the correct package
   8377                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
   8378                     resolveInfos.set(i, installerInfo);
   8379                 }
   8380                 continue;
   8381             }
   8382             // allow services that have been explicitly exposed to ephemeral apps
   8383             if (!isEphemeralApp
   8384                     && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
   8385                 continue;
   8386             }
   8387             resolveInfos.remove(i);
   8388         }
   8389         return resolveInfos;
   8390     }
   8391 
   8392     @Override
   8393     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
   8394             String resolvedType, int flags, int userId) {
   8395         return new ParceledListSlice<>(
   8396                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
   8397     }
   8398 
   8399     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
   8400             Intent intent, String resolvedType, int flags, int userId) {
   8401         if (!sUserManager.exists(userId)) return Collections.emptyList();
   8402         final int callingUid = Binder.getCallingUid();
   8403         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   8404         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
   8405                 false /*includeInstantApps*/);
   8406         ComponentName comp = intent.getComponent();
   8407         if (comp == null) {
   8408             if (intent.getSelector() != null) {
   8409                 intent = intent.getSelector();
   8410                 comp = intent.getComponent();
   8411             }
   8412         }
   8413         if (comp != null) {
   8414             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   8415             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
   8416             if (pi != null) {
   8417                 // When specifying an explicit component, we prevent the provider from being
   8418                 // used when either 1) the provider is in an instant application and the
   8419                 // caller is not the same instant application or 2) the calling package is an
   8420                 // instant application and the provider is not visible to instant applications.
   8421                 final boolean matchInstantApp =
   8422                         (flags & PackageManager.MATCH_INSTANT) != 0;
   8423                 final boolean matchVisibleToInstantAppOnly =
   8424                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   8425                 final boolean isCallerInstantApp =
   8426                         instantAppPkgName != null;
   8427                 final boolean isTargetSameInstantApp =
   8428                         comp.getPackageName().equals(instantAppPkgName);
   8429                 final boolean isTargetInstantApp =
   8430                         (pi.applicationInfo.privateFlags
   8431                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   8432                 final boolean isTargetHiddenFromInstantApp =
   8433                         (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
   8434                 final boolean blockResolution =
   8435                         !isTargetSameInstantApp
   8436                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   8437                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   8438                                         && isTargetHiddenFromInstantApp));
   8439                 if (!blockResolution) {
   8440                     final ResolveInfo ri = new ResolveInfo();
   8441                     ri.providerInfo = pi;
   8442                     list.add(ri);
   8443                 }
   8444             }
   8445             return list;
   8446         }
   8447 
   8448         // reader
   8449         synchronized (mPackages) {
   8450             String pkgName = intent.getPackage();
   8451             if (pkgName == null) {
   8452                 return applyPostContentProviderResolutionFilter(
   8453                         mProviders.queryIntent(intent, resolvedType, flags, userId),
   8454                         instantAppPkgName);
   8455             }
   8456             final PackageParser.Package pkg = mPackages.get(pkgName);
   8457             if (pkg != null) {
   8458                 return applyPostContentProviderResolutionFilter(
   8459                         mProviders.queryIntentForPackage(
   8460                         intent, resolvedType, flags, pkg.providers, userId),
   8461                         instantAppPkgName);
   8462             }
   8463             return Collections.emptyList();
   8464         }
   8465     }
   8466 
   8467     private List<ResolveInfo> applyPostContentProviderResolutionFilter(
   8468             List<ResolveInfo> resolveInfos, String instantAppPkgName) {
   8469         if (instantAppPkgName == null) {
   8470             return resolveInfos;
   8471         }
   8472         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   8473             final ResolveInfo info = resolveInfos.get(i);
   8474             final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
   8475             // allow providers that are defined in the provided package
   8476             if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
   8477                 if (info.providerInfo.splitName != null
   8478                         && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
   8479                                 info.providerInfo.splitName)) {
   8480                     // requested provider is defined in a split that hasn't been installed yet.
   8481                     // add the installer to the resolve list
   8482                     if (DEBUG_EPHEMERAL) {
   8483                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
   8484                     }
   8485                     final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
   8486                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
   8487                             info.providerInfo.packageName, info.providerInfo.splitName,
   8488                             null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
   8489                             null /*failureIntent*/);
   8490                     // make sure this resolver is the default
   8491                     installerInfo.isDefault = true;
   8492                     installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
   8493                             | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
   8494                     // add a non-generic filter
   8495                     installerInfo.filter = new IntentFilter();
   8496                     // load resources from the correct package
   8497                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
   8498                     resolveInfos.set(i, installerInfo);
   8499                 }
   8500                 continue;
   8501             }
   8502             // allow providers that have been explicitly exposed to instant applications
   8503             if (!isEphemeralApp
   8504                     && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
   8505                 continue;
   8506             }
   8507             resolveInfos.remove(i);
   8508         }
   8509         return resolveInfos;
   8510     }
   8511 
   8512     @Override
   8513     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
   8514         final int callingUid = Binder.getCallingUid();
   8515         if (getInstantAppPackageName(callingUid) != null) {
   8516             return ParceledListSlice.emptyList();
   8517         }
   8518         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   8519         flags = updateFlagsForPackage(flags, userId, null);
   8520         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
   8521         enforceCrossUserPermission(callingUid, userId,
   8522                 true /* requireFullPermission */, false /* checkShell */,
   8523                 "get installed packages");
   8524 
   8525         // writer
   8526         synchronized (mPackages) {
   8527             ArrayList<PackageInfo> list;
   8528             if (listUninstalled) {
   8529                 list = new ArrayList<>(mSettings.mPackages.size());
   8530                 for (PackageSetting ps : mSettings.mPackages.values()) {
   8531                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
   8532                         continue;
   8533                     }
   8534                     if (filterAppAccessLPr(ps, callingUid, userId)) {
   8535                         continue;
   8536                     }
   8537                     final PackageInfo pi = generatePackageInfo(ps, flags, userId);
   8538                     if (pi != null) {
   8539                         list.add(pi);
   8540                     }
   8541                 }
   8542             } else {
   8543                 list = new ArrayList<>(mPackages.size());
   8544                 for (PackageParser.Package p : mPackages.values()) {
   8545                     final PackageSetting ps = (PackageSetting) p.mExtras;
   8546                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
   8547                         continue;
   8548                     }
   8549                     if (filterAppAccessLPr(ps, callingUid, userId)) {
   8550                         continue;
   8551                     }
   8552                     final PackageInfo pi = generatePackageInfo((PackageSetting)
   8553                             p.mExtras, flags, userId);
   8554                     if (pi != null) {
   8555                         list.add(pi);
   8556                     }
   8557                 }
   8558             }
   8559 
   8560             return new ParceledListSlice<>(list);
   8561         }
   8562     }
   8563 
   8564     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
   8565             String[] permissions, boolean[] tmp, int flags, int userId) {
   8566         int numMatch = 0;
   8567         final PermissionsState permissionsState = ps.getPermissionsState();
   8568         for (int i=0; i<permissions.length; i++) {
   8569             final String permission = permissions[i];
   8570             if (permissionsState.hasPermission(permission, userId)) {
   8571                 tmp[i] = true;
   8572                 numMatch++;
   8573             } else {
   8574                 tmp[i] = false;
   8575             }
   8576         }
   8577         if (numMatch == 0) {
   8578             return;
   8579         }
   8580         final PackageInfo pi = generatePackageInfo(ps, flags, userId);
   8581 
   8582         // The above might return null in cases of uninstalled apps or install-state
   8583         // skew across users/profiles.
   8584         if (pi != null) {
   8585             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
   8586                 if (numMatch == permissions.length) {
   8587                     pi.requestedPermissions = permissions;
   8588                 } else {
   8589                     pi.requestedPermissions = new String[numMatch];
   8590                     numMatch = 0;
   8591                     for (int i=0; i<permissions.length; i++) {
   8592                         if (tmp[i]) {
   8593                             pi.requestedPermissions[numMatch] = permissions[i];
   8594                             numMatch++;
   8595                         }
   8596                     }
   8597                 }
   8598             }
   8599             list.add(pi);
   8600         }
   8601     }
   8602 
   8603     @Override
   8604     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
   8605             String[] permissions, int flags, int userId) {
   8606         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   8607         flags = updateFlagsForPackage(flags, userId, permissions);
   8608         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8609                 true /* requireFullPermission */, false /* checkShell */,
   8610                 "get packages holding permissions");
   8611         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
   8612 
   8613         // writer
   8614         synchronized (mPackages) {
   8615             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
   8616             boolean[] tmpBools = new boolean[permissions.length];
   8617             if (listUninstalled) {
   8618                 for (PackageSetting ps : mSettings.mPackages.values()) {
   8619                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
   8620                             userId);
   8621                 }
   8622             } else {
   8623                 for (PackageParser.Package pkg : mPackages.values()) {
   8624                     PackageSetting ps = (PackageSetting)pkg.mExtras;
   8625                     if (ps != null) {
   8626                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
   8627                                 userId);
   8628                     }
   8629                 }
   8630             }
   8631 
   8632             return new ParceledListSlice<PackageInfo>(list);
   8633         }
   8634     }
   8635 
   8636     @Override
   8637     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
   8638         final int callingUid = Binder.getCallingUid();
   8639         if (getInstantAppPackageName(callingUid) != null) {
   8640             return ParceledListSlice.emptyList();
   8641         }
   8642         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   8643         flags = updateFlagsForApplication(flags, userId, null);
   8644         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
   8645 
   8646         // writer
   8647         synchronized (mPackages) {
   8648             ArrayList<ApplicationInfo> list;
   8649             if (listUninstalled) {
   8650                 list = new ArrayList<>(mSettings.mPackages.size());
   8651                 for (PackageSetting ps : mSettings.mPackages.values()) {
   8652                     ApplicationInfo ai;
   8653                     int effectiveFlags = flags;
   8654                     if (ps.isSystem()) {
   8655                         effectiveFlags |= PackageManager.MATCH_ANY_USER;
   8656                     }
   8657                     if (ps.pkg != null) {
   8658                         if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
   8659                             continue;
   8660                         }
   8661                         if (filterAppAccessLPr(ps, callingUid, userId)) {
   8662                             continue;
   8663                         }
   8664                         ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
   8665                                 ps.readUserState(userId), userId);
   8666                         if (ai != null) {
   8667                             ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
   8668                         }
   8669                     } else {
   8670                         // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
   8671                         // and already converts to externally visible package name
   8672                         ai = generateApplicationInfoFromSettingsLPw(ps.name,
   8673                                 callingUid, effectiveFlags, userId);
   8674                     }
   8675                     if (ai != null) {
   8676                         list.add(ai);
   8677                     }
   8678                 }
   8679             } else {
   8680                 list = new ArrayList<>(mPackages.size());
   8681                 for (PackageParser.Package p : mPackages.values()) {
   8682                     if (p.mExtras != null) {
   8683                         PackageSetting ps = (PackageSetting) p.mExtras;
   8684                         if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
   8685                             continue;
   8686                         }
   8687                         if (filterAppAccessLPr(ps, callingUid, userId)) {
   8688                             continue;
   8689                         }
   8690                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
   8691                                 ps.readUserState(userId), userId);
   8692                         if (ai != null) {
   8693                             ai.packageName = resolveExternalPackageNameLPr(p);
   8694                             list.add(ai);
   8695                         }
   8696                     }
   8697                 }
   8698             }
   8699 
   8700             return new ParceledListSlice<>(list);
   8701         }
   8702     }
   8703 
   8704     @Override
   8705     public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
   8706         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
   8707             return null;
   8708         }
   8709         if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
   8710             mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
   8711                     "getEphemeralApplications");
   8712         }
   8713         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8714                 true /* requireFullPermission */, false /* checkShell */,
   8715                 "getEphemeralApplications");
   8716         synchronized (mPackages) {
   8717             List<InstantAppInfo> instantApps = mInstantAppRegistry
   8718                     .getInstantAppsLPr(userId);
   8719             if (instantApps != null) {
   8720                 return new ParceledListSlice<>(instantApps);
   8721             }
   8722         }
   8723         return null;
   8724     }
   8725 
   8726     @Override
   8727     public boolean isInstantApp(String packageName, int userId) {
   8728         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8729                 true /* requireFullPermission */, false /* checkShell */,
   8730                 "isInstantApp");
   8731         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
   8732             return false;
   8733         }
   8734 
   8735         synchronized (mPackages) {
   8736             int callingUid = Binder.getCallingUid();
   8737             if (Process.isIsolated(callingUid)) {
   8738                 callingUid = mIsolatedOwners.get(callingUid);
   8739             }
   8740             final PackageSetting ps = mSettings.mPackages.get(packageName);
   8741             PackageParser.Package pkg = mPackages.get(packageName);
   8742             final boolean returnAllowed =
   8743                     ps != null
   8744                     && (isCallerSameApp(packageName, callingUid)
   8745                             || canViewInstantApps(callingUid, userId)
   8746                             || mInstantAppRegistry.isInstantAccessGranted(
   8747                                     userId, UserHandle.getAppId(callingUid), ps.appId));
   8748             if (returnAllowed) {
   8749                 return ps.getInstantApp(userId);
   8750             }
   8751         }
   8752         return false;
   8753     }
   8754 
   8755     @Override
   8756     public byte[] getInstantAppCookie(String packageName, int userId) {
   8757         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
   8758             return null;
   8759         }
   8760 
   8761         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8762                 true /* requireFullPermission */, false /* checkShell */,
   8763                 "getInstantAppCookie");
   8764         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
   8765             return null;
   8766         }
   8767         synchronized (mPackages) {
   8768             return mInstantAppRegistry.getInstantAppCookieLPw(
   8769                     packageName, userId);
   8770         }
   8771     }
   8772 
   8773     @Override
   8774     public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
   8775         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
   8776             return true;
   8777         }
   8778 
   8779         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8780                 true /* requireFullPermission */, true /* checkShell */,
   8781                 "setInstantAppCookie");
   8782         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
   8783             return false;
   8784         }
   8785         synchronized (mPackages) {
   8786             return mInstantAppRegistry.setInstantAppCookieLPw(
   8787                     packageName, cookie, userId);
   8788         }
   8789     }
   8790 
   8791     @Override
   8792     public Bitmap getInstantAppIcon(String packageName, int userId) {
   8793         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
   8794             return null;
   8795         }
   8796 
   8797         if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
   8798             mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
   8799                     "getInstantAppIcon");
   8800         }
   8801         enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8802                 true /* requireFullPermission */, false /* checkShell */,
   8803                 "getInstantAppIcon");
   8804 
   8805         synchronized (mPackages) {
   8806             return mInstantAppRegistry.getInstantAppIconLPw(
   8807                     packageName, userId);
   8808         }
   8809     }
   8810 
   8811     private boolean isCallerSameApp(String packageName, int uid) {
   8812         PackageParser.Package pkg = mPackages.get(packageName);
   8813         return pkg != null
   8814                 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
   8815     }
   8816 
   8817     @Override
   8818     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
   8819         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   8820             return ParceledListSlice.emptyList();
   8821         }
   8822         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
   8823     }
   8824 
   8825     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
   8826         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
   8827 
   8828         // reader
   8829         synchronized (mPackages) {
   8830             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
   8831             final int userId = UserHandle.getCallingUserId();
   8832             while (i.hasNext()) {
   8833                 final PackageParser.Package p = i.next();
   8834                 if (p.applicationInfo == null) continue;
   8835 
   8836                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
   8837                         && !p.applicationInfo.isDirectBootAware();
   8838                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
   8839                         && p.applicationInfo.isDirectBootAware();
   8840 
   8841                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
   8842                         && (!mSafeMode || isSystemApp(p))
   8843                         && (matchesUnaware || matchesAware)) {
   8844                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
   8845                     if (ps != null) {
   8846                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
   8847                                 ps.readUserState(userId), userId);
   8848                         if (ai != null) {
   8849                             finalList.add(ai);
   8850                         }
   8851                     }
   8852                 }
   8853             }
   8854         }
   8855 
   8856         return finalList;
   8857     }
   8858 
   8859     @Override
   8860     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
   8861         if (!sUserManager.exists(userId)) return null;
   8862         flags = updateFlagsForComponent(flags, userId, name);
   8863         final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
   8864         // reader
   8865         synchronized (mPackages) {
   8866             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
   8867             PackageSetting ps = provider != null
   8868                     ? mSettings.mPackages.get(provider.owner.packageName)
   8869                     : null;
   8870             if (ps != null) {
   8871                 final boolean isInstantApp = ps.getInstantApp(userId);
   8872                 // normal application; filter out instant application provider
   8873                 if (instantAppPkgName == null && isInstantApp) {
   8874                     return null;
   8875                 }
   8876                 // instant application; filter out other instant applications
   8877                 if (instantAppPkgName != null
   8878                         && isInstantApp
   8879                         && !provider.owner.packageName.equals(instantAppPkgName)) {
   8880                     return null;
   8881                 }
   8882                 // instant application; filter out non-exposed provider
   8883                 if (instantAppPkgName != null
   8884                         && !isInstantApp
   8885                         && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
   8886                     return null;
   8887                 }
   8888                 // provider not enabled
   8889                 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
   8890                     return null;
   8891                 }
   8892                 return PackageParser.generateProviderInfo(
   8893                         provider, flags, ps.readUserState(userId), userId);
   8894             }
   8895             return null;
   8896         }
   8897     }
   8898 
   8899     /**
   8900      * @deprecated
   8901      */
   8902     @Deprecated
   8903     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
   8904         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   8905             return;
   8906         }
   8907         // reader
   8908         synchronized (mPackages) {
   8909             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
   8910                     .entrySet().iterator();
   8911             final int userId = UserHandle.getCallingUserId();
   8912             while (i.hasNext()) {
   8913                 Map.Entry<String, PackageParser.Provider> entry = i.next();
   8914                 PackageParser.Provider p = entry.getValue();
   8915                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
   8916 
   8917                 if (ps != null && p.syncable
   8918                         && (!mSafeMode || (p.info.applicationInfo.flags
   8919                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
   8920                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
   8921                             ps.readUserState(userId), userId);
   8922                     if (info != null) {
   8923                         outNames.add(entry.getKey());
   8924                         outInfo.add(info);
   8925                     }
   8926                 }
   8927             }
   8928         }
   8929     }
   8930 
   8931     @Override
   8932     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
   8933             int uid, int flags, String metaDataKey) {
   8934         final int callingUid = Binder.getCallingUid();
   8935         final int userId = processName != null ? UserHandle.getUserId(uid)
   8936                 : UserHandle.getCallingUserId();
   8937         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   8938         flags = updateFlagsForComponent(flags, userId, processName);
   8939         ArrayList<ProviderInfo> finalList = null;
   8940         // reader
   8941         synchronized (mPackages) {
   8942             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
   8943             while (i.hasNext()) {
   8944                 final PackageParser.Provider p = i.next();
   8945                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
   8946                 if (ps != null && p.info.authority != null
   8947                         && (processName == null
   8948                                 || (p.info.processName.equals(processName)
   8949                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
   8950                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
   8951 
   8952                     // See PM.queryContentProviders()'s javadoc for why we have the metaData
   8953                     // parameter.
   8954                     if (metaDataKey != null
   8955                             && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
   8956                         continue;
   8957                     }
   8958                     final ComponentName component =
   8959                             new ComponentName(p.info.packageName, p.info.name);
   8960                     if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
   8961                         continue;
   8962                     }
   8963                     if (finalList == null) {
   8964                         finalList = new ArrayList<ProviderInfo>(3);
   8965                     }
   8966                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
   8967                             ps.readUserState(userId), userId);
   8968                     if (info != null) {
   8969                         finalList.add(info);
   8970                     }
   8971                 }
   8972             }
   8973         }
   8974 
   8975         if (finalList != null) {
   8976             Collections.sort(finalList, mProviderInitOrderSorter);
   8977             return new ParceledListSlice<ProviderInfo>(finalList);
   8978         }
   8979 
   8980         return ParceledListSlice.emptyList();
   8981     }
   8982 
   8983     @Override
   8984     public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
   8985         // reader
   8986         synchronized (mPackages) {
   8987             final int callingUid = Binder.getCallingUid();
   8988             final int callingUserId = UserHandle.getUserId(callingUid);
   8989             final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   8990             if (ps == null) return null;
   8991             if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
   8992                 return null;
   8993             }
   8994             final PackageParser.Instrumentation i = mInstrumentation.get(component);
   8995             return PackageParser.generateInstrumentationInfo(i, flags);
   8996         }
   8997     }
   8998 
   8999     @Override
   9000     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
   9001             String targetPackage, int flags) {
   9002         final int callingUid = Binder.getCallingUid();
   9003         final int callingUserId = UserHandle.getUserId(callingUid);
   9004         final PackageSetting ps = mSettings.mPackages.get(targetPackage);
   9005         if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   9006             return ParceledListSlice.emptyList();
   9007         }
   9008         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
   9009     }
   9010 
   9011     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
   9012             int flags) {
   9013         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
   9014 
   9015         // reader
   9016         synchronized (mPackages) {
   9017             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
   9018             while (i.hasNext()) {
   9019                 final PackageParser.Instrumentation p = i.next();
   9020                 if (targetPackage == null
   9021                         || targetPackage.equals(p.info.targetPackage)) {
   9022                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
   9023                             flags);
   9024                     if (ii != null) {
   9025                         finalList.add(ii);
   9026                     }
   9027                 }
   9028             }
   9029         }
   9030 
   9031         return finalList;
   9032     }
   9033 
   9034     private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
   9035         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
   9036         try {
   9037             scanDirLI(dir, parseFlags, scanFlags, currentTime);
   9038         } finally {
   9039             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9040         }
   9041     }
   9042 
   9043     private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
   9044         final File[] files = dir.listFiles();
   9045         if (ArrayUtils.isEmpty(files)) {
   9046             Log.d(TAG, "No files in app dir " + dir);
   9047             return;
   9048         }
   9049 
   9050         if (DEBUG_PACKAGE_SCANNING) {
   9051             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
   9052                     + " flags=0x" + Integer.toHexString(parseFlags));
   9053         }
   9054         ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
   9055                 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
   9056                 mParallelPackageParserCallback);
   9057 
   9058         // Submit files for parsing in parallel
   9059         int fileCount = 0;
   9060         for (File file : files) {
   9061             final boolean isPackage = (isApkFile(file) || file.isDirectory())
   9062                     && !PackageInstallerService.isStageName(file.getName());
   9063             if (!isPackage) {
   9064                 // Ignore entries which are not packages
   9065                 continue;
   9066             }
   9067             parallelPackageParser.submit(file, parseFlags);
   9068             fileCount++;
   9069         }
   9070 
   9071         // Process results one by one
   9072         for (; fileCount > 0; fileCount--) {
   9073             ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
   9074             Throwable throwable = parseResult.throwable;
   9075             int errorCode = PackageManager.INSTALL_SUCCEEDED;
   9076 
   9077             if (throwable == null) {
   9078                 // Static shared libraries have synthetic package names
   9079                 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
   9080                     renameStaticSharedLibraryPackage(parseResult.pkg);
   9081                 }
   9082                 try {
   9083                     if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
   9084                         scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
   9085                                 currentTime, null);
   9086                     }
   9087                 } catch (PackageManagerException e) {
   9088                     errorCode = e.error;
   9089                     Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
   9090                 }
   9091             } else if (throwable instanceof PackageParser.PackageParserException) {
   9092                 PackageParser.PackageParserException e = (PackageParser.PackageParserException)
   9093                         throwable;
   9094                 errorCode = e.error;
   9095                 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
   9096             } else {
   9097                 throw new IllegalStateException("Unexpected exception occurred while parsing "
   9098                         + parseResult.scanFile, throwable);
   9099             }
   9100 
   9101             // Delete invalid userdata apps
   9102             if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
   9103                     errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
   9104                 logCriticalInfo(Log.WARN,
   9105                         "Deleting invalid package at " + parseResult.scanFile);
   9106                 removeCodePathLI(parseResult.scanFile);
   9107             }
   9108         }
   9109         parallelPackageParser.close();
   9110     }
   9111 
   9112     private static File getSettingsProblemFile() {
   9113         File dataDir = Environment.getDataDirectory();
   9114         File systemDir = new File(dataDir, "system");
   9115         File fname = new File(systemDir, "uiderrors.txt");
   9116         return fname;
   9117     }
   9118 
   9119     static void reportSettingsProblem(int priority, String msg) {
   9120         logCriticalInfo(priority, msg);
   9121     }
   9122 
   9123     public static void logCriticalInfo(int priority, String msg) {
   9124         Slog.println(priority, TAG, msg);
   9125         EventLogTags.writePmCriticalInfo(msg);
   9126         try {
   9127             File fname = getSettingsProblemFile();
   9128             FileOutputStream out = new FileOutputStream(fname, true);
   9129             PrintWriter pw = new FastPrintWriter(out);
   9130             SimpleDateFormat formatter = new SimpleDateFormat();
   9131             String dateString = formatter.format(new Date(System.currentTimeMillis()));
   9132             pw.println(dateString + ": " + msg);
   9133             pw.close();
   9134             FileUtils.setPermissions(
   9135                     fname.toString(),
   9136                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
   9137                     -1, -1);
   9138         } catch (java.io.IOException e) {
   9139         }
   9140     }
   9141 
   9142     private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
   9143         if (srcFile.isDirectory()) {
   9144             final File baseFile = new File(pkg.baseCodePath);
   9145             long maxModifiedTime = baseFile.lastModified();
   9146             if (pkg.splitCodePaths != null) {
   9147                 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
   9148                     final File splitFile = new File(pkg.splitCodePaths[i]);
   9149                     maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
   9150                 }
   9151             }
   9152             return maxModifiedTime;
   9153         }
   9154         return srcFile.lastModified();
   9155     }
   9156 
   9157     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
   9158             final int policyFlags) throws PackageManagerException {
   9159         // When upgrading from pre-N MR1, verify the package time stamp using the package
   9160         // directory and not the APK file.
   9161         final long lastModifiedTime = mIsPreNMR1Upgrade
   9162                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
   9163         if (ps != null
   9164                 && ps.codePath.equals(srcFile)
   9165                 && ps.timeStamp == lastModifiedTime
   9166                 && !isCompatSignatureUpdateNeeded(pkg)
   9167                 && !isRecoverSignatureUpdateNeeded(pkg)) {
   9168             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
   9169             KeySetManagerService ksms = mSettings.mKeySetManagerService;
   9170             ArraySet<PublicKey> signingKs;
   9171             synchronized (mPackages) {
   9172                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
   9173             }
   9174             if (ps.signatures.mSignatures != null
   9175                     && ps.signatures.mSignatures.length != 0
   9176                     && signingKs != null) {
   9177                 // Optimization: reuse the existing cached certificates
   9178                 // if the package appears to be unchanged.
   9179                 pkg.mSignatures = ps.signatures.mSignatures;
   9180                 pkg.mSigningKeys = signingKs;
   9181                 return;
   9182             }
   9183 
   9184             Slog.w(TAG, "PackageSetting for " + ps.name
   9185                     + " is missing signatures.  Collecting certs again to recover them.");
   9186         } else {
   9187             Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
   9188         }
   9189 
   9190         try {
   9191             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
   9192             PackageParser.collectCertificates(pkg, policyFlags);
   9193         } catch (PackageParserException e) {
   9194             throw PackageManagerException.from(e);
   9195         } finally {
   9196             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9197         }
   9198     }
   9199 
   9200     /**
   9201      *  Traces a package scan.
   9202      *  @see #scanPackageLI(File, int, int, long, UserHandle)
   9203      */
   9204     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
   9205             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
   9206         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
   9207         try {
   9208             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
   9209         } finally {
   9210             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9211         }
   9212     }
   9213 
   9214     /**
   9215      *  Scans a package and returns the newly parsed package.
   9216      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
   9217      */
   9218     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
   9219             long currentTime, UserHandle user) throws PackageManagerException {
   9220         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
   9221         PackageParser pp = new PackageParser();
   9222         pp.setSeparateProcesses(mSeparateProcesses);
   9223         pp.setOnlyCoreApps(mOnlyCore);
   9224         pp.setDisplayMetrics(mMetrics);
   9225         pp.setCallback(mPackageParserCallback);
   9226 
   9227         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
   9228             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
   9229         }
   9230 
   9231         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
   9232         final PackageParser.Package pkg;
   9233         try {
   9234             pkg = pp.parsePackage(scanFile, parseFlags);
   9235         } catch (PackageParserException e) {
   9236             throw PackageManagerException.from(e);
   9237         } finally {
   9238             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9239         }
   9240 
   9241         // Static shared libraries have synthetic package names
   9242         if (pkg.applicationInfo.isStaticSharedLibrary()) {
   9243             renameStaticSharedLibraryPackage(pkg);
   9244         }
   9245 
   9246         return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
   9247     }
   9248 
   9249     /**
   9250      *  Scans a package and returns the newly parsed package.
   9251      *  @throws PackageManagerException on a parse error.
   9252      */
   9253     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
   9254             final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
   9255             throws PackageManagerException {
   9256         // If the package has children and this is the first dive in the function
   9257         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
   9258         // packages (parent and children) would be successfully scanned before the
   9259         // actual scan since scanning mutates internal state and we want to atomically
   9260         // install the package and its children.
   9261         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
   9262             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
   9263                 scanFlags |= SCAN_CHECK_ONLY;
   9264             }
   9265         } else {
   9266             scanFlags &= ~SCAN_CHECK_ONLY;
   9267         }
   9268 
   9269         // Scan the parent
   9270         PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
   9271                 scanFlags, currentTime, user);
   9272 
   9273         // Scan the children
   9274         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9275         for (int i = 0; i < childCount; i++) {
   9276             PackageParser.Package childPackage = pkg.childPackages.get(i);
   9277             scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
   9278                     currentTime, user);
   9279         }
   9280 
   9281 
   9282         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
   9283             return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
   9284         }
   9285 
   9286         return scannedPkg;
   9287     }
   9288 
   9289     /**
   9290      *  Scans a package and returns the newly parsed package.
   9291      *  @throws PackageManagerException on a parse error.
   9292      */
   9293     private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
   9294             int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
   9295             throws PackageManagerException {
   9296         PackageSetting ps = null;
   9297         PackageSetting updatedPkg;
   9298         // reader
   9299         synchronized (mPackages) {
   9300             // Look to see if we already know about this package.
   9301             String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
   9302             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
   9303                 // This package has been renamed to its original name.  Let's
   9304                 // use that.
   9305                 ps = mSettings.getPackageLPr(oldName);
   9306             }
   9307             // If there was no original package, see one for the real package name.
   9308             if (ps == null) {
   9309                 ps = mSettings.getPackageLPr(pkg.packageName);
   9310             }
   9311             // Check to see if this package could be hiding/updating a system
   9312             // package.  Must look for it either under the original or real
   9313             // package name depending on our state.
   9314             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
   9315             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
   9316 
   9317             // If this is a package we don't know about on the system partition, we
   9318             // may need to remove disabled child packages on the system partition
   9319             // or may need to not add child packages if the parent apk is updated
   9320             // on the data partition and no longer defines this child package.
   9321             if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
   9322                 // If this is a parent package for an updated system app and this system
   9323                 // app got an OTA update which no longer defines some of the child packages
   9324                 // we have to prune them from the disabled system packages.
   9325                 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
   9326                 if (disabledPs != null) {
   9327                     final int scannedChildCount = (pkg.childPackages != null)
   9328                             ? pkg.childPackages.size() : 0;
   9329                     final int disabledChildCount = disabledPs.childPackageNames != null
   9330                             ? disabledPs.childPackageNames.size() : 0;
   9331                     for (int i = 0; i < disabledChildCount; i++) {
   9332                         String disabledChildPackageName = disabledPs.childPackageNames.get(i);
   9333                         boolean disabledPackageAvailable = false;
   9334                         for (int j = 0; j < scannedChildCount; j++) {
   9335                             PackageParser.Package childPkg = pkg.childPackages.get(j);
   9336                             if (childPkg.packageName.equals(disabledChildPackageName)) {
   9337                                 disabledPackageAvailable = true;
   9338                                 break;
   9339                             }
   9340                          }
   9341                          if (!disabledPackageAvailable) {
   9342                              mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
   9343                          }
   9344                     }
   9345                 }
   9346             }
   9347         }
   9348 
   9349         final boolean isUpdatedPkg = updatedPkg != null;
   9350         final boolean isUpdatedSystemPkg = isUpdatedPkg
   9351                 && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
   9352         boolean isUpdatedPkgBetter = false;
   9353         // First check if this is a system package that may involve an update
   9354         if (isUpdatedSystemPkg) {
   9355             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
   9356             // it needs to drop FLAG_PRIVILEGED.
   9357             if (locationIsPrivileged(scanFile)) {
   9358                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
   9359             } else {
   9360                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
   9361             }
   9362 
   9363             if (ps != null && !ps.codePath.equals(scanFile)) {
   9364                 // The path has changed from what was last scanned...  check the
   9365                 // version of the new path against what we have stored to determine
   9366                 // what to do.
   9367                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
   9368                 if (pkg.mVersionCode <= ps.versionCode) {
   9369                     // The system package has been updated and the code path does not match
   9370                     // Ignore entry. Skip it.
   9371                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
   9372                             + " ignored: updated version " + ps.versionCode
   9373                             + " better than this " + pkg.mVersionCode);
   9374                     if (!updatedPkg.codePath.equals(scanFile)) {
   9375                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
   9376                                 + ps.name + " changing from " + updatedPkg.codePathString
   9377                                 + " to " + scanFile);
   9378                         updatedPkg.codePath = scanFile;
   9379                         updatedPkg.codePathString = scanFile.toString();
   9380                         updatedPkg.resourcePath = scanFile;
   9381                         updatedPkg.resourcePathString = scanFile.toString();
   9382                     }
   9383                     updatedPkg.pkg = pkg;
   9384                     updatedPkg.versionCode = pkg.mVersionCode;
   9385 
   9386                     // Update the disabled system child packages to point to the package too.
   9387                     final int childCount = updatedPkg.childPackageNames != null
   9388                             ? updatedPkg.childPackageNames.size() : 0;
   9389                     for (int i = 0; i < childCount; i++) {
   9390                         String childPackageName = updatedPkg.childPackageNames.get(i);
   9391                         PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
   9392                                 childPackageName);
   9393                         if (updatedChildPkg != null) {
   9394                             updatedChildPkg.pkg = pkg;
   9395                             updatedChildPkg.versionCode = pkg.mVersionCode;
   9396                         }
   9397                     }
   9398                 } else {
   9399                     // The current app on the system partition is better than
   9400                     // what we have updated to on the data partition; switch
   9401                     // back to the system partition version.
   9402                     // At this point, its safely assumed that package installation for
   9403                     // apps in system partition will go through. If not there won't be a working
   9404                     // version of the app
   9405                     // writer
   9406                     synchronized (mPackages) {
   9407                         // Just remove the loaded entries from package lists.
   9408                         mPackages.remove(ps.name);
   9409                     }
   9410 
   9411                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
   9412                             + " reverting from " + ps.codePathString
   9413                             + ": new version " + pkg.mVersionCode
   9414                             + " better than installed " + ps.versionCode);
   9415 
   9416                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
   9417                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
   9418                     synchronized (mInstallLock) {
   9419                         args.cleanUpResourcesLI();
   9420                     }
   9421                     synchronized (mPackages) {
   9422                         mSettings.enableSystemPackageLPw(ps.name);
   9423                     }
   9424                     isUpdatedPkgBetter = true;
   9425                 }
   9426             }
   9427         }
   9428 
   9429         String resourcePath = null;
   9430         String baseResourcePath = null;
   9431         if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
   9432             if (ps != null && ps.resourcePathString != null) {
   9433                 resourcePath = ps.resourcePathString;
   9434                 baseResourcePath = ps.resourcePathString;
   9435             } else {
   9436                 // Should not happen at all. Just log an error.
   9437                 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
   9438             }
   9439         } else {
   9440             resourcePath = pkg.codePath;
   9441             baseResourcePath = pkg.baseCodePath;
   9442         }
   9443 
   9444         // Set application objects path explicitly.
   9445         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
   9446         pkg.setApplicationInfoCodePath(pkg.codePath);
   9447         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
   9448         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
   9449         pkg.setApplicationInfoResourcePath(resourcePath);
   9450         pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
   9451         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
   9452 
   9453         // throw an exception if we have an update to a system application, but, it's not more
   9454         // recent than the package we've already scanned
   9455         if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
   9456             // Set CPU Abis to application info.
   9457             if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
   9458                 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
   9459                 derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
   9460             } else {
   9461                 pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
   9462                 pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
   9463             }
   9464 
   9465             throw new PackageManagerException(