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_DEVICE_ADMINS;
     22 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
     23 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
     24 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
     25 import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
     26 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
     27 import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
     28 import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
     29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
     30 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
     31 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
     32 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
     33 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
     34 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
     35 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
     36 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
     37 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
     38 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
     39 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
     40 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
     41 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
     42 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
     43 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
     44 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
     45 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
     46 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
     47 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
     48 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
     49 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
     50 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
     51 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
     52 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
     53 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
     54 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
     55 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
     56 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
     57 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
     58 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
     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.isApkFile;
     86 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
     87 import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
     88 import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
     89 import static android.system.OsConstants.O_CREAT;
     90 import static android.system.OsConstants.O_RDWR;
     91 
     92 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
     93 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
     94 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
     95 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
     96 import static com.android.internal.util.ArrayUtils.appendInt;
     97 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
     98 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
     99 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
    100 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
    101 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
    102 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
    103 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
    104 import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
    105 import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
    106 import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
    107 import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
    108 import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
    109 import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
    110 import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
    111 import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
    112 import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
    113 import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
    114 import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
    115 
    116 import android.Manifest;
    117 import android.annotation.IntDef;
    118 import android.annotation.NonNull;
    119 import android.annotation.Nullable;
    120 import android.annotation.UserIdInt;
    121 import android.app.ActivityManager;
    122 import android.app.ActivityManagerInternal;
    123 import android.app.AppOpsManager;
    124 import android.app.IActivityManager;
    125 import android.app.ResourcesManager;
    126 import android.app.admin.IDevicePolicyManager;
    127 import android.app.admin.SecurityLog;
    128 import android.app.backup.IBackupManager;
    129 import android.content.BroadcastReceiver;
    130 import android.content.ComponentName;
    131 import android.content.ContentResolver;
    132 import android.content.Context;
    133 import android.content.IIntentReceiver;
    134 import android.content.Intent;
    135 import android.content.IntentFilter;
    136 import android.content.IntentSender;
    137 import android.content.IntentSender.SendIntentException;
    138 import android.content.ServiceConnection;
    139 import android.content.pm.ActivityInfo;
    140 import android.content.pm.ApplicationInfo;
    141 import android.content.pm.AppsQueryHelper;
    142 import android.content.pm.AuxiliaryResolveInfo;
    143 import android.content.pm.ChangedPackages;
    144 import android.content.pm.ComponentInfo;
    145 import android.content.pm.FallbackCategoryProvider;
    146 import android.content.pm.FeatureInfo;
    147 import android.content.pm.IDexModuleRegisterCallback;
    148 import android.content.pm.IOnPermissionsChangeListener;
    149 import android.content.pm.IPackageDataObserver;
    150 import android.content.pm.IPackageDeleteObserver;
    151 import android.content.pm.IPackageDeleteObserver2;
    152 import android.content.pm.IPackageInstallObserver2;
    153 import android.content.pm.IPackageInstaller;
    154 import android.content.pm.IPackageManager;
    155 import android.content.pm.IPackageManagerNative;
    156 import android.content.pm.IPackageMoveObserver;
    157 import android.content.pm.IPackageStatsObserver;
    158 import android.content.pm.InstantAppInfo;
    159 import android.content.pm.InstantAppRequest;
    160 import android.content.pm.InstantAppResolveInfo;
    161 import android.content.pm.InstrumentationInfo;
    162 import android.content.pm.IntentFilterVerificationInfo;
    163 import android.content.pm.KeySet;
    164 import android.content.pm.PackageCleanItem;
    165 import android.content.pm.PackageInfo;
    166 import android.content.pm.PackageInfoLite;
    167 import android.content.pm.PackageInstaller;
    168 import android.content.pm.PackageList;
    169 import android.content.pm.PackageManager;
    170 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
    171 import android.content.pm.PackageManagerInternal;
    172 import android.content.pm.PackageManagerInternal.PackageListObserver;
    173 import android.content.pm.PackageParser;
    174 import android.content.pm.PackageParser.ActivityIntentInfo;
    175 import android.content.pm.PackageParser.Package;
    176 import android.content.pm.PackageParser.PackageLite;
    177 import android.content.pm.PackageParser.PackageParserException;
    178 import android.content.pm.PackageParser.ParseFlags;
    179 import android.content.pm.PackageParser.ServiceIntentInfo;
    180 import android.content.pm.PackageParser.SigningDetails;
    181 import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
    182 import android.content.pm.PackageStats;
    183 import android.content.pm.PackageUserState;
    184 import android.content.pm.ParceledListSlice;
    185 import android.content.pm.PermissionGroupInfo;
    186 import android.content.pm.PermissionInfo;
    187 import android.content.pm.ProviderInfo;
    188 import android.content.pm.ResolveInfo;
    189 import android.content.pm.SELinuxUtil;
    190 import android.content.pm.ServiceInfo;
    191 import android.content.pm.SharedLibraryInfo;
    192 import android.content.pm.Signature;
    193 import android.content.pm.UserInfo;
    194 import android.content.pm.VerifierDeviceIdentity;
    195 import android.content.pm.VerifierInfo;
    196 import android.content.pm.VersionedPackage;
    197 import android.content.pm.dex.ArtManager;
    198 import android.content.pm.dex.DexMetadataHelper;
    199 import android.content.pm.dex.IArtManager;
    200 import android.content.res.Resources;
    201 import android.database.ContentObserver;
    202 import android.graphics.Bitmap;
    203 import android.hardware.display.DisplayManager;
    204 import android.net.Uri;
    205 import android.os.AsyncTask;
    206 import android.os.Binder;
    207 import android.os.Build;
    208 import android.os.Bundle;
    209 import android.os.Debug;
    210 import android.os.Environment;
    211 import android.os.Environment.UserEnvironment;
    212 import android.os.FileUtils;
    213 import android.os.Handler;
    214 import android.os.IBinder;
    215 import android.os.Looper;
    216 import android.os.Message;
    217 import android.os.Parcel;
    218 import android.os.ParcelFileDescriptor;
    219 import android.os.PatternMatcher;
    220 import android.os.PersistableBundle;
    221 import android.os.Process;
    222 import android.os.RemoteCallbackList;
    223 import android.os.RemoteException;
    224 import android.os.ResultReceiver;
    225 import android.os.SELinux;
    226 import android.os.ServiceManager;
    227 import android.os.ShellCallback;
    228 import android.os.SystemClock;
    229 import android.os.SystemProperties;
    230 import android.os.Trace;
    231 import android.os.UserHandle;
    232 import android.os.UserManager;
    233 import android.os.UserManagerInternal;
    234 import android.os.storage.IStorageManager;
    235 import android.os.storage.StorageEventListener;
    236 import android.os.storage.StorageManager;
    237 import android.os.storage.StorageManagerInternal;
    238 import android.os.storage.VolumeInfo;
    239 import android.os.storage.VolumeRecord;
    240 import android.provider.Settings.Global;
    241 import android.provider.Settings.Secure;
    242 import android.security.KeyStore;
    243 import android.security.SystemKeyStore;
    244 import android.service.pm.PackageServiceDumpProto;
    245 import android.system.ErrnoException;
    246 import android.system.Os;
    247 import android.text.TextUtils;
    248 import android.text.format.DateUtils;
    249 import android.util.ArrayMap;
    250 import android.util.ArraySet;
    251 import android.util.Base64;
    252 import android.util.ByteStringUtils;
    253 import android.util.DisplayMetrics;
    254 import android.util.EventLog;
    255 import android.util.ExceptionUtils;
    256 import android.util.Log;
    257 import android.util.LogPrinter;
    258 import android.util.LongSparseArray;
    259 import android.util.LongSparseLongArray;
    260 import android.util.MathUtils;
    261 import android.util.PackageUtils;
    262 import android.util.Pair;
    263 import android.util.PrintStreamPrinter;
    264 import android.util.Slog;
    265 import android.util.SparseArray;
    266 import android.util.SparseBooleanArray;
    267 import android.util.SparseIntArray;
    268 import android.util.TimingsTraceLog;
    269 import android.util.Xml;
    270 import android.util.jar.StrictJarFile;
    271 import android.util.proto.ProtoOutputStream;
    272 import android.view.Display;
    273 
    274 import com.android.internal.R;
    275 import com.android.internal.annotations.GuardedBy;
    276 import com.android.internal.app.IMediaContainerService;
    277 import com.android.internal.app.ResolverActivity;
    278 import com.android.internal.content.NativeLibraryHelper;
    279 import com.android.internal.content.PackageHelper;
    280 import com.android.internal.logging.MetricsLogger;
    281 import com.android.internal.os.IParcelFileDescriptorFactory;
    282 import com.android.internal.os.SomeArgs;
    283 import com.android.internal.os.Zygote;
    284 import com.android.internal.telephony.CarrierAppUtils;
    285 import com.android.internal.util.ArrayUtils;
    286 import com.android.internal.util.ConcurrentUtils;
    287 import com.android.internal.util.DumpUtils;
    288 import com.android.internal.util.FastXmlSerializer;
    289 import com.android.internal.util.IndentingPrintWriter;
    290 import com.android.internal.util.Preconditions;
    291 import com.android.internal.util.XmlUtils;
    292 import com.android.server.AttributeCache;
    293 import com.android.server.DeviceIdleController;
    294 import com.android.server.EventLogTags;
    295 import com.android.server.FgThread;
    296 import com.android.server.IntentResolver;
    297 import com.android.server.LocalServices;
    298 import com.android.server.LockGuard;
    299 import com.android.server.ServiceThread;
    300 import com.android.server.SystemConfig;
    301 import com.android.server.SystemServerInitThreadPool;
    302 import com.android.server.Watchdog;
    303 import com.android.server.net.NetworkPolicyManagerInternal;
    304 import com.android.server.pm.Installer.InstallerException;
    305 import com.android.server.pm.Settings.DatabaseVersion;
    306 import com.android.server.pm.Settings.VersionInfo;
    307 import com.android.server.pm.dex.ArtManagerService;
    308 import com.android.server.pm.dex.DexLogger;
    309 import com.android.server.pm.dex.DexManager;
    310 import com.android.server.pm.dex.DexoptOptions;
    311 import com.android.server.pm.dex.PackageDexUsage;
    312 import com.android.server.pm.permission.BasePermission;
    313 import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
    314 import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
    315 import com.android.server.pm.permission.PermissionManagerInternal;
    316 import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
    317 import com.android.server.pm.permission.PermissionManagerService;
    318 import com.android.server.pm.permission.PermissionsState;
    319 import com.android.server.pm.permission.PermissionsState.PermissionState;
    320 import com.android.server.security.VerityUtils;
    321 import com.android.server.storage.DeviceStorageMonitorInternal;
    322 
    323 import dalvik.system.CloseGuard;
    324 import dalvik.system.VMRuntime;
    325 
    326 import libcore.io.IoUtils;
    327 
    328 import org.xmlpull.v1.XmlPullParser;
    329 import org.xmlpull.v1.XmlPullParserException;
    330 import org.xmlpull.v1.XmlSerializer;
    331 
    332 import java.io.BufferedOutputStream;
    333 import java.io.ByteArrayInputStream;
    334 import java.io.ByteArrayOutputStream;
    335 import java.io.File;
    336 import java.io.FileDescriptor;
    337 import java.io.FileInputStream;
    338 import java.io.FileOutputStream;
    339 import java.io.FilenameFilter;
    340 import java.io.IOException;
    341 import java.io.PrintWriter;
    342 import java.lang.annotation.Retention;
    343 import java.lang.annotation.RetentionPolicy;
    344 import java.nio.charset.StandardCharsets;
    345 import java.security.DigestException;
    346 import java.security.DigestInputStream;
    347 import java.security.MessageDigest;
    348 import java.security.NoSuchAlgorithmException;
    349 import java.security.PublicKey;
    350 import java.security.SecureRandom;
    351 import java.security.cert.CertificateException;
    352 import java.util.ArrayList;
    353 import java.util.Arrays;
    354 import java.util.Collection;
    355 import java.util.Collections;
    356 import java.util.Comparator;
    357 import java.util.HashMap;
    358 import java.util.HashSet;
    359 import java.util.Iterator;
    360 import java.util.LinkedHashSet;
    361 import java.util.List;
    362 import java.util.Map;
    363 import java.util.Objects;
    364 import java.util.Set;
    365 import java.util.concurrent.CountDownLatch;
    366 import java.util.concurrent.Future;
    367 import java.util.concurrent.TimeUnit;
    368 import java.util.concurrent.atomic.AtomicBoolean;
    369 import java.util.concurrent.atomic.AtomicInteger;
    370 import java.util.function.Predicate;
    371 
    372 /**
    373  * Keep track of all those APKs everywhere.
    374  * <p>
    375  * Internally there are two important locks:
    376  * <ul>
    377  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
    378  * and other related state. It is a fine-grained lock that should only be held
    379  * momentarily, as it's one of the most contended locks in the system.
    380  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
    381  * operations typically involve heavy lifting of application data on disk. Since
    382  * {@code installd} is single-threaded, and it's operations can often be slow,
    383  * this lock should never be acquired while already holding {@link #mPackages}.
    384  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
    385  * holding {@link #mInstallLock}.
    386  * </ul>
    387  * Many internal methods rely on the caller to hold the appropriate locks, and
    388  * this contract is expressed through method name suffixes:
    389  * <ul>
    390  * <li>fooLI(): the caller must hold {@link #mInstallLock}
    391  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
    392  * being modified must be frozen
    393  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
    394  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
    395  * </ul>
    396  * <p>
    397  * Because this class is very central to the platform's security; please run all
    398  * CTS and unit tests whenever making modifications:
    399  *
    400  * <pre>
    401  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
    402  * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
    403  * </pre>
    404  */
    405 public class PackageManagerService extends IPackageManager.Stub
    406         implements PackageSender {
    407     static final String TAG = "PackageManager";
    408     public static final boolean DEBUG_SETTINGS = false;
    409     static final boolean DEBUG_PREFERRED = false;
    410     static final boolean DEBUG_UPGRADE = false;
    411     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
    412     private static final boolean DEBUG_BACKUP = false;
    413     public static final boolean DEBUG_INSTALL = false;
    414     public static final boolean DEBUG_REMOVE = false;
    415     private static final boolean DEBUG_BROADCASTS = false;
    416     private static final boolean DEBUG_SHOW_INFO = false;
    417     private static final boolean DEBUG_PACKAGE_INFO = false;
    418     private static final boolean DEBUG_INTENT_MATCHING = false;
    419     public static final boolean DEBUG_PACKAGE_SCANNING = false;
    420     private static final boolean DEBUG_VERIFY = false;
    421     private static final boolean DEBUG_FILTERS = false;
    422     public static final boolean DEBUG_PERMISSIONS = false;
    423     private static final boolean DEBUG_SHARED_LIBRARIES = false;
    424     public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
    425 
    426     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
    427     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
    428     // user, but by default initialize to this.
    429     public static final boolean DEBUG_DEXOPT = false;
    430 
    431     private static final boolean DEBUG_ABI_SELECTION = false;
    432     private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
    433     private static final boolean DEBUG_TRIAGED_MISSING = false;
    434     private static final boolean DEBUG_APP_DATA = false;
    435 
    436     /** REMOVE. According to Svet, this was only used to reset permissions during development. */
    437     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
    438 
    439     private static final boolean HIDE_EPHEMERAL_APIS = false;
    440 
    441     private static final boolean ENABLE_FREE_CACHE_V2 =
    442             SystemProperties.getBoolean("fw.free_cache_v2", true);
    443 
    444     private static final int RADIO_UID = Process.PHONE_UID;
    445     private static final int LOG_UID = Process.LOG_UID;
    446     private static final int NFC_UID = Process.NFC_UID;
    447     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
    448     private static final int SHELL_UID = Process.SHELL_UID;
    449     private static final int SE_UID = Process.SE_UID;
    450 
    451     // Suffix used during package installation when copying/moving
    452     // package apks to install directory.
    453     private static final String INSTALL_PACKAGE_SUFFIX = "-";
    454 
    455     static final int SCAN_NO_DEX = 1<<0;
    456     static final int SCAN_UPDATE_SIGNATURE = 1<<1;
    457     static final int SCAN_NEW_INSTALL = 1<<2;
    458     static final int SCAN_UPDATE_TIME = 1<<3;
    459     static final int SCAN_BOOTING = 1<<4;
    460     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
    461     static final int SCAN_REQUIRE_KNOWN = 1<<7;
    462     static final int SCAN_MOVE = 1<<8;
    463     static final int SCAN_INITIAL = 1<<9;
    464     static final int SCAN_CHECK_ONLY = 1<<10;
    465     static final int SCAN_DONT_KILL_APP = 1<<11;
    466     static final int SCAN_IGNORE_FROZEN = 1<<12;
    467     static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
    468     static final int SCAN_AS_INSTANT_APP = 1<<14;
    469     static final int SCAN_AS_FULL_APP = 1<<15;
    470     static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
    471     static final int SCAN_AS_SYSTEM = 1<<17;
    472     static final int SCAN_AS_PRIVILEGED = 1<<18;
    473     static final int SCAN_AS_OEM = 1<<19;
    474     static final int SCAN_AS_VENDOR = 1<<20;
    475     static final int SCAN_AS_PRODUCT = 1<<21;
    476 
    477     @IntDef(flag = true, prefix = { "SCAN_" }, value = {
    478             SCAN_NO_DEX,
    479             SCAN_UPDATE_SIGNATURE,
    480             SCAN_NEW_INSTALL,
    481             SCAN_UPDATE_TIME,
    482             SCAN_BOOTING,
    483             SCAN_DELETE_DATA_ON_FAILURES,
    484             SCAN_REQUIRE_KNOWN,
    485             SCAN_MOVE,
    486             SCAN_INITIAL,
    487             SCAN_CHECK_ONLY,
    488             SCAN_DONT_KILL_APP,
    489             SCAN_IGNORE_FROZEN,
    490             SCAN_FIRST_BOOT_OR_UPGRADE,
    491             SCAN_AS_INSTANT_APP,
    492             SCAN_AS_FULL_APP,
    493             SCAN_AS_VIRTUAL_PRELOAD,
    494     })
    495     @Retention(RetentionPolicy.SOURCE)
    496     public @interface ScanFlags {}
    497 
    498     private static final String STATIC_SHARED_LIB_DELIMITER = "_";
    499     /** Extension of the compressed packages */
    500     public final static String COMPRESSED_EXTENSION = ".gz";
    501     /** Suffix of stub packages on the system partition */
    502     public final static String STUB_SUFFIX = "-Stub";
    503 
    504     private static final int[] EMPTY_INT_ARRAY = new int[0];
    505 
    506     private static final int TYPE_UNKNOWN = 0;
    507     private static final int TYPE_ACTIVITY = 1;
    508     private static final int TYPE_RECEIVER = 2;
    509     private static final int TYPE_SERVICE = 3;
    510     private static final int TYPE_PROVIDER = 4;
    511     @IntDef(prefix = { "TYPE_" }, value = {
    512             TYPE_UNKNOWN,
    513             TYPE_ACTIVITY,
    514             TYPE_RECEIVER,
    515             TYPE_SERVICE,
    516             TYPE_PROVIDER,
    517     })
    518     @Retention(RetentionPolicy.SOURCE)
    519     public @interface ComponentType {}
    520 
    521     /**
    522      * Timeout (in milliseconds) after which the watchdog should declare that
    523      * our handler thread is wedged.  The usual default for such things is one
    524      * minute but we sometimes do very lengthy I/O operations on this thread,
    525      * such as installing multi-gigabyte applications, so ours needs to be longer.
    526      */
    527     static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
    528 
    529     /**
    530      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
    531      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
    532      * settings entry if available, otherwise we use the hardcoded default.  If it's been
    533      * more than this long since the last fstrim, we force one during the boot sequence.
    534      *
    535      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
    536      * one gets run at the next available charging+idle time.  This final mandatory
    537      * no-fstrim check kicks in only of the other scheduling criteria is never met.
    538      */
    539     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
    540 
    541     /**
    542      * Whether verification is enabled by default.
    543      */
    544     private static final boolean DEFAULT_VERIFY_ENABLE = true;
    545 
    546     /**
    547      * The default maximum time to wait for the verification agent to return in
    548      * milliseconds.
    549      */
    550     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
    551 
    552     /**
    553      * The default response for package verification timeout.
    554      *
    555      * This can be either PackageManager.VERIFICATION_ALLOW or
    556      * PackageManager.VERIFICATION_REJECT.
    557      */
    558     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
    559 
    560     public static final String PLATFORM_PACKAGE_NAME = "android";
    561 
    562     public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
    563 
    564     public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
    565             DEFAULT_CONTAINER_PACKAGE,
    566             "com.android.defcontainer.DefaultContainerService");
    567 
    568     private static final String KILL_APP_REASON_GIDS_CHANGED =
    569             "permission grant or revoke changed gids";
    570 
    571     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
    572             "permissions revoked";
    573 
    574     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
    575 
    576     private static final String PACKAGE_SCHEME = "package";
    577 
    578     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
    579 
    580     private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
    581 
    582     /** Canonical intent used to identify what counts as a "web browser" app */
    583     private static final Intent sBrowserIntent;
    584     static {
    585         sBrowserIntent = new Intent();
    586         sBrowserIntent.setAction(Intent.ACTION_VIEW);
    587         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
    588         sBrowserIntent.setData(Uri.parse("http:"));
    589         sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
    590     }
    591 
    592     /**
    593      * The set of all protected actions [i.e. those actions for which a high priority
    594      * intent filter is disallowed].
    595      */
    596     private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
    597     static {
    598         PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
    599         PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
    600         PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
    601         PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
    602     }
    603 
    604     // Compilation reasons.
    605     public static final int REASON_UNKNOWN = -1;
    606     public static final int REASON_FIRST_BOOT = 0;
    607     public static final int REASON_BOOT = 1;
    608     public static final int REASON_INSTALL = 2;
    609     public static final int REASON_BACKGROUND_DEXOPT = 3;
    610     public static final int REASON_AB_OTA = 4;
    611     public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
    612     public static final int REASON_SHARED = 6;
    613 
    614     public static final int REASON_LAST = REASON_SHARED;
    615 
    616     /**
    617      * Version number for the package parser cache. Increment this whenever the format or
    618      * extent of cached data changes. See {@code PackageParser#setCacheDir}.
    619      */
    620     private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
    621 
    622     /**
    623      * Whether the package parser cache is enabled.
    624      */
    625     private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
    626 
    627     /**
    628      * Permissions required in order to receive instant application lifecycle broadcasts.
    629      */
    630     private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
    631             new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
    632 
    633     final ServiceThread mHandlerThread;
    634 
    635     final PackageHandler mHandler;
    636 
    637     private final ProcessLoggingHandler mProcessLoggingHandler;
    638 
    639     /**
    640      * Messages for {@link #mHandler} that need to wait for system ready before
    641      * being dispatched.
    642      */
    643     private ArrayList<Message> mPostSystemReadyMessages;
    644 
    645     final int mSdkVersion = Build.VERSION.SDK_INT;
    646 
    647     final Context mContext;
    648     final boolean mFactoryTest;
    649     final boolean mOnlyCore;
    650     final DisplayMetrics mMetrics;
    651     final int mDefParseFlags;
    652     final String[] mSeparateProcesses;
    653     final boolean mIsUpgrade;
    654     final boolean mIsPreNUpgrade;
    655     final boolean mIsPreNMR1Upgrade;
    656 
    657     // Have we told the Activity Manager to whitelist the default container service by uid yet?
    658     @GuardedBy("mPackages")
    659     boolean mDefaultContainerWhitelisted = false;
    660 
    661     @GuardedBy("mPackages")
    662     private boolean mDexOptDialogShown;
    663 
    664     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
    665     // LOCK HELD.  Can be called with mInstallLock held.
    666     @GuardedBy("mInstallLock")
    667     final Installer mInstaller;
    668 
    669     /** Directory where installed applications are stored */
    670     private static final File sAppInstallDir =
    671             new File(Environment.getDataDirectory(), "app");
    672     /** Directory where installed application's 32-bit native libraries are copied. */
    673     private static final File sAppLib32InstallDir =
    674             new File(Environment.getDataDirectory(), "app-lib");
    675     /** Directory where code and non-resource assets of forward-locked applications are stored */
    676     private static final File sDrmAppPrivateInstallDir =
    677             new File(Environment.getDataDirectory(), "app-private");
    678 
    679     // ----------------------------------------------------------------
    680 
    681     // Lock for state used when installing and doing other long running
    682     // operations.  Methods that must be called with this lock held have
    683     // the suffix "LI".
    684     final Object mInstallLock = new Object();
    685 
    686     // ----------------------------------------------------------------
    687 
    688     // Keys are String (package name), values are Package.  This also serves
    689     // as the lock for the global state.  Methods that must be called with
    690     // this lock held have the prefix "LP".
    691     @GuardedBy("mPackages")
    692     final ArrayMap<String, PackageParser.Package> mPackages =
    693             new ArrayMap<String, PackageParser.Package>();
    694 
    695     final ArrayMap<String, Set<String>> mKnownCodebase =
    696             new ArrayMap<String, Set<String>>();
    697 
    698     // Keys are isolated uids and values are the uid of the application
    699     // that created the isolated proccess.
    700     @GuardedBy("mPackages")
    701     final SparseIntArray mIsolatedOwners = new SparseIntArray();
    702 
    703     /**
    704      * Tracks new system packages [received in an OTA] that we expect to
    705      * find updated user-installed versions. Keys are package name, values
    706      * are package location.
    707      */
    708     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
    709     /**
    710      * Tracks high priority intent filters for protected actions. During boot, certain
    711      * filter actions are protected and should never be allowed to have a high priority
    712      * intent filter for them. However, there is one, and only one exception -- the
    713      * setup wizard. It must be able to define a high priority intent filter for these
    714      * actions to ensure there are no escapes from the wizard. We need to delay processing
    715      * of these during boot as we need to look at all of the system packages in order
    716      * to know which component is the setup wizard.
    717      */
    718     private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
    719     /**
    720      * Whether or not processing protected filters should be deferred.
    721      */
    722     private boolean mDeferProtectedFilters = true;
    723 
    724     /**
    725      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
    726      */
    727     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
    728     /**
    729      * Whether or not system app permissions should be promoted from install to runtime.
    730      */
    731     boolean mPromoteSystemApps;
    732 
    733     @GuardedBy("mPackages")
    734     final Settings mSettings;
    735 
    736     /**
    737      * Set of package names that are currently "frozen", which means active
    738      * surgery is being done on the code/data for that package. The platform
    739      * will refuse to launch frozen packages to avoid race conditions.
    740      *
    741      * @see PackageFreezer
    742      */
    743     @GuardedBy("mPackages")
    744     final ArraySet<String> mFrozenPackages = new ArraySet<>();
    745 
    746     final ProtectedPackages mProtectedPackages;
    747 
    748     @GuardedBy("mLoadedVolumes")
    749     final ArraySet<String> mLoadedVolumes = new ArraySet<>();
    750 
    751     boolean mFirstBoot;
    752 
    753     PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
    754 
    755     @GuardedBy("mAvailableFeatures")
    756     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
    757 
    758     private final InstantAppRegistry mInstantAppRegistry;
    759 
    760     @GuardedBy("mPackages")
    761     int mChangedPackagesSequenceNumber;
    762     /**
    763      * List of changed [installed, removed or updated] packages.
    764      * mapping from user id -> sequence number -> package name
    765      */
    766     @GuardedBy("mPackages")
    767     final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
    768     /**
    769      * The sequence number of the last change to a package.
    770      * mapping from user id -> package name -> sequence number
    771      */
    772     @GuardedBy("mPackages")
    773     final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
    774 
    775     @GuardedBy("mPackages")
    776     final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
    777 
    778     class PackageParserCallback implements PackageParser.Callback {
    779         @Override public final boolean hasFeature(String feature) {
    780             return PackageManagerService.this.hasSystemFeature(feature, 0);
    781         }
    782 
    783         final List<PackageParser.Package> getStaticOverlayPackages(
    784                 Collection<PackageParser.Package> allPackages, String targetPackageName) {
    785             if ("android".equals(targetPackageName)) {
    786                 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
    787                 // native AssetManager.
    788                 return null;
    789             }
    790 
    791             List<PackageParser.Package> overlayPackages = null;
    792             for (PackageParser.Package p : allPackages) {
    793                 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
    794                     if (overlayPackages == null) {
    795                         overlayPackages = new ArrayList<PackageParser.Package>();
    796                     }
    797                     overlayPackages.add(p);
    798                 }
    799             }
    800             if (overlayPackages != null) {
    801                 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
    802                     public int compare(PackageParser.Package p1, PackageParser.Package p2) {
    803                         return p1.mOverlayPriority - p2.mOverlayPriority;
    804                     }
    805                 };
    806                 Collections.sort(overlayPackages, cmp);
    807             }
    808             return overlayPackages;
    809         }
    810 
    811         final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
    812                 String targetPath) {
    813             if (overlayPackages == null || overlayPackages.isEmpty()) {
    814                 return null;
    815             }
    816             List<String> overlayPathList = null;
    817             for (PackageParser.Package overlayPackage : overlayPackages) {
    818                 if (targetPath == null) {
    819                     if (overlayPathList == null) {
    820                         overlayPathList = new ArrayList<String>();
    821                     }
    822                     overlayPathList.add(overlayPackage.baseCodePath);
    823                     continue;
    824                 }
    825 
    826                 try {
    827                     // Creates idmaps for system to parse correctly the Android manifest of the
    828                     // target package.
    829                     //
    830                     // OverlayManagerService will update each of them with a correct gid from its
    831                     // target package app id.
    832                     mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
    833                             UserHandle.getSharedAppGid(
    834                                     UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
    835                     if (overlayPathList == null) {
    836                         overlayPathList = new ArrayList<String>();
    837                     }
    838                     overlayPathList.add(overlayPackage.baseCodePath);
    839                 } catch (InstallerException e) {
    840                     Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
    841                             overlayPackage.baseCodePath);
    842                 }
    843             }
    844             return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
    845         }
    846 
    847         String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
    848             List<PackageParser.Package> overlayPackages;
    849             synchronized (mInstallLock) {
    850                 synchronized (mPackages) {
    851                     overlayPackages = getStaticOverlayPackages(
    852                             mPackages.values(), targetPackageName);
    853                 }
    854                 // It is safe to keep overlayPackages without holding mPackages because static overlay
    855                 // packages can't be uninstalled or disabled.
    856                 return getStaticOverlayPaths(overlayPackages, targetPath);
    857             }
    858         }
    859 
    860         @Override public final String[] getOverlayApks(String targetPackageName) {
    861             return getStaticOverlayPaths(targetPackageName, null);
    862         }
    863 
    864         @Override public final String[] getOverlayPaths(String targetPackageName,
    865                 String targetPath) {
    866             return getStaticOverlayPaths(targetPackageName, targetPath);
    867         }
    868     }
    869 
    870     class ParallelPackageParserCallback extends PackageParserCallback {
    871         List<PackageParser.Package> mOverlayPackages = null;
    872 
    873         void findStaticOverlayPackages() {
    874             synchronized (mPackages) {
    875                 for (PackageParser.Package p : mPackages.values()) {
    876                     if (p.mOverlayIsStatic) {
    877                         if (mOverlayPackages == null) {
    878                             mOverlayPackages = new ArrayList<PackageParser.Package>();
    879                         }
    880                         mOverlayPackages.add(p);
    881                     }
    882                 }
    883             }
    884         }
    885 
    886         @Override
    887         synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
    888             // We can trust mOverlayPackages without holding mPackages because package uninstall
    889             // can't happen while running parallel parsing.
    890             // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
    891             // because mInstallLock is held before running parallel parsing.
    892             // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
    893             return mOverlayPackages == null ? null :
    894                     getStaticOverlayPaths(
    895                             getStaticOverlayPackages(mOverlayPackages, targetPackageName),
    896                             targetPath);
    897         }
    898     }
    899 
    900     final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
    901     final ParallelPackageParserCallback mParallelPackageParserCallback =
    902             new ParallelPackageParserCallback();
    903 
    904     public static final class SharedLibraryEntry {
    905         public final @Nullable String path;
    906         public final @Nullable String apk;
    907         public final @NonNull SharedLibraryInfo info;
    908 
    909         SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
    910                 String declaringPackageName, long declaringPackageVersionCode) {
    911             path = _path;
    912             apk = _apk;
    913             info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
    914                     declaringPackageName, declaringPackageVersionCode), null);
    915         }
    916     }
    917 
    918     // Currently known shared libraries.
    919     final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
    920     final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
    921             new ArrayMap<>();
    922 
    923     // All available activities, for your resolving pleasure.
    924     final ActivityIntentResolver mActivities =
    925             new ActivityIntentResolver();
    926 
    927     // All available receivers, for your resolving pleasure.
    928     final ActivityIntentResolver mReceivers =
    929             new ActivityIntentResolver();
    930 
    931     // All available services, for your resolving pleasure.
    932     final ServiceIntentResolver mServices = new ServiceIntentResolver();
    933 
    934     // All available providers, for your resolving pleasure.
    935     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
    936 
    937     // Mapping from provider base names (first directory in content URI codePath)
    938     // to the provider information.
    939     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
    940             new ArrayMap<String, PackageParser.Provider>();
    941 
    942     // Mapping from instrumentation class names to info about them.
    943     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
    944             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
    945 
    946     // Packages whose data we have transfered into another package, thus
    947     // should no longer exist.
    948     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
    949 
    950     // Broadcast actions that are only available to the system.
    951     @GuardedBy("mProtectedBroadcasts")
    952     final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
    953 
    954     /** List of packages waiting for verification. */
    955     final SparseArray<PackageVerificationState> mPendingVerification
    956             = new SparseArray<PackageVerificationState>();
    957 
    958     final PackageInstallerService mInstallerService;
    959 
    960     final ArtManagerService mArtManagerService;
    961 
    962     private final PackageDexOptimizer mPackageDexOptimizer;
    963     // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
    964     // is used by other apps).
    965     private final DexManager mDexManager;
    966 
    967     private AtomicInteger mNextMoveId = new AtomicInteger();
    968     private final MoveCallbacks mMoveCallbacks;
    969 
    970     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
    971 
    972     // Cache of users who need badging.
    973     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
    974 
    975     /** Token for keys in mPendingVerification. */
    976     private int mPendingVerificationToken = 0;
    977 
    978     volatile boolean mSystemReady;
    979     volatile boolean mSafeMode;
    980     volatile boolean mHasSystemUidErrors;
    981     private volatile boolean mWebInstantAppsDisabled;
    982 
    983     ApplicationInfo mAndroidApplication;
    984     final ActivityInfo mResolveActivity = new ActivityInfo();
    985     final ResolveInfo mResolveInfo = new ResolveInfo();
    986     ComponentName mResolveComponentName;
    987     PackageParser.Package mPlatformPackage;
    988     ComponentName mCustomResolverComponentName;
    989 
    990     boolean mResolverReplaced = false;
    991 
    992     private final @Nullable ComponentName mIntentFilterVerifierComponent;
    993     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
    994 
    995     private int mIntentFilterVerificationToken = 0;
    996 
    997     /** The service connection to the ephemeral resolver */
    998     final InstantAppResolverConnection mInstantAppResolverConnection;
    999     /** Component used to show resolver settings for Instant Apps */
   1000     final ComponentName mInstantAppResolverSettingsComponent;
   1001 
   1002     /** Activity used to install instant applications */
   1003     ActivityInfo mInstantAppInstallerActivity;
   1004     final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
   1005 
   1006     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
   1007             = new SparseArray<IntentFilterVerificationState>();
   1008 
   1009     // TODO remove this and go through mPermissonManager directly
   1010     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
   1011     private final PermissionManagerInternal mPermissionManager;
   1012 
   1013     // List of packages names to keep cached, even if they are uninstalled for all users
   1014     private List<String> mKeepUninstalledPackages;
   1015 
   1016     private UserManagerInternal mUserManagerInternal;
   1017     private ActivityManagerInternal mActivityManagerInternal;
   1018 
   1019     private DeviceIdleController.LocalService mDeviceIdleController;
   1020 
   1021     private File mCacheDir;
   1022 
   1023     private Future<?> mPrepareAppDataFuture;
   1024 
   1025     private static class IFVerificationParams {
   1026         PackageParser.Package pkg;
   1027         boolean replacing;
   1028         int userId;
   1029         int verifierUid;
   1030 
   1031         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
   1032                 int _userId, int _verifierUid) {
   1033             pkg = _pkg;
   1034             replacing = _replacing;
   1035             userId = _userId;
   1036             replacing = _replacing;
   1037             verifierUid = _verifierUid;
   1038         }
   1039     }
   1040 
   1041     private interface IntentFilterVerifier<T extends IntentFilter> {
   1042         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
   1043                                                T filter, String packageName);
   1044         void startVerifications(int userId);
   1045         void receiveVerificationResponse(int verificationId);
   1046     }
   1047 
   1048     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
   1049         private Context mContext;
   1050         private ComponentName mIntentFilterVerifierComponent;
   1051         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
   1052 
   1053         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
   1054             mContext = context;
   1055             mIntentFilterVerifierComponent = verifierComponent;
   1056         }
   1057 
   1058         private String getDefaultScheme() {
   1059             return IntentFilter.SCHEME_HTTPS;
   1060         }
   1061 
   1062         @Override
   1063         public void startVerifications(int userId) {
   1064             // Launch verifications requests
   1065             int count = mCurrentIntentFilterVerifications.size();
   1066             for (int n=0; n<count; n++) {
   1067                 int verificationId = mCurrentIntentFilterVerifications.get(n);
   1068                 final IntentFilterVerificationState ivs =
   1069                         mIntentFilterVerificationStates.get(verificationId);
   1070 
   1071                 String packageName = ivs.getPackageName();
   1072 
   1073                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
   1074                 final int filterCount = filters.size();
   1075                 ArraySet<String> domainsSet = new ArraySet<>();
   1076                 for (int m=0; m<filterCount; m++) {
   1077                     PackageParser.ActivityIntentInfo filter = filters.get(m);
   1078                     domainsSet.addAll(filter.getHostsList());
   1079                 }
   1080                 synchronized (mPackages) {
   1081                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
   1082                             packageName, domainsSet) != null) {
   1083                         scheduleWriteSettingsLocked();
   1084                     }
   1085                 }
   1086                 sendVerificationRequest(verificationId, ivs);
   1087             }
   1088             mCurrentIntentFilterVerifications.clear();
   1089         }
   1090 
   1091         private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
   1092             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
   1093             verificationIntent.putExtra(
   1094                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
   1095                     verificationId);
   1096             verificationIntent.putExtra(
   1097                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
   1098                     getDefaultScheme());
   1099             verificationIntent.putExtra(
   1100                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
   1101                     ivs.getHostsString());
   1102             verificationIntent.putExtra(
   1103                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
   1104                     ivs.getPackageName());
   1105             verificationIntent.setComponent(mIntentFilterVerifierComponent);
   1106             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
   1107 
   1108             DeviceIdleController.LocalService idleController = getDeviceIdleController();
   1109             idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
   1110                     mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
   1111                     UserHandle.USER_SYSTEM, true, "intent filter verifier");
   1112 
   1113             mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
   1114             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1115                     "Sending IntentFilter verification broadcast");
   1116         }
   1117 
   1118         public void receiveVerificationResponse(int verificationId) {
   1119             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
   1120 
   1121             final boolean verified = ivs.isVerified();
   1122 
   1123             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
   1124             final int count = filters.size();
   1125             if (DEBUG_DOMAIN_VERIFICATION) {
   1126                 Slog.i(TAG, "Received verification response " + verificationId
   1127                         + " for " + count + " filters, verified=" + verified);
   1128             }
   1129             for (int n=0; n<count; n++) {
   1130                 PackageParser.ActivityIntentInfo filter = filters.get(n);
   1131                 filter.setVerified(verified);
   1132 
   1133                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
   1134                         + " verified with result:" + verified + " and hosts:"
   1135                         + ivs.getHostsString());
   1136             }
   1137 
   1138             mIntentFilterVerificationStates.remove(verificationId);
   1139 
   1140             final String packageName = ivs.getPackageName();
   1141             IntentFilterVerificationInfo ivi = null;
   1142 
   1143             synchronized (mPackages) {
   1144                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
   1145             }
   1146             if (ivi == null) {
   1147                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
   1148                         + verificationId + " packageName:" + packageName);
   1149                 return;
   1150             }
   1151             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1152                     "Updating IntentFilterVerificationInfo for package " + packageName
   1153                             +" verificationId:" + verificationId);
   1154 
   1155             synchronized (mPackages) {
   1156                 if (verified) {
   1157                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
   1158                 } else {
   1159                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
   1160                 }
   1161                 scheduleWriteSettingsLocked();
   1162 
   1163                 final int userId = ivs.getUserId();
   1164                 if (userId != UserHandle.USER_ALL) {
   1165                     final int userStatus =
   1166                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
   1167 
   1168                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
   1169                     boolean needUpdate = false;
   1170 
   1171                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
   1172                     // already been set by the User thru the Disambiguation dialog
   1173                     switch (userStatus) {
   1174                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
   1175                             if (verified) {
   1176                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
   1177                             } else {
   1178                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
   1179                             }
   1180                             needUpdate = true;
   1181                             break;
   1182 
   1183                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
   1184                             if (verified) {
   1185                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
   1186                                 needUpdate = true;
   1187                             }
   1188                             break;
   1189 
   1190                         default:
   1191                             // Nothing to do
   1192                     }
   1193 
   1194                     if (needUpdate) {
   1195                         mSettings.updateIntentFilterVerificationStatusLPw(
   1196                                 packageName, updatedStatus, userId);
   1197                         scheduleWritePackageRestrictionsLocked(userId);
   1198                     }
   1199                 }
   1200             }
   1201         }
   1202 
   1203         @Override
   1204         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
   1205                     ActivityIntentInfo filter, String packageName) {
   1206             if (!hasValidDomains(filter)) {
   1207                 return false;
   1208             }
   1209             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
   1210             if (ivs == null) {
   1211                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
   1212                         packageName);
   1213             }
   1214             if (DEBUG_DOMAIN_VERIFICATION) {
   1215                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
   1216             }
   1217             ivs.addFilter(filter);
   1218             return true;
   1219         }
   1220 
   1221         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
   1222                 int userId, int verificationId, String packageName) {
   1223             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
   1224                     verifierUid, userId, packageName);
   1225             ivs.setPendingState();
   1226             synchronized (mPackages) {
   1227                 mIntentFilterVerificationStates.append(verificationId, ivs);
   1228                 mCurrentIntentFilterVerifications.add(verificationId);
   1229             }
   1230             return ivs;
   1231         }
   1232     }
   1233 
   1234     private static boolean hasValidDomains(ActivityIntentInfo filter) {
   1235         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
   1236                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
   1237                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
   1238     }
   1239 
   1240     // Set of pending broadcasts for aggregating enable/disable of components.
   1241     static class PendingPackageBroadcasts {
   1242         // for each user id, a map of <package name -> components within that package>
   1243         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
   1244 
   1245         public PendingPackageBroadcasts() {
   1246             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
   1247         }
   1248 
   1249         public ArrayList<String> get(int userId, String packageName) {
   1250             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
   1251             return packages.get(packageName);
   1252         }
   1253 
   1254         public void put(int userId, String packageName, ArrayList<String> components) {
   1255             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
   1256             packages.put(packageName, components);
   1257         }
   1258 
   1259         public void remove(int userId, String packageName) {
   1260             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
   1261             if (packages != null) {
   1262                 packages.remove(packageName);
   1263             }
   1264         }
   1265 
   1266         public void remove(int userId) {
   1267             mUidMap.remove(userId);
   1268         }
   1269 
   1270         public int userIdCount() {
   1271             return mUidMap.size();
   1272         }
   1273 
   1274         public int userIdAt(int n) {
   1275             return mUidMap.keyAt(n);
   1276         }
   1277 
   1278         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
   1279             return mUidMap.get(userId);
   1280         }
   1281 
   1282         public int size() {
   1283             // total number of pending broadcast entries across all userIds
   1284             int num = 0;
   1285             for (int i = 0; i< mUidMap.size(); i++) {
   1286                 num += mUidMap.valueAt(i).size();
   1287             }
   1288             return num;
   1289         }
   1290 
   1291         public void clear() {
   1292             mUidMap.clear();
   1293         }
   1294 
   1295         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
   1296             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
   1297             if (map == null) {
   1298                 map = new ArrayMap<String, ArrayList<String>>();
   1299                 mUidMap.put(userId, map);
   1300             }
   1301             return map;
   1302         }
   1303     }
   1304     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
   1305 
   1306     // Service Connection to remote media container service to copy
   1307     // package uri's from external media onto secure containers
   1308     // or internal storage.
   1309     private IMediaContainerService mContainerService = null;
   1310 
   1311     static final int SEND_PENDING_BROADCAST = 1;
   1312     static final int MCS_BOUND = 3;
   1313     static final int END_COPY = 4;
   1314     static final int INIT_COPY = 5;
   1315     static final int MCS_UNBIND = 6;
   1316     static final int START_CLEANING_PACKAGE = 7;
   1317     static final int FIND_INSTALL_LOC = 8;
   1318     static final int POST_INSTALL = 9;
   1319     static final int MCS_RECONNECT = 10;
   1320     static final int MCS_GIVE_UP = 11;
   1321     static final int WRITE_SETTINGS = 13;
   1322     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
   1323     static final int PACKAGE_VERIFIED = 15;
   1324     static final int CHECK_PENDING_VERIFICATION = 16;
   1325     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
   1326     static final int INTENT_FILTER_VERIFIED = 18;
   1327     static final int WRITE_PACKAGE_LIST = 19;
   1328     static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
   1329     static final int DEF_CONTAINER_BIND = 21;
   1330 
   1331     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
   1332 
   1333     // Delay time in millisecs
   1334     static final int BROADCAST_DELAY = 10 * 1000;
   1335 
   1336     private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
   1337             2 * 60 * 60 * 1000L; /* two hours */
   1338 
   1339     static UserManagerService sUserManager;
   1340 
   1341     // Stores a list of users whose package restrictions file needs to be updated
   1342     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
   1343 
   1344     final private DefaultContainerConnection mDefContainerConn =
   1345             new DefaultContainerConnection();
   1346     class DefaultContainerConnection implements ServiceConnection {
   1347         public void onServiceConnected(ComponentName name, IBinder service) {
   1348             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
   1349             final IMediaContainerService imcs = IMediaContainerService.Stub
   1350                     .asInterface(Binder.allowBlocking(service));
   1351             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
   1352         }
   1353 
   1354         public void onServiceDisconnected(ComponentName name) {
   1355             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
   1356         }
   1357     }
   1358 
   1359     // Recordkeeping of restore-after-install operations that are currently in flight
   1360     // between the Package Manager and the Backup Manager
   1361     static class PostInstallData {
   1362         public InstallArgs args;
   1363         public PackageInstalledInfo res;
   1364 
   1365         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
   1366             args = _a;
   1367             res = _r;
   1368         }
   1369     }
   1370 
   1371     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
   1372     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
   1373 
   1374     // XML tags for backup/restore of various bits of state
   1375     private static final String TAG_PREFERRED_BACKUP = "pa";
   1376     private static final String TAG_DEFAULT_APPS = "da";
   1377     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
   1378 
   1379     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
   1380     private static final String TAG_ALL_GRANTS = "rt-grants";
   1381     private static final String TAG_GRANT = "grant";
   1382     private static final String ATTR_PACKAGE_NAME = "pkg";
   1383 
   1384     private static final String TAG_PERMISSION = "perm";
   1385     private static final String ATTR_PERMISSION_NAME = "name";
   1386     private static final String ATTR_IS_GRANTED = "g";
   1387     private static final String ATTR_USER_SET = "set";
   1388     private static final String ATTR_USER_FIXED = "fixed";
   1389     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
   1390 
   1391     // System/policy permission grants are not backed up
   1392     private static final int SYSTEM_RUNTIME_GRANT_MASK =
   1393             FLAG_PERMISSION_POLICY_FIXED
   1394             | FLAG_PERMISSION_SYSTEM_FIXED
   1395             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
   1396 
   1397     // And we back up these user-adjusted states
   1398     private static final int USER_RUNTIME_GRANT_MASK =
   1399             FLAG_PERMISSION_USER_SET
   1400             | FLAG_PERMISSION_USER_FIXED
   1401             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
   1402 
   1403     final @Nullable String mRequiredVerifierPackage;
   1404     final @NonNull String mRequiredInstallerPackage;
   1405     final @NonNull String mRequiredUninstallerPackage;
   1406     final @Nullable String mSetupWizardPackage;
   1407     final @Nullable String mStorageManagerPackage;
   1408     final @Nullable String mSystemTextClassifierPackage;
   1409     final @NonNull String mServicesSystemSharedLibraryPackageName;
   1410     final @NonNull String mSharedSystemSharedLibraryPackageName;
   1411 
   1412     private final PackageUsage mPackageUsage = new PackageUsage();
   1413     private final CompilerStats mCompilerStats = new CompilerStats();
   1414 
   1415     class PackageHandler extends Handler {
   1416         private boolean mBound = false;
   1417         final ArrayList<HandlerParams> mPendingInstalls =
   1418             new ArrayList<HandlerParams>();
   1419 
   1420         private boolean connectToService() {
   1421             if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
   1422             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
   1423             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1424             if (mContext.bindServiceAsUser(service, mDefContainerConn,
   1425                     Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
   1426                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1427                 mBound = true;
   1428                 return true;
   1429             }
   1430             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1431             return false;
   1432         }
   1433 
   1434         private void disconnectService() {
   1435             mContainerService = null;
   1436             mBound = false;
   1437             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1438             mContext.unbindService(mDefContainerConn);
   1439             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1440         }
   1441 
   1442         PackageHandler(Looper looper) {
   1443             super(looper);
   1444         }
   1445 
   1446         public void handleMessage(Message msg) {
   1447             try {
   1448                 doHandleMessage(msg);
   1449             } finally {
   1450                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1451             }
   1452         }
   1453 
   1454         void doHandleMessage(Message msg) {
   1455             switch (msg.what) {
   1456                 case DEF_CONTAINER_BIND:
   1457                     if (!mBound) {
   1458                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
   1459                                 System.identityHashCode(mHandler));
   1460                         if (!connectToService()) {
   1461                             Slog.e(TAG, "Failed to bind to media container service");
   1462                         }
   1463                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
   1464                                 System.identityHashCode(mHandler));
   1465                     }
   1466                     break;
   1467                 case INIT_COPY: {
   1468                     HandlerParams params = (HandlerParams) msg.obj;
   1469                     int idx = mPendingInstalls.size();
   1470                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
   1471                     // If a bind was already initiated we dont really
   1472                     // need to do anything. The pending install
   1473                     // will be processed later on.
   1474                     if (!mBound) {
   1475                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
   1476                                 System.identityHashCode(mHandler));
   1477                         // If this is the only one pending we might
   1478                         // have to bind to the service again.
   1479                         if (!connectToService()) {
   1480                             Slog.e(TAG, "Failed to bind to media container service");
   1481                             params.serviceError();
   1482                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
   1483                                     System.identityHashCode(mHandler));
   1484                             if (params.traceMethod != null) {
   1485                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
   1486                                         params.traceCookie);
   1487                             }
   1488                             return;
   1489                         } else {
   1490                             // Once we bind to the service, the first
   1491                             // pending request will be processed.
   1492                             mPendingInstalls.add(idx, params);
   1493                         }
   1494                     } else {
   1495                         mPendingInstalls.add(idx, params);
   1496                         // Already bound to the service. Just make
   1497                         // sure we trigger off processing the first request.
   1498                         if (idx == 0) {
   1499                             mHandler.sendEmptyMessage(MCS_BOUND);
   1500                         }
   1501                     }
   1502                     break;
   1503                 }
   1504                 case MCS_BOUND: {
   1505                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
   1506                     if (msg.obj != null) {
   1507                         mContainerService = (IMediaContainerService) msg.obj;
   1508                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
   1509                                 System.identityHashCode(mHandler));
   1510                     }
   1511                     if (mContainerService == null) {
   1512                         if (!mBound) {
   1513                             // Something seriously wrong since we are not bound and we are not
   1514                             // waiting for connection. Bail out.
   1515                             Slog.e(TAG, "Cannot bind to media container service");
   1516                             for (HandlerParams params : mPendingInstalls) {
   1517                                 // Indicate service bind error
   1518                                 params.serviceError();
   1519                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1520                                         System.identityHashCode(params));
   1521                                 if (params.traceMethod != null) {
   1522                                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
   1523                                             params.traceMethod, params.traceCookie);
   1524                                 }
   1525                             }
   1526                             mPendingInstalls.clear();
   1527                         } else {
   1528                             Slog.w(TAG, "Waiting to connect to media container service");
   1529                         }
   1530                     } else if (mPendingInstalls.size() > 0) {
   1531                         HandlerParams params = mPendingInstalls.get(0);
   1532                         if (params != null) {
   1533                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1534                                     System.identityHashCode(params));
   1535                             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
   1536                             if (params.startCopy()) {
   1537                                 // We are done...  look for more work or to
   1538                                 // go idle.
   1539                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
   1540                                         "Checking for more work or unbind...");
   1541                                 // Delete pending install
   1542                                 if (mPendingInstalls.size() > 0) {
   1543                                     mPendingInstalls.remove(0);
   1544                                 }
   1545                                 if (mPendingInstalls.size() == 0) {
   1546                                     if (mBound) {
   1547                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
   1548                                                 "Posting delayed MCS_UNBIND");
   1549                                         removeMessages(MCS_UNBIND);
   1550                                         Message ubmsg = obtainMessage(MCS_UNBIND);
   1551                                         // Unbind after a little delay, to avoid
   1552                                         // continual thrashing.
   1553                                         sendMessageDelayed(ubmsg, 10000);
   1554                                     }
   1555                                 } else {
   1556                                     // There are more pending requests in queue.
   1557                                     // Just post MCS_BOUND message to trigger processing
   1558                                     // of next pending install.
   1559                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
   1560                                             "Posting MCS_BOUND for next work");
   1561                                     mHandler.sendEmptyMessage(MCS_BOUND);
   1562                                 }
   1563                             }
   1564                             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   1565                         }
   1566                     } else {
   1567                         // Should never happen ideally.
   1568                         Slog.w(TAG, "Empty queue");
   1569                     }
   1570                     break;
   1571                 }
   1572                 case MCS_RECONNECT: {
   1573                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
   1574                     if (mPendingInstalls.size() > 0) {
   1575                         if (mBound) {
   1576                             disconnectService();
   1577                         }
   1578                         if (!connectToService()) {
   1579                             Slog.e(TAG, "Failed to bind to media container service");
   1580                             for (HandlerParams params : mPendingInstalls) {
   1581                                 // Indicate service bind error
   1582                                 params.serviceError();
   1583                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1584                                         System.identityHashCode(params));
   1585                             }
   1586                             mPendingInstalls.clear();
   1587                         }
   1588                     }
   1589                     break;
   1590                 }
   1591                 case MCS_UNBIND: {
   1592                     // If there is no actual work left, then time to unbind.
   1593                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
   1594 
   1595                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
   1596                         if (mBound) {
   1597                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
   1598 
   1599                             disconnectService();
   1600                         }
   1601                     } else if (mPendingInstalls.size() > 0) {
   1602                         // There are more pending requests in queue.
   1603                         // Just post MCS_BOUND message to trigger processing
   1604                         // of next pending install.
   1605                         mHandler.sendEmptyMessage(MCS_BOUND);
   1606                     }
   1607 
   1608                     break;
   1609                 }
   1610                 case MCS_GIVE_UP: {
   1611                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
   1612                     HandlerParams params = mPendingInstalls.remove(0);
   1613                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   1614                             System.identityHashCode(params));
   1615                     break;
   1616                 }
   1617                 case SEND_PENDING_BROADCAST: {
   1618                     String packages[];
   1619                     ArrayList<String> components[];
   1620                     int size = 0;
   1621                     int uids[];
   1622                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1623                     synchronized (mPackages) {
   1624                         if (mPendingBroadcasts == null) {
   1625                             return;
   1626                         }
   1627                         size = mPendingBroadcasts.size();
   1628                         if (size <= 0) {
   1629                             // Nothing to be done. Just return
   1630                             return;
   1631                         }
   1632                         packages = new String[size];
   1633                         components = new ArrayList[size];
   1634                         uids = new int[size];
   1635                         int i = 0;  // filling out the above arrays
   1636 
   1637                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
   1638                             int packageUserId = mPendingBroadcasts.userIdAt(n);
   1639                             Iterator<Map.Entry<String, ArrayList<String>>> it
   1640                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
   1641                                             .entrySet().iterator();
   1642                             while (it.hasNext() && i < size) {
   1643                                 Map.Entry<String, ArrayList<String>> ent = it.next();
   1644                                 packages[i] = ent.getKey();
   1645                                 components[i] = ent.getValue();
   1646                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
   1647                                 uids[i] = (ps != null)
   1648                                         ? UserHandle.getUid(packageUserId, ps.appId)
   1649                                         : -1;
   1650                                 i++;
   1651                             }
   1652                         }
   1653                         size = i;
   1654                         mPendingBroadcasts.clear();
   1655                     }
   1656                     // Send broadcasts
   1657                     for (int i = 0; i < size; i++) {
   1658                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
   1659                     }
   1660                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1661                     break;
   1662                 }
   1663                 case START_CLEANING_PACKAGE: {
   1664                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1665                     final String packageName = (String)msg.obj;
   1666                     final int userId = msg.arg1;
   1667                     final boolean andCode = msg.arg2 != 0;
   1668                     synchronized (mPackages) {
   1669                         if (userId == UserHandle.USER_ALL) {
   1670                             int[] users = sUserManager.getUserIds();
   1671                             for (int user : users) {
   1672                                 mSettings.addPackageToCleanLPw(
   1673                                         new PackageCleanItem(user, packageName, andCode));
   1674                             }
   1675                         } else {
   1676                             mSettings.addPackageToCleanLPw(
   1677                                     new PackageCleanItem(userId, packageName, andCode));
   1678                         }
   1679                     }
   1680                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1681                     startCleaningPackages();
   1682                 } break;
   1683                 case POST_INSTALL: {
   1684                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
   1685 
   1686                     PostInstallData data = mRunningInstalls.get(msg.arg1);
   1687                     final boolean didRestore = (msg.arg2 != 0);
   1688                     mRunningInstalls.delete(msg.arg1);
   1689 
   1690                     if (data != null) {
   1691                         InstallArgs args = data.args;
   1692                         PackageInstalledInfo parentRes = data.res;
   1693 
   1694                         final boolean grantPermissions = (args.installFlags
   1695                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
   1696                         final boolean killApp = (args.installFlags
   1697                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
   1698                         final boolean virtualPreload = ((args.installFlags
   1699                                 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
   1700                         final String[] grantedPermissions = args.installGrantPermissions;
   1701 
   1702                         // Handle the parent package
   1703                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
   1704                                 virtualPreload, grantedPermissions, didRestore,
   1705                                 args.installerPackageName, args.observer);
   1706 
   1707                         // Handle the child packages
   1708                         final int childCount = (parentRes.addedChildPackages != null)
   1709                                 ? parentRes.addedChildPackages.size() : 0;
   1710                         for (int i = 0; i < childCount; i++) {
   1711                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
   1712                             handlePackagePostInstall(childRes, grantPermissions, killApp,
   1713                                     virtualPreload, grantedPermissions, false /*didRestore*/,
   1714                                     args.installerPackageName, args.observer);
   1715                         }
   1716 
   1717                         // Log tracing if needed
   1718                         if (args.traceMethod != null) {
   1719                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
   1720                                     args.traceCookie);
   1721                         }
   1722                     } else {
   1723                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
   1724                     }
   1725 
   1726                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
   1727                 } break;
   1728                 case WRITE_SETTINGS: {
   1729                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1730                     synchronized (mPackages) {
   1731                         removeMessages(WRITE_SETTINGS);
   1732                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   1733                         mSettings.writeLPr();
   1734                         mDirtyUsers.clear();
   1735                     }
   1736                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1737                 } break;
   1738                 case WRITE_PACKAGE_RESTRICTIONS: {
   1739                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1740                     synchronized (mPackages) {
   1741                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   1742                         for (int userId : mDirtyUsers) {
   1743                             mSettings.writePackageRestrictionsLPr(userId);
   1744                         }
   1745                         mDirtyUsers.clear();
   1746                     }
   1747                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1748                 } break;
   1749                 case WRITE_PACKAGE_LIST: {
   1750                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1751                     synchronized (mPackages) {
   1752                         removeMessages(WRITE_PACKAGE_LIST);
   1753                         mSettings.writePackageListLPr(msg.arg1);
   1754                     }
   1755                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1756                 } break;
   1757                 case CHECK_PENDING_VERIFICATION: {
   1758                     final int verificationId = msg.arg1;
   1759                     final PackageVerificationState state = mPendingVerification.get(verificationId);
   1760 
   1761                     if ((state != null) && !state.timeoutExtended()) {
   1762                         final InstallArgs args = state.getInstallArgs();
   1763                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
   1764 
   1765                         Slog.i(TAG, "Verification timed out for " + originUri);
   1766                         mPendingVerification.remove(verificationId);
   1767 
   1768                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   1769 
   1770                         final UserHandle user = args.getUser();
   1771                         if (getDefaultVerificationResponse(user)
   1772                                 == PackageManager.VERIFICATION_ALLOW) {
   1773                             Slog.i(TAG, "Continuing with installation of " + originUri);
   1774                             state.setVerifierResponse(Binder.getCallingUid(),
   1775                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
   1776                             broadcastPackageVerified(verificationId, originUri,
   1777                                     PackageManager.VERIFICATION_ALLOW, user);
   1778                             try {
   1779                                 ret = args.copyApk(mContainerService, true);
   1780                             } catch (RemoteException e) {
   1781                                 Slog.e(TAG, "Could not contact the ContainerService");
   1782                             }
   1783                         } else {
   1784                             broadcastPackageVerified(verificationId, originUri,
   1785                                     PackageManager.VERIFICATION_REJECT, user);
   1786                         }
   1787 
   1788                         Trace.asyncTraceEnd(
   1789                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
   1790 
   1791                         processPendingInstall(args, ret);
   1792                         mHandler.sendEmptyMessage(MCS_UNBIND);
   1793                     }
   1794                     break;
   1795                 }
   1796                 case PACKAGE_VERIFIED: {
   1797                     final int verificationId = msg.arg1;
   1798 
   1799                     final PackageVerificationState state = mPendingVerification.get(verificationId);
   1800                     if (state == null) {
   1801                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
   1802                         break;
   1803                     }
   1804 
   1805                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
   1806 
   1807                     state.setVerifierResponse(response.callerUid, response.code);
   1808 
   1809                     if (state.isVerificationComplete()) {
   1810                         mPendingVerification.remove(verificationId);
   1811 
   1812                         final InstallArgs args = state.getInstallArgs();
   1813                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
   1814 
   1815                         int ret;
   1816                         if (state.isInstallAllowed()) {
   1817                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   1818                             broadcastPackageVerified(verificationId, originUri,
   1819                                     response.code, state.getInstallArgs().getUser());
   1820                             try {
   1821                                 ret = args.copyApk(mContainerService, true);
   1822                             } catch (RemoteException e) {
   1823                                 Slog.e(TAG, "Could not contact the ContainerService");
   1824                             }
   1825                         } else {
   1826                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   1827                         }
   1828 
   1829                         Trace.asyncTraceEnd(
   1830                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
   1831 
   1832                         processPendingInstall(args, ret);
   1833                         mHandler.sendEmptyMessage(MCS_UNBIND);
   1834                     }
   1835 
   1836                     break;
   1837                 }
   1838                 case START_INTENT_FILTER_VERIFICATIONS: {
   1839                     IFVerificationParams params = (IFVerificationParams) msg.obj;
   1840                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
   1841                             params.replacing, params.pkg);
   1842                     break;
   1843                 }
   1844                 case INTENT_FILTER_VERIFIED: {
   1845                     final int verificationId = msg.arg1;
   1846 
   1847                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
   1848                             verificationId);
   1849                     if (state == null) {
   1850                         Slog.w(TAG, "Invalid IntentFilter verification token "
   1851                                 + verificationId + " received");
   1852                         break;
   1853                     }
   1854 
   1855                     final int userId = state.getUserId();
   1856 
   1857                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1858                             "Processing IntentFilter verification with token:"
   1859                             + verificationId + " and userId:" + userId);
   1860 
   1861                     final IntentFilterVerificationResponse response =
   1862                             (IntentFilterVerificationResponse) msg.obj;
   1863 
   1864                     state.setVerifierResponse(response.callerUid, response.code);
   1865 
   1866                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1867                             "IntentFilter verification with token:" + verificationId
   1868                             + " and userId:" + userId
   1869                             + " is settings verifier response with response code:"
   1870                             + response.code);
   1871 
   1872                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
   1873                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
   1874                                 + response.getFailedDomainsString());
   1875                     }
   1876 
   1877                     if (state.isVerificationComplete()) {
   1878                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
   1879                     } else {
   1880                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   1881                                 "IntentFilter verification with token:" + verificationId
   1882                                 + " was not said to be complete");
   1883                     }
   1884 
   1885                     break;
   1886                 }
   1887                 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
   1888                     InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
   1889                             mInstantAppResolverConnection,
   1890                             (InstantAppRequest) msg.obj,
   1891                             mInstantAppInstallerActivity,
   1892                             mHandler);
   1893                 }
   1894             }
   1895         }
   1896     }
   1897 
   1898     private PermissionCallback mPermissionCallback = new PermissionCallback() {
   1899         @Override
   1900         public void onGidsChanged(int appId, int userId) {
   1901             mHandler.post(new Runnable() {
   1902                 @Override
   1903                 public void run() {
   1904                     killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
   1905                 }
   1906             });
   1907         }
   1908         @Override
   1909         public void onPermissionGranted(int uid, int userId) {
   1910             mOnPermissionChangeListeners.onPermissionsChanged(uid);
   1911 
   1912             // Not critical; if this is lost, the application has to request again.
   1913             synchronized (mPackages) {
   1914                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   1915             }
   1916         }
   1917         @Override
   1918         public void onInstallPermissionGranted() {
   1919             synchronized (mPackages) {
   1920                 scheduleWriteSettingsLocked();
   1921             }
   1922         }
   1923         @Override
   1924         public void onPermissionRevoked(int uid, int userId) {
   1925             mOnPermissionChangeListeners.onPermissionsChanged(uid);
   1926 
   1927             synchronized (mPackages) {
   1928                 // Critical; after this call the application should never have the permission
   1929                 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
   1930             }
   1931 
   1932             final int appId = UserHandle.getAppId(uid);
   1933             killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
   1934         }
   1935         @Override
   1936         public void onInstallPermissionRevoked() {
   1937             synchronized (mPackages) {
   1938                 scheduleWriteSettingsLocked();
   1939             }
   1940         }
   1941         @Override
   1942         public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
   1943             synchronized (mPackages) {
   1944                 for (int userId : updatedUserIds) {
   1945                     mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
   1946                 }
   1947             }
   1948         }
   1949         @Override
   1950         public void onInstallPermissionUpdated() {
   1951             synchronized (mPackages) {
   1952                 scheduleWriteSettingsLocked();
   1953             }
   1954         }
   1955         @Override
   1956         public void onPermissionRemoved() {
   1957             synchronized (mPackages) {
   1958                 mSettings.writeLPr();
   1959             }
   1960         }
   1961     };
   1962 
   1963     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
   1964             boolean killApp, boolean virtualPreload, String[] grantedPermissions,
   1965             boolean launchedForRestore, String installerPackage,
   1966             IPackageInstallObserver2 installObserver) {
   1967         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   1968             // Send the removed broadcasts
   1969             if (res.removedInfo != null) {
   1970                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
   1971             }
   1972 
   1973             // Now that we successfully installed the package, grant runtime
   1974             // permissions if requested before broadcasting the install. Also
   1975             // for legacy apps in permission review mode we clear the permission
   1976             // review flag which is used to emulate runtime permissions for
   1977             // legacy apps.
   1978             if (grantPermissions) {
   1979                 final int callingUid = Binder.getCallingUid();
   1980                 mPermissionManager.grantRequestedRuntimePermissions(
   1981                         res.pkg, res.newUsers, grantedPermissions, callingUid,
   1982                         mPermissionCallback);
   1983             }
   1984 
   1985             final boolean update = res.removedInfo != null
   1986                     && res.removedInfo.removedPackage != null;
   1987             final String installerPackageName =
   1988                     res.installerPackageName != null
   1989                             ? res.installerPackageName
   1990                             : res.removedInfo != null
   1991                                     ? res.removedInfo.installerPackageName
   1992                                     : null;
   1993 
   1994             // If this is the first time we have child packages for a disabled privileged
   1995             // app that had no children, we grant requested runtime permissions to the new
   1996             // children if the parent on the system image had them already granted.
   1997             if (res.pkg.parentPackage != null) {
   1998                 final int callingUid = Binder.getCallingUid();
   1999                 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
   2000                         res.pkg, callingUid, mPermissionCallback);
   2001             }
   2002 
   2003             synchronized (mPackages) {
   2004                 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
   2005             }
   2006 
   2007             final String packageName = res.pkg.applicationInfo.packageName;
   2008 
   2009             // Determine the set of users who are adding this package for
   2010             // the first time vs. those who are seeing an update.
   2011             int[] firstUserIds = EMPTY_INT_ARRAY;
   2012             int[] firstInstantUserIds = EMPTY_INT_ARRAY;
   2013             int[] updateUserIds = EMPTY_INT_ARRAY;
   2014             int[] instantUserIds = EMPTY_INT_ARRAY;
   2015             final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
   2016             final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
   2017             for (int newUser : res.newUsers) {
   2018                 final boolean isInstantApp = ps.getInstantApp(newUser);
   2019                 if (allNewUsers) {
   2020                     if (isInstantApp) {
   2021                         firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
   2022                     } else {
   2023                         firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
   2024                     }
   2025                     continue;
   2026                 }
   2027                 boolean isNew = true;
   2028                 for (int origUser : res.origUsers) {
   2029                     if (origUser == newUser) {
   2030                         isNew = false;
   2031                         break;
   2032                     }
   2033                 }
   2034                 if (isNew) {
   2035                     if (isInstantApp) {
   2036                         firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
   2037                     } else {
   2038                         firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
   2039                     }
   2040                 } else {
   2041                     if (isInstantApp) {
   2042                         instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
   2043                     } else {
   2044                         updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
   2045                     }
   2046                 }
   2047             }
   2048 
   2049             // Send installed broadcasts if the package is not a static shared lib.
   2050             if (res.pkg.staticSharedLibName == null) {
   2051                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
   2052 
   2053                 // Send added for users that see the package for the first time
   2054                 // sendPackageAddedForNewUsers also deals with system apps
   2055                 int appId = UserHandle.getAppId(res.uid);
   2056                 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
   2057                 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
   2058                         virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
   2059 
   2060                 // Send added for users that don't see the package for the first time
   2061                 Bundle extras = new Bundle(1);
   2062                 extras.putInt(Intent.EXTRA_UID, res.uid);
   2063                 if (update) {
   2064                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
   2065                 }
   2066                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
   2067                         extras, 0 /*flags*/,
   2068                         null /*targetPackage*/, null /*finishedReceiver*/,
   2069                         updateUserIds, instantUserIds);
   2070                 if (installerPackageName != null) {
   2071                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
   2072                             extras, 0 /*flags*/,
   2073                             installerPackageName, null /*finishedReceiver*/,
   2074                             updateUserIds, instantUserIds);
   2075                 }
   2076                 // if the required verifier is defined, but, is not the installer of record
   2077                 // for the package, it gets notified
   2078                 final boolean notifyVerifier = mRequiredVerifierPackage != null
   2079                         && !mRequiredVerifierPackage.equals(installerPackageName);
   2080                 if (notifyVerifier) {
   2081                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
   2082                             extras, 0 /*flags*/,
   2083                             mRequiredVerifierPackage, null /*finishedReceiver*/,
   2084                             updateUserIds, instantUserIds);
   2085                 }
   2086 
   2087                 // Send replaced for users that don't see the package for the first time
   2088                 if (update) {
   2089                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
   2090                             packageName, extras, 0 /*flags*/,
   2091                             null /*targetPackage*/, null /*finishedReceiver*/,
   2092                             updateUserIds, instantUserIds);
   2093                     if (installerPackageName != null) {
   2094                         sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
   2095                                 extras, 0 /*flags*/,
   2096                                 installerPackageName, null /*finishedReceiver*/,
   2097                                 updateUserIds, instantUserIds);
   2098                     }
   2099                     if (notifyVerifier) {
   2100                         sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
   2101                                 extras, 0 /*flags*/,
   2102                                 mRequiredVerifierPackage, null /*finishedReceiver*/,
   2103                                 updateUserIds, instantUserIds);
   2104                     }
   2105                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
   2106                             null /*package*/, null /*extras*/, 0 /*flags*/,
   2107                             packageName /*targetPackage*/,
   2108                             null /*finishedReceiver*/, updateUserIds, instantUserIds);
   2109                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
   2110                     // First-install and we did a restore, so we're responsible for the
   2111                     // first-launch broadcast.
   2112                     if (DEBUG_BACKUP) {
   2113                         Slog.i(TAG, "Post-restore of " + packageName
   2114                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
   2115                     }
   2116                     sendFirstLaunchBroadcast(packageName, installerPackage,
   2117                             firstUserIds, firstInstantUserIds);
   2118                 }
   2119 
   2120                 // Send broadcast package appeared if forward locked/external for all users
   2121                 // treat asec-hosted packages like removable media on upgrade
   2122                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
   2123                     if (DEBUG_INSTALL) {
   2124                         Slog.i(TAG, "upgrading pkg " + res.pkg
   2125                                 + " is ASEC-hosted -> AVAILABLE");
   2126                     }
   2127                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
   2128                     ArrayList<String> pkgList = new ArrayList<>(1);
   2129                     pkgList.add(packageName);
   2130                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
   2131                 }
   2132             }
   2133 
   2134             // Work that needs to happen on first install within each user
   2135             if (firstUserIds != null && firstUserIds.length > 0) {
   2136                 synchronized (mPackages) {
   2137                     for (int userId : firstUserIds) {
   2138                         // If this app is a browser and it's newly-installed for some
   2139                         // users, clear any default-browser state in those users. The
   2140                         // app's nature doesn't depend on the user, so we can just check
   2141                         // its browser nature in any user and generalize.
   2142                         if (packageIsBrowser(packageName, userId)) {
   2143                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
   2144                         }
   2145 
   2146                         // We may also need to apply pending (restored) runtime
   2147                         // permission grants within these users.
   2148                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
   2149                     }
   2150                 }
   2151             }
   2152 
   2153             if (allNewUsers && !update) {
   2154                 notifyPackageAdded(packageName);
   2155             }
   2156 
   2157             // Log current value of "unknown sources" setting
   2158             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
   2159                     getUnknownSourcesSettings());
   2160 
   2161             // Remove the replaced package's older resources safely now
   2162             // We delete after a gc for applications  on sdcard.
   2163             if (res.removedInfo != null && res.removedInfo.args != null) {
   2164                 Runtime.getRuntime().gc();
   2165                 synchronized (mInstallLock) {
   2166                     res.removedInfo.args.doPostDeleteLI(true);
   2167                 }
   2168             } else {
   2169                 // Force a gc to clear up things. Ask for a background one, it's fine to go on
   2170                 // and not block here.
   2171                 VMRuntime.getRuntime().requestConcurrentGC();
   2172             }
   2173 
   2174             // Notify DexManager that the package was installed for new users.
   2175             // The updated users should already be indexed and the package code paths
   2176             // should not change.
   2177             // Don't notify the manager for ephemeral apps as they are not expected to
   2178             // survive long enough to benefit of background optimizations.
   2179             for (int userId : firstUserIds) {
   2180                 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
   2181                 // There's a race currently where some install events may interleave with an uninstall.
   2182                 // This can lead to package info being null (b/36642664).
   2183                 if (info != null) {
   2184                     mDexManager.notifyPackageInstalled(info, userId);
   2185                 }
   2186             }
   2187         }
   2188 
   2189         // If someone is watching installs - notify them
   2190         if (installObserver != null) {
   2191             try {
   2192                 Bundle extras = extrasForInstallResult(res);
   2193                 installObserver.onPackageInstalled(res.name, res.returnCode,
   2194                         res.returnMsg, extras);
   2195             } catch (RemoteException e) {
   2196                 Slog.i(TAG, "Observer no longer exists.");
   2197             }
   2198         }
   2199     }
   2200 
   2201     private StorageEventListener mStorageListener = new StorageEventListener() {
   2202         @Override
   2203         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
   2204             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
   2205                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
   2206                     final String volumeUuid = vol.getFsUuid();
   2207 
   2208                     // Clean up any users or apps that were removed or recreated
   2209                     // while this volume was missing
   2210                     sUserManager.reconcileUsers(volumeUuid);
   2211                     reconcileApps(volumeUuid);
   2212 
   2213                     // Clean up any install sessions that expired or were
   2214                     // cancelled while this volume was missing
   2215                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
   2216 
   2217                     loadPrivatePackages(vol);
   2218 
   2219                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
   2220                     unloadPrivatePackages(vol);
   2221                 }
   2222             }
   2223         }
   2224 
   2225         @Override
   2226         public void onVolumeForgotten(String fsUuid) {
   2227             if (TextUtils.isEmpty(fsUuid)) {
   2228                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
   2229                 return;
   2230             }
   2231 
   2232             // Remove any apps installed on the forgotten volume
   2233             synchronized (mPackages) {
   2234                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
   2235                 for (PackageSetting ps : packages) {
   2236                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
   2237                     deletePackageVersioned(new VersionedPackage(ps.name,
   2238                             PackageManager.VERSION_CODE_HIGHEST),
   2239                             new LegacyPackageDeleteObserver(null).getBinder(),
   2240                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
   2241                     // Try very hard to release any references to this package
   2242                     // so we don't risk the system server being killed due to
   2243                     // open FDs
   2244                     AttributeCache.instance().removePackage(ps.name);
   2245                 }
   2246 
   2247                 mSettings.onVolumeForgotten(fsUuid);
   2248                 mSettings.writeLPr();
   2249             }
   2250         }
   2251     };
   2252 
   2253     Bundle extrasForInstallResult(PackageInstalledInfo res) {
   2254         Bundle extras = null;
   2255         switch (res.returnCode) {
   2256             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
   2257                 extras = new Bundle();
   2258                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
   2259                         res.origPermission);
   2260                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
   2261                         res.origPackage);
   2262                 break;
   2263             }
   2264             case PackageManager.INSTALL_SUCCEEDED: {
   2265                 extras = new Bundle();
   2266                 extras.putBoolean(Intent.EXTRA_REPLACING,
   2267                         res.removedInfo != null && res.removedInfo.removedPackage != null);
   2268                 break;
   2269             }
   2270         }
   2271         return extras;
   2272     }
   2273 
   2274     void scheduleWriteSettingsLocked() {
   2275         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
   2276             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
   2277         }
   2278     }
   2279 
   2280     void scheduleWritePackageListLocked(int userId) {
   2281         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
   2282             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
   2283             msg.arg1 = userId;
   2284             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
   2285         }
   2286     }
   2287 
   2288     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
   2289         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
   2290         scheduleWritePackageRestrictionsLocked(userId);
   2291     }
   2292 
   2293     void scheduleWritePackageRestrictionsLocked(int userId) {
   2294         final int[] userIds = (userId == UserHandle.USER_ALL)
   2295                 ? sUserManager.getUserIds() : new int[]{userId};
   2296         for (int nextUserId : userIds) {
   2297             if (!sUserManager.exists(nextUserId)) return;
   2298             mDirtyUsers.add(nextUserId);
   2299             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
   2300                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
   2301             }
   2302         }
   2303     }
   2304 
   2305     public static PackageManagerService main(Context context, Installer installer,
   2306             boolean factoryTest, boolean onlyCore) {
   2307         // Self-check for initial settings.
   2308         PackageManagerServiceCompilerMapping.checkProperties();
   2309 
   2310         PackageManagerService m = new PackageManagerService(context, installer,
   2311                 factoryTest, onlyCore);
   2312         m.enableSystemUserPackages();
   2313         ServiceManager.addService("package", m);
   2314         final PackageManagerNative pmn = m.new PackageManagerNative();
   2315         ServiceManager.addService("package_native", pmn);
   2316         return m;
   2317     }
   2318 
   2319     private void enableSystemUserPackages() {
   2320         if (!UserManager.isSplitSystemUser()) {
   2321             return;
   2322         }
   2323         // For system user, enable apps based on the following conditions:
   2324         // - app is whitelisted or belong to one of these groups:
   2325         //   -- system app which has no launcher icons
   2326         //   -- system app which has INTERACT_ACROSS_USERS permission
   2327         //   -- system IME app
   2328         // - app is not in the blacklist
   2329         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
   2330         Set<String> enableApps = new ArraySet<>();
   2331         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
   2332                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
   2333                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
   2334         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
   2335         enableApps.addAll(wlApps);
   2336         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
   2337                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
   2338         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
   2339         enableApps.removeAll(blApps);
   2340         Log.i(TAG, "Applications installed for system user: " + enableApps);
   2341         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
   2342                 UserHandle.SYSTEM);
   2343         final int allAppsSize = allAps.size();
   2344         synchronized (mPackages) {
   2345             for (int i = 0; i < allAppsSize; i++) {
   2346                 String pName = allAps.get(i);
   2347                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
   2348                 // Should not happen, but we shouldn't be failing if it does
   2349                 if (pkgSetting == null) {
   2350                     continue;
   2351                 }
   2352                 boolean install = enableApps.contains(pName);
   2353                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
   2354                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
   2355                             + " for system user");
   2356                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
   2357                 }
   2358             }
   2359             scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
   2360         }
   2361     }
   2362 
   2363     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
   2364         DisplayManager displayManager = (DisplayManager) context.getSystemService(
   2365                 Context.DISPLAY_SERVICE);
   2366         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
   2367     }
   2368 
   2369     /**
   2370      * Requests that files preopted on a secondary system partition be copied to the data partition
   2371      * if possible.  Note that the actual copying of the files is accomplished by init for security
   2372      * reasons. This simply requests that the copy takes place and awaits confirmation of its
   2373      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
   2374      */
   2375     private static void requestCopyPreoptedFiles() {
   2376         final int WAIT_TIME_MS = 100;
   2377         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
   2378         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
   2379             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
   2380             // We will wait for up to 100 seconds.
   2381             final long timeStart = SystemClock.uptimeMillis();
   2382             final long timeEnd = timeStart + 100 * 1000;
   2383             long timeNow = timeStart;
   2384             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
   2385                 try {
   2386                     Thread.sleep(WAIT_TIME_MS);
   2387                 } catch (InterruptedException e) {
   2388                     // Do nothing
   2389                 }
   2390                 timeNow = SystemClock.uptimeMillis();
   2391                 if (timeNow > timeEnd) {
   2392                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
   2393                     Slog.wtf(TAG, "cppreopt did not finish!");
   2394                     break;
   2395                 }
   2396             }
   2397 
   2398             Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
   2399         }
   2400     }
   2401 
   2402     public PackageManagerService(Context context, Installer installer,
   2403             boolean factoryTest, boolean onlyCore) {
   2404         LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
   2405         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
   2406         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
   2407                 SystemClock.uptimeMillis());
   2408 
   2409         if (mSdkVersion <= 0) {
   2410             Slog.w(TAG, "**** ro.build.version.sdk not set!");
   2411         }
   2412 
   2413         mContext = context;
   2414 
   2415         mFactoryTest = factoryTest;
   2416         mOnlyCore = onlyCore;
   2417         mMetrics = new DisplayMetrics();
   2418         mInstaller = installer;
   2419 
   2420         // Create sub-components that provide services / data. Order here is important.
   2421         synchronized (mInstallLock) {
   2422         synchronized (mPackages) {
   2423             // Expose private service for system components to use.
   2424             LocalServices.addService(
   2425                     PackageManagerInternal.class, new PackageManagerInternalImpl());
   2426             sUserManager = new UserManagerService(context, this,
   2427                     new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
   2428             mPermissionManager = PermissionManagerService.create(context,
   2429                     new DefaultPermissionGrantedCallback() {
   2430                         @Override
   2431                         public void onDefaultRuntimePermissionsGranted(int userId) {
   2432                             synchronized(mPackages) {
   2433                                 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
   2434                             }
   2435                         }
   2436                     }, mPackages /*externalLock*/);
   2437             mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
   2438             mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
   2439         }
   2440         }
   2441         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
   2442                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2443         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
   2444                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2445         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
   2446                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2447         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
   2448                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2449         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
   2450                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2451         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
   2452                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2453         mSettings.addSharedUserLPw("android.uid.se", SE_UID,
   2454                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
   2455 
   2456         String separateProcesses = SystemProperties.get("debug.separate_processes");
   2457         if (separateProcesses != null && separateProcesses.length() > 0) {
   2458             if ("*".equals(separateProcesses)) {
   2459                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
   2460                 mSeparateProcesses = null;
   2461                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
   2462             } else {
   2463                 mDefParseFlags = 0;
   2464                 mSeparateProcesses = separateProcesses.split(",");
   2465                 Slog.w(TAG, "Running with debug.separate_processes: "
   2466                         + separateProcesses);
   2467             }
   2468         } else {
   2469             mDefParseFlags = 0;
   2470             mSeparateProcesses = null;
   2471         }
   2472 
   2473         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
   2474                 "*dexopt*");
   2475         DexManager.Listener dexManagerListener = DexLogger.getListener(this,
   2476                 installer, mInstallLock);
   2477         mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock,
   2478                 dexManagerListener);
   2479         mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
   2480         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
   2481 
   2482         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
   2483                 FgThread.get().getLooper());
   2484 
   2485         getDefaultDisplayMetrics(context, mMetrics);
   2486 
   2487         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
   2488         SystemConfig systemConfig = SystemConfig.getInstance();
   2489         mAvailableFeatures = systemConfig.getAvailableFeatures();
   2490         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   2491 
   2492         mProtectedPackages = new ProtectedPackages(mContext);
   2493 
   2494         synchronized (mInstallLock) {
   2495         // writer
   2496         synchronized (mPackages) {
   2497             mHandlerThread = new ServiceThread(TAG,
   2498                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
   2499             mHandlerThread.start();
   2500             mHandler = new PackageHandler(mHandlerThread.getLooper());
   2501             mProcessLoggingHandler = new ProcessLoggingHandler();
   2502             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
   2503             mInstantAppRegistry = new InstantAppRegistry(this);
   2504 
   2505             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
   2506             final int builtInLibCount = libConfig.size();
   2507             for (int i = 0; i < builtInLibCount; i++) {
   2508                 String name = libConfig.keyAt(i);
   2509                 String path = libConfig.valueAt(i);
   2510                 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
   2511                         SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
   2512             }
   2513 
   2514             SELinuxMMAC.readInstallPolicy();
   2515 
   2516             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
   2517             FallbackCategoryProvider.loadFallbacks();
   2518             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   2519 
   2520             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
   2521             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
   2522             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   2523 
   2524             // Clean up orphaned packages for which the code path doesn't exist
   2525             // and they are an update to a system app - caused by bug/32321269
   2526             final int packageSettingCount = mSettings.mPackages.size();
   2527             for (int i = packageSettingCount - 1; i >= 0; i--) {
   2528                 PackageSetting ps = mSettings.mPackages.valueAt(i);
   2529                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
   2530                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
   2531                     mSettings.mPackages.removeAt(i);
   2532                     mSettings.enableSystemPackageLPw(ps.name);
   2533                 }
   2534             }
   2535 
   2536             if (mFirstBoot) {
   2537                 requestCopyPreoptedFiles();
   2538             }
   2539 
   2540             String customResolverActivity = Resources.getSystem().getString(
   2541                     R.string.config_customResolverActivity);
   2542             if (TextUtils.isEmpty(customResolverActivity)) {
   2543                 customResolverActivity = null;
   2544             } else {
   2545                 mCustomResolverComponentName = ComponentName.unflattenFromString(
   2546                         customResolverActivity);
   2547             }
   2548 
   2549             long startTime = SystemClock.uptimeMillis();
   2550 
   2551             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
   2552                     startTime);
   2553 
   2554             final String bootClassPath = System.getenv("BOOTCLASSPATH");
   2555             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
   2556 
   2557             if (bootClassPath == null) {
   2558                 Slog.w(TAG, "No BOOTCLASSPATH found!");
   2559             }
   2560 
   2561             if (systemServerClassPath == null) {
   2562                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
   2563             }
   2564 
   2565             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
   2566 
   2567             final VersionInfo ver = mSettings.getInternalVersion();
   2568             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
   2569             if (mIsUpgrade) {
   2570                 logCriticalInfo(Log.INFO,
   2571                         "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
   2572             }
   2573 
   2574             // when upgrading from pre-M, promote system app permissions from install to runtime
   2575             mPromoteSystemApps =
   2576                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
   2577 
   2578             // When upgrading from pre-N, we need to handle package extraction like first boot,
   2579             // as there is no profiling data available.
   2580             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
   2581 
   2582             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
   2583 
   2584             // save off the names of pre-existing system packages prior to scanning; we don't
   2585             // want to automatically grant runtime permissions for new system apps
   2586             if (mPromoteSystemApps) {
   2587                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
   2588                 while (pkgSettingIter.hasNext()) {
   2589                     PackageSetting ps = pkgSettingIter.next();
   2590                     if (isSystemApp(ps)) {
   2591                         mExistingSystemPackages.add(ps.name);
   2592                     }
   2593                 }
   2594             }
   2595 
   2596             mCacheDir = preparePackageParserCache(mIsUpgrade);
   2597 
   2598             // Set flag to monitor and not change apk file paths when
   2599             // scanning install directories.
   2600             int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
   2601 
   2602             if (mIsUpgrade || mFirstBoot) {
   2603                 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
   2604             }
   2605 
   2606             // Collect vendor/product overlay packages. (Do this before scanning any apps.)
   2607             // For security and version matching reason, only consider
   2608             // overlay packages if they reside in the right directory.
   2609             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
   2610                     mDefParseFlags
   2611                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2612                     scanFlags
   2613                     | SCAN_AS_SYSTEM
   2614                     | SCAN_AS_VENDOR,
   2615                     0);
   2616             scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
   2617                     mDefParseFlags
   2618                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2619                     scanFlags
   2620                     | SCAN_AS_SYSTEM
   2621                     | SCAN_AS_PRODUCT,
   2622                     0);
   2623 
   2624             mParallelPackageParserCallback.findStaticOverlayPackages();
   2625 
   2626             // Find base frameworks (resource packages without code).
   2627             scanDirTracedLI(frameworkDir,
   2628                     mDefParseFlags
   2629                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2630                     scanFlags
   2631                     | SCAN_NO_DEX
   2632                     | SCAN_AS_SYSTEM
   2633                     | SCAN_AS_PRIVILEGED,
   2634                     0);
   2635 
   2636             // Collect privileged system packages.
   2637             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
   2638             scanDirTracedLI(privilegedAppDir,
   2639                     mDefParseFlags
   2640                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2641                     scanFlags
   2642                     | SCAN_AS_SYSTEM
   2643                     | SCAN_AS_PRIVILEGED,
   2644                     0);
   2645 
   2646             // Collect ordinary system packages.
   2647             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
   2648             scanDirTracedLI(systemAppDir,
   2649                     mDefParseFlags
   2650                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2651                     scanFlags
   2652                     | SCAN_AS_SYSTEM,
   2653                     0);
   2654 
   2655             // Collect privileged vendor packages.
   2656             File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
   2657             try {
   2658                 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
   2659             } catch (IOException e) {
   2660                 // failed to look up canonical path, continue with original one
   2661             }
   2662             scanDirTracedLI(privilegedVendorAppDir,
   2663                     mDefParseFlags
   2664                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2665                     scanFlags
   2666                     | SCAN_AS_SYSTEM
   2667                     | SCAN_AS_VENDOR
   2668                     | SCAN_AS_PRIVILEGED,
   2669                     0);
   2670 
   2671             // Collect ordinary vendor packages.
   2672             File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
   2673             try {
   2674                 vendorAppDir = vendorAppDir.getCanonicalFile();
   2675             } catch (IOException e) {
   2676                 // failed to look up canonical path, continue with original one
   2677             }
   2678             scanDirTracedLI(vendorAppDir,
   2679                     mDefParseFlags
   2680                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2681                     scanFlags
   2682                     | SCAN_AS_SYSTEM
   2683                     | SCAN_AS_VENDOR,
   2684                     0);
   2685 
   2686             // Collect privileged odm packages. /odm is another vendor partition
   2687             // other than /vendor.
   2688             File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
   2689                         "priv-app");
   2690             try {
   2691                 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
   2692             } catch (IOException e) {
   2693                 // failed to look up canonical path, continue with original one
   2694             }
   2695             scanDirTracedLI(privilegedOdmAppDir,
   2696                     mDefParseFlags
   2697                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2698                     scanFlags
   2699                     | SCAN_AS_SYSTEM
   2700                     | SCAN_AS_VENDOR
   2701                     | SCAN_AS_PRIVILEGED,
   2702                     0);
   2703 
   2704             // Collect ordinary odm packages. /odm is another vendor partition
   2705             // other than /vendor.
   2706             File odmAppDir = new File(Environment.getOdmDirectory(), "app");
   2707             try {
   2708                 odmAppDir = odmAppDir.getCanonicalFile();
   2709             } catch (IOException e) {
   2710                 // failed to look up canonical path, continue with original one
   2711             }
   2712             scanDirTracedLI(odmAppDir,
   2713                     mDefParseFlags
   2714                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2715                     scanFlags
   2716                     | SCAN_AS_SYSTEM
   2717                     | SCAN_AS_VENDOR,
   2718                     0);
   2719 
   2720             // Collect all OEM packages.
   2721             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
   2722             scanDirTracedLI(oemAppDir,
   2723                     mDefParseFlags
   2724                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2725                     scanFlags
   2726                     | SCAN_AS_SYSTEM
   2727                     | SCAN_AS_OEM,
   2728                     0);
   2729 
   2730             // Collected privileged product packages.
   2731             File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
   2732             try {
   2733                 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
   2734             } catch (IOException e) {
   2735                 // failed to look up canonical path, continue with original one
   2736             }
   2737             scanDirTracedLI(privilegedProductAppDir,
   2738                     mDefParseFlags
   2739                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2740                     scanFlags
   2741                     | SCAN_AS_SYSTEM
   2742                     | SCAN_AS_PRODUCT
   2743                     | SCAN_AS_PRIVILEGED,
   2744                     0);
   2745 
   2746             // Collect ordinary product packages.
   2747             File productAppDir = new File(Environment.getProductDirectory(), "app");
   2748             try {
   2749                 productAppDir = productAppDir.getCanonicalFile();
   2750             } catch (IOException e) {
   2751                 // failed to look up canonical path, continue with original one
   2752             }
   2753             scanDirTracedLI(productAppDir,
   2754                     mDefParseFlags
   2755                     | PackageParser.PARSE_IS_SYSTEM_DIR,
   2756                     scanFlags
   2757                     | SCAN_AS_SYSTEM
   2758                     | SCAN_AS_PRODUCT,
   2759                     0);
   2760 
   2761             // Prune any system packages that no longer exist.
   2762             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
   2763             // Stub packages must either be replaced with full versions in the /data
   2764             // partition or be disabled.
   2765             final List<String> stubSystemApps = new ArrayList<>();
   2766             if (!mOnlyCore) {
   2767                 // do this first before mucking with mPackages for the "expecting better" case
   2768                 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
   2769                 while (pkgIterator.hasNext()) {
   2770                     final PackageParser.Package pkg = pkgIterator.next();
   2771                     if (pkg.isStub) {
   2772                         stubSystemApps.add(pkg.packageName);
   2773                     }
   2774                 }
   2775 
   2776                 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
   2777                 while (psit.hasNext()) {
   2778                     PackageSetting ps = psit.next();
   2779 
   2780                     /*
   2781                      * If this is not a system app, it can't be a
   2782                      * disable system app.
   2783                      */
   2784                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
   2785                         continue;
   2786                     }
   2787 
   2788                     /*
   2789                      * If the package is scanned, it's not erased.
   2790                      */
   2791                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
   2792                     if (scannedPkg != null) {
   2793                         /*
   2794                          * If the system app is both scanned and in the
   2795                          * disabled packages list, then it must have been
   2796                          * added via OTA. Remove it from the currently
   2797                          * scanned package so the previously user-installed
   2798                          * application can be scanned.
   2799                          */
   2800                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
   2801                             logCriticalInfo(Log.WARN,
   2802                                     "Expecting better updated system app for " + ps.name
   2803                                     + "; removing system app.  Last known"
   2804                                     + " codePath=" + ps.codePathString
   2805                                     + ", versionCode=" + ps.versionCode
   2806                                     + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
   2807                             removePackageLI(scannedPkg, true);
   2808                             mExpectingBetter.put(ps.name, ps.codePath);
   2809                         }
   2810 
   2811                         continue;
   2812                     }
   2813 
   2814                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
   2815                         psit.remove();
   2816                         logCriticalInfo(Log.WARN, "System package " + ps.name
   2817                                 + " no longer exists; it's data will be wiped");
   2818                         // Actual deletion of code and data will be handled by later
   2819                         // reconciliation step
   2820                     } else {
   2821                         // we still have a disabled system package, but, it still might have
   2822                         // been removed. check the code path still exists and check there's
   2823                         // still a package. the latter can happen if an OTA keeps the same
   2824                         // code path, but, changes the package name.
   2825                         final PackageSetting disabledPs =
   2826                                 mSettings.getDisabledSystemPkgLPr(ps.name);
   2827                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()
   2828                                 || disabledPs.pkg == null) {
   2829                             possiblyDeletedUpdatedSystemApps.add(ps.name);
   2830                         }
   2831                     }
   2832                 }
   2833             }
   2834 
   2835             //delete tmp files
   2836             deleteTempPackageFiles();
   2837 
   2838             final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
   2839 
   2840             // Remove any shared userIDs that have no associated packages
   2841             mSettings.pruneSharedUsersLPw();
   2842             final long systemScanTime = SystemClock.uptimeMillis() - startTime;
   2843             final int systemPackagesCount = mPackages.size();
   2844             Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
   2845                     + " ms, packageCount: " + systemPackagesCount
   2846                     + " , timePerPackage: "
   2847                     + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
   2848                     + " , cached: " + cachedSystemApps);
   2849             if (mIsUpgrade && systemPackagesCount > 0) {
   2850                 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
   2851                         ((int) systemScanTime) / systemPackagesCount);
   2852             }
   2853             if (!mOnlyCore) {
   2854                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
   2855                         SystemClock.uptimeMillis());
   2856                 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
   2857 
   2858                 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
   2859                         | PackageParser.PARSE_FORWARD_LOCK,
   2860                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
   2861 
   2862                 // Remove disable package settings for updated system apps that were
   2863                 // removed via an OTA. If the update is no longer present, remove the
   2864                 // app completely. Otherwise, revoke their system privileges.
   2865                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
   2866                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
   2867                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
   2868                     final String msg;
   2869                     if (deletedPkg == null) {
   2870                         // should have found an update, but, we didn't; remove everything
   2871                         msg = "Updated system package " + deletedAppName
   2872                                 + " no longer exists; removing its data";
   2873                         // Actual deletion of code and data will be handled by later
   2874                         // reconciliation step
   2875                     } else {
   2876                         // found an update; revoke system privileges
   2877                         msg = "Updated system package + " + deletedAppName
   2878                                 + " no longer exists; revoking system privileges";
   2879 
   2880                         // Don't do anything if a stub is removed from the system image. If
   2881                         // we were to remove the uncompressed version from the /data partition,
   2882                         // this is where it'd be done.
   2883 
   2884                         final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
   2885                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
   2886                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
   2887                     }
   2888                     logCriticalInfo(Log.WARN, msg);
   2889                 }
   2890 
   2891                 /*
   2892                  * Make sure all system apps that we expected to appear on
   2893                  * the userdata partition actually showed up. If they never
   2894                  * appeared, crawl back and revive the system version.
   2895                  */
   2896                 for (int i = 0; i < mExpectingBetter.size(); i++) {
   2897                     final String packageName = mExpectingBetter.keyAt(i);
   2898                     if (!mPackages.containsKey(packageName)) {
   2899                         final File scanFile = mExpectingBetter.valueAt(i);
   2900 
   2901                         logCriticalInfo(Log.WARN, "Expected better " + packageName
   2902                                 + " but never showed up; reverting to system");
   2903 
   2904                         final @ParseFlags int reparseFlags;
   2905                         final @ScanFlags int rescanFlags;
   2906                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
   2907                             reparseFlags =
   2908                                     mDefParseFlags |
   2909                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2910                             rescanFlags =
   2911                                     scanFlags
   2912                                     | SCAN_AS_SYSTEM
   2913                                     | SCAN_AS_PRIVILEGED;
   2914                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
   2915                             reparseFlags =
   2916                                     mDefParseFlags |
   2917                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2918                             rescanFlags =
   2919                                     scanFlags
   2920                                     | SCAN_AS_SYSTEM;
   2921                         } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
   2922                                 || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
   2923                             reparseFlags =
   2924                                     mDefParseFlags |
   2925                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2926                             rescanFlags =
   2927                                     scanFlags
   2928                                     | SCAN_AS_SYSTEM
   2929                                     | SCAN_AS_VENDOR
   2930                                     | SCAN_AS_PRIVILEGED;
   2931                         } else if (FileUtils.contains(vendorAppDir, scanFile)
   2932                                 || FileUtils.contains(odmAppDir, scanFile)) {
   2933                             reparseFlags =
   2934                                     mDefParseFlags |
   2935                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2936                             rescanFlags =
   2937                                     scanFlags
   2938                                     | SCAN_AS_SYSTEM
   2939                                     | SCAN_AS_VENDOR;
   2940                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
   2941                             reparseFlags =
   2942                                     mDefParseFlags |
   2943                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2944                             rescanFlags =
   2945                                     scanFlags
   2946                                     | SCAN_AS_SYSTEM
   2947                                     | SCAN_AS_OEM;
   2948                         } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
   2949                             reparseFlags =
   2950                                     mDefParseFlags |
   2951                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2952                             rescanFlags =
   2953                                     scanFlags
   2954                                     | SCAN_AS_SYSTEM
   2955                                     | SCAN_AS_PRODUCT
   2956                                     | SCAN_AS_PRIVILEGED;
   2957                         } else if (FileUtils.contains(productAppDir, scanFile)) {
   2958                             reparseFlags =
   2959                                     mDefParseFlags |
   2960                                     PackageParser.PARSE_IS_SYSTEM_DIR;
   2961                             rescanFlags =
   2962                                     scanFlags
   2963                                     | SCAN_AS_SYSTEM
   2964                                     | SCAN_AS_PRODUCT;
   2965                         } else {
   2966                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
   2967                             continue;
   2968                         }
   2969 
   2970                         mSettings.enableSystemPackageLPw(packageName);
   2971 
   2972                         try {
   2973                             scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
   2974                         } catch (PackageManagerException e) {
   2975                             Slog.e(TAG, "Failed to parse original system package: "
   2976                                     + e.getMessage());
   2977                         }
   2978                     }
   2979                 }
   2980 
   2981                 // Uncompress and install any stubbed system applications.
   2982                 // This must be done last to ensure all stubs are replaced or disabled.
   2983                 decompressSystemApplications(stubSystemApps, scanFlags);
   2984 
   2985                 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
   2986                                 - cachedSystemApps;
   2987 
   2988                 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
   2989                 final int dataPackagesCount = mPackages.size() - systemPackagesCount;
   2990                 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
   2991                         + " ms, packageCount: " + dataPackagesCount
   2992                         + " , timePerPackage: "
   2993                         + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
   2994                         + " , cached: " + cachedNonSystemApps);
   2995                 if (mIsUpgrade && dataPackagesCount > 0) {
   2996                     MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
   2997                             ((int) dataScanTime) / dataPackagesCount);
   2998                 }
   2999             }
   3000             mExpectingBetter.clear();
   3001 
   3002             // Resolve the storage manager.
   3003             mStorageManagerPackage = getStorageManagerPackageName();
   3004 
   3005             // Resolve protected action filters. Only the setup wizard is allowed to
   3006             // have a high priority filter for these actions.
   3007             mSetupWizardPackage = getSetupWizardPackageName();
   3008             if (mProtectedFilters.size() > 0) {
   3009                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
   3010                     Slog.i(TAG, "No setup wizard;"
   3011                         + " All protected intents capped to priority 0");
   3012                 }
   3013                 for (ActivityIntentInfo filter : mProtectedFilters) {
   3014                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
   3015                         if (DEBUG_FILTERS) {
   3016                             Slog.i(TAG, "Found setup wizard;"
   3017                                 + " allow priority " + filter.getPriority() + ";"
   3018                                 + " package: " + filter.activity.info.packageName
   3019                                 + " activity: " + filter.activity.className
   3020                                 + " priority: " + filter.getPriority());
   3021                         }
   3022                         // skip setup wizard; allow it to keep the high priority filter
   3023                         continue;
   3024                     }
   3025                     if (DEBUG_FILTERS) {
   3026                         Slog.i(TAG, "Protected action; cap priority to 0;"
   3027                                 + " package: " + filter.activity.info.packageName
   3028                                 + " activity: " + filter.activity.className
   3029                                 + " origPrio: " + filter.getPriority());
   3030                     }
   3031                     filter.setPriority(0);
   3032                 }
   3033             }
   3034 
   3035             mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
   3036 
   3037             mDeferProtectedFilters = false;
   3038             mProtectedFilters.clear();
   3039 
   3040             // Now that we know all of the shared libraries, update all clients to have
   3041             // the correct library paths.
   3042             updateAllSharedLibrariesLPw(null);
   3043 
   3044             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
   3045                 // NOTE: We ignore potential failures here during a system scan (like
   3046                 // the rest of the commands above) because there's precious little we
   3047                 // can do about it. A settings error is reported, though.
   3048                 final List<String> changedAbiCodePath =
   3049                         adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
   3050                 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
   3051                     for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
   3052                         final String codePathString = changedAbiCodePath.get(i);
   3053                         try {
   3054                             mInstaller.rmdex(codePathString,
   3055                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
   3056                         } catch (InstallerException ignored) {
   3057                         }
   3058                     }
   3059                 }
   3060                 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
   3061                 // SELinux domain.
   3062                 setting.fixSeInfoLocked();
   3063             }
   3064 
   3065             // Now that we know all the packages we are keeping,
   3066             // read and update their last usage times.
   3067             mPackageUsage.read(mPackages);
   3068             mCompilerStats.read();
   3069 
   3070             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
   3071                     SystemClock.uptimeMillis());
   3072             Slog.i(TAG, "Time to scan packages: "
   3073                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
   3074                     + " seconds");
   3075 
   3076             // If the platform SDK has changed since the last time we booted,
   3077             // we need to re-grant app permission to catch any new ones that
   3078             // appear.  This is really a hack, and means that apps can in some
   3079             // cases get permissions that the user didn't initially explicitly
   3080             // allow...  it would be nice to have some better way to handle
   3081             // this situation.
   3082             final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
   3083             if (sdkUpdated) {
   3084                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
   3085                         + mSdkVersion + "; regranting permissions for internal storage");
   3086             }
   3087             mPermissionManager.updateAllPermissions(
   3088                     StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
   3089                     mPermissionCallback);
   3090             ver.sdkVersion = mSdkVersion;
   3091 
   3092             // If this is the first boot or an update from pre-M, and it is a normal
   3093             // boot, then we need to initialize the default preferred apps across
   3094             // all defined users.
   3095             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
   3096                 for (UserInfo user : sUserManager.getUsers(true)) {
   3097                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
   3098                     applyFactoryDefaultBrowserLPw(user.id);
   3099                     primeDomainVerificationsLPw(user.id);
   3100                 }
   3101             }
   3102 
   3103             // Prepare storage for system user really early during boot,
   3104             // since core system apps like SettingsProvider and SystemUI
   3105             // can't wait for user to start
   3106             final int storageFlags;
   3107             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
   3108                 storageFlags = StorageManager.FLAG_STORAGE_DE;
   3109             } else {
   3110                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
   3111             }
   3112             List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
   3113                     UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
   3114                     true /* onlyCoreApps */);
   3115             mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
   3116                 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
   3117                         Trace.TRACE_TAG_PACKAGE_MANAGER);
   3118                 traceLog.traceBegin("AppDataFixup");
   3119                 try {
   3120                     mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
   3121                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
   3122                 } catch (InstallerException e) {
   3123                     Slog.w(TAG, "Trouble fixing GIDs", e);
   3124                 }
   3125                 traceLog.traceEnd();
   3126 
   3127                 traceLog.traceBegin("AppDataPrepare");
   3128                 if (deferPackages == null || deferPackages.isEmpty()) {
   3129                     return;
   3130                 }
   3131                 int count = 0;
   3132                 for (String pkgName : deferPackages) {
   3133                     PackageParser.Package pkg = null;
   3134                     synchronized (mPackages) {
   3135                         PackageSetting ps = mSettings.getPackageLPr(pkgName);
   3136                         if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
   3137                             pkg = ps.pkg;
   3138                         }
   3139                     }
   3140                     if (pkg != null) {
   3141                         synchronized (mInstallLock) {
   3142                             prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
   3143                                     true /* maybeMigrateAppData */);
   3144                         }
   3145                         count++;
   3146                     }
   3147                 }
   3148                 traceLog.traceEnd();
   3149                 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
   3150             }, "prepareAppData");
   3151 
   3152             // If this is first boot after an OTA, and a normal boot, then
   3153             // we need to clear code cache directories.
   3154             // Note that we do *not* clear the application profiles. These remain valid
   3155             // across OTAs and are used to drive profile verification (post OTA) and
   3156             // profile compilation (without waiting to collect a fresh set of profiles).
   3157             if (mIsUpgrade && !onlyCore) {
   3158                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
   3159                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
   3160                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
   3161                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
   3162                         // No apps are running this early, so no need to freeze
   3163                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
   3164                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
   3165                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   3166                     }
   3167                 }
   3168                 ver.fingerprint = Build.FINGERPRINT;
   3169             }
   3170 
   3171             checkDefaultBrowser();
   3172 
   3173             // clear only after permissions and other defaults have been updated
   3174             mExistingSystemPackages.clear();
   3175             mPromoteSystemApps = false;
   3176 
   3177             // All the changes are done during package scanning.
   3178             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
   3179 
   3180             // can downgrade to reader
   3181             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
   3182             mSettings.writeLPr();
   3183             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3184             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
   3185                     SystemClock.uptimeMillis());
   3186 
   3187             if (!mOnlyCore) {
   3188                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
   3189                 mRequiredInstallerPackage = getRequiredInstallerLPr();
   3190                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
   3191                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
   3192                 if (mIntentFilterVerifierComponent != null) {
   3193                     mIntentFilterVerifier = new IntentVerifierProxy(mContext,
   3194                             mIntentFilterVerifierComponent);
   3195                 } else {
   3196                     mIntentFilterVerifier = null;
   3197                 }
   3198                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
   3199                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
   3200                         SharedLibraryInfo.VERSION_UNDEFINED);
   3201                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
   3202                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
   3203                         SharedLibraryInfo.VERSION_UNDEFINED);
   3204             } else {
   3205                 mRequiredVerifierPackage = null;
   3206                 mRequiredInstallerPackage = null;
   3207                 mRequiredUninstallerPackage = null;
   3208                 mIntentFilterVerifierComponent = null;
   3209                 mIntentFilterVerifier = null;
   3210                 mServicesSystemSharedLibraryPackageName = null;
   3211                 mSharedSystemSharedLibraryPackageName = null;
   3212             }
   3213 
   3214             mInstallerService = new PackageInstallerService(context, this);
   3215             final Pair<ComponentName, String> instantAppResolverComponent =
   3216                     getInstantAppResolverLPr();
   3217             if (instantAppResolverComponent != null) {
   3218                 if (DEBUG_INSTANT) {
   3219                     Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
   3220                 }
   3221                 mInstantAppResolverConnection = new InstantAppResolverConnection(
   3222                         mContext, instantAppResolverComponent.first,
   3223                         instantAppResolverComponent.second);
   3224                 mInstantAppResolverSettingsComponent =
   3225                         getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
   3226             } else {
   3227                 mInstantAppResolverConnection = null;
   3228                 mInstantAppResolverSettingsComponent = null;
   3229             }
   3230             updateInstantAppInstallerLocked(null);
   3231 
   3232             // Read and update the usage of dex files.
   3233             // Do this at the end of PM init so that all the packages have their
   3234             // data directory reconciled.
   3235             // At this point we know the code paths of the packages, so we can validate
   3236             // the disk file and build the internal cache.
   3237             // The usage file is expected to be small so loading and verifying it
   3238             // should take a fairly small time compare to the other activities (e.g. package
   3239             // scanning).
   3240             final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
   3241             final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
   3242             for (int userId : currentUserIds) {
   3243                 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
   3244             }
   3245             mDexManager.load(userPackages);
   3246             if (mIsUpgrade) {
   3247                 MetricsLogger.histogram(null, "ota_package_manager_init_time",
   3248                         (int) (SystemClock.uptimeMillis() - startTime));
   3249             }
   3250         } // synchronized (mPackages)
   3251         } // synchronized (mInstallLock)
   3252 
   3253         // Now after opening every single application zip, make sure they
   3254         // are all flushed.  Not really needed, but keeps things nice and
   3255         // tidy.
   3256         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
   3257         Runtime.getRuntime().gc();
   3258         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3259 
   3260         // The initial scanning above does many calls into installd while
   3261         // holding the mPackages lock, but we're mostly interested in yelling
   3262         // once we have a booted system.
   3263         mInstaller.setWarnIfHeld(mPackages);
   3264 
   3265         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   3266     }
   3267 
   3268     /**
   3269      * Uncompress and install stub applications.
   3270      * <p>In order to save space on the system partition, some applications are shipped in a
   3271      * compressed form. In addition the compressed bits for the full application, the
   3272      * system image contains a tiny stub comprised of only the Android manifest.
   3273      * <p>During the first boot, attempt to uncompress and install the full application. If
   3274      * the application can't be installed for any reason, disable the stub and prevent
   3275      * uncompressing the full application during future boots.
   3276      * <p>In order to forcefully attempt an installation of a full application, go to app
   3277      * settings and enable the application.
   3278      */
   3279     private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
   3280         for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
   3281             final String pkgName = stubSystemApps.get(i);
   3282             // skip if the system package is already disabled
   3283             if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
   3284                 stubSystemApps.remove(i);
   3285                 continue;
   3286             }
   3287             // skip if the package isn't installed (?!); this should never happen
   3288             final PackageParser.Package pkg = mPackages.get(pkgName);
   3289             if (pkg == null) {
   3290                 stubSystemApps.remove(i);
   3291                 continue;
   3292             }
   3293             // skip if the package has been disabled by the user
   3294             final PackageSetting ps = mSettings.mPackages.get(pkgName);
   3295             if (ps != null) {
   3296                 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
   3297                 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
   3298                     stubSystemApps.remove(i);
   3299                     continue;
   3300                 }
   3301             }
   3302 
   3303             if (DEBUG_COMPRESSION) {
   3304                 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
   3305             }
   3306 
   3307             // uncompress the binary to its eventual destination on /data
   3308             final File scanFile = decompressPackage(pkg);
   3309             if (scanFile == null) {
   3310                 continue;
   3311             }
   3312 
   3313             // install the package to replace the stub on /system
   3314             try {
   3315                 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
   3316                 removePackageLI(pkg, true /*chatty*/);
   3317                 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
   3318                 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
   3319                         UserHandle.USER_SYSTEM, "android");
   3320                 stubSystemApps.remove(i);
   3321                 continue;
   3322             } catch (PackageManagerException e) {
   3323                 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
   3324             }
   3325 
   3326             // any failed attempt to install the package will be cleaned up later
   3327         }
   3328 
   3329         // disable any stub still left; these failed to install the full application
   3330         for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
   3331             final String pkgName = stubSystemApps.get(i);
   3332             final PackageSetting ps = mSettings.mPackages.get(pkgName);
   3333             ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
   3334                     UserHandle.USER_SYSTEM, "android");
   3335             logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
   3336         }
   3337     }
   3338 
   3339     /**
   3340      * Decompresses the given package on the system image onto
   3341      * the /data partition.
   3342      * @return The directory the package was decompressed into. Otherwise, {@code null}.
   3343      */
   3344     private File decompressPackage(PackageParser.Package pkg) {
   3345         final File[] compressedFiles = getCompressedFiles(pkg.codePath);
   3346         if (compressedFiles == null || compressedFiles.length == 0) {
   3347             if (DEBUG_COMPRESSION) {
   3348                 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
   3349             }
   3350             return null;
   3351         }
   3352         final File dstCodePath =
   3353                 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
   3354         int ret = PackageManager.INSTALL_SUCCEEDED;
   3355         try {
   3356             Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
   3357             Os.chmod(dstCodePath.getAbsolutePath(), 0755);
   3358             for (File srcFile : compressedFiles) {
   3359                 final String srcFileName = srcFile.getName();
   3360                 final String dstFileName = srcFileName.substring(
   3361                         0, srcFileName.length() - COMPRESSED_EXTENSION.length());
   3362                 final File dstFile = new File(dstCodePath, dstFileName);
   3363                 ret = decompressFile(srcFile, dstFile);
   3364                 if (ret != PackageManager.INSTALL_SUCCEEDED) {
   3365                     logCriticalInfo(Log.ERROR, "Failed to decompress"
   3366                             + "; pkg: " + pkg.packageName
   3367                             + ", file: " + dstFileName);
   3368                     break;
   3369                 }
   3370             }
   3371         } catch (ErrnoException e) {
   3372             logCriticalInfo(Log.ERROR, "Failed to decompress"
   3373                     + "; pkg: " + pkg.packageName
   3374                     + ", err: " + e.errno);
   3375         }
   3376         if (ret == PackageManager.INSTALL_SUCCEEDED) {
   3377             final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
   3378             NativeLibraryHelper.Handle handle = null;
   3379             try {
   3380                 handle = NativeLibraryHelper.Handle.create(dstCodePath);
   3381                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
   3382                         null /*abiOverride*/);
   3383             } catch (IOException e) {
   3384                 logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
   3385                         + "; pkg: " + pkg.packageName);
   3386                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   3387             } finally {
   3388                 IoUtils.closeQuietly(handle);
   3389             }
   3390         }
   3391         if (ret != PackageManager.INSTALL_SUCCEEDED) {
   3392             if (dstCodePath == null || !dstCodePath.exists()) {
   3393                 return null;
   3394             }
   3395             removeCodePathLI(dstCodePath);
   3396             return null;
   3397         }
   3398 
   3399         return dstCodePath;
   3400     }
   3401 
   3402     private void updateInstantAppInstallerLocked(String modifiedPackage) {
   3403         // we're only interested in updating the installer appliction when 1) it's not
   3404         // already set or 2) the modified package is the installer
   3405         if (mInstantAppInstallerActivity != null
   3406                 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
   3407                         .equals(modifiedPackage)) {
   3408             return;
   3409         }
   3410         setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
   3411     }
   3412 
   3413     private static File preparePackageParserCache(boolean isUpgrade) {
   3414         if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
   3415             return null;
   3416         }
   3417 
   3418         // Disable package parsing on eng builds to allow for faster incremental development.
   3419         if (Build.IS_ENG) {
   3420             return null;
   3421         }
   3422 
   3423         if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
   3424             Slog.i(TAG, "Disabling package parser cache due to system property.");
   3425             return null;
   3426         }
   3427 
   3428         // The base directory for the package parser cache lives under /data/system/.
   3429         final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
   3430                 "package_cache");
   3431         if (cacheBaseDir == null) {
   3432             return null;
   3433         }
   3434 
   3435         // If this is a system upgrade scenario, delete the contents of the package cache dir.
   3436         // This also serves to "GC" unused entries when the package cache version changes (which
   3437         // can only happen during upgrades).
   3438         if (isUpgrade) {
   3439             FileUtils.deleteContents(cacheBaseDir);
   3440         }
   3441 
   3442 
   3443         // Return the versioned package cache directory. This is something like
   3444         // "/data/system/package_cache/1"
   3445         File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
   3446 
   3447         if (cacheDir == null) {
   3448             // Something went wrong. Attempt to delete everything and return.
   3449             Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
   3450             FileUtils.deleteContentsAndDir(cacheBaseDir);
   3451             return null;
   3452         }
   3453 
   3454         // The following is a workaround to aid development on non-numbered userdebug
   3455         // builds or cases where "adb sync" is used on userdebug builds. If we detect that
   3456         // the system partition is newer.
   3457         //
   3458         // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
   3459         // that starts with "eng." to signify that this is an engineering build and not
   3460         // destined for release.
   3461         if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
   3462             Slog.w(TAG, "Wiping cache directory because the system partition changed.");
   3463 
   3464             // Heuristic: If the /system directory has been modified recently due to an "adb sync"
   3465             // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
   3466             // in general and should not be used for production changes. In this specific case,
   3467             // we know that they will work.
   3468             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
   3469             if (cacheDir.lastModified() < frameworkDir.lastModified()) {
   3470                 FileUtils.deleteContents(cacheBaseDir);
   3471                 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
   3472             }
   3473         }
   3474 
   3475         return cacheDir;
   3476     }
   3477 
   3478     @Override
   3479     public boolean isFirstBoot() {
   3480         // allow instant applications
   3481         return mFirstBoot;
   3482     }
   3483 
   3484     @Override
   3485     public boolean isOnlyCoreApps() {
   3486         // allow instant applications
   3487         return mOnlyCore;
   3488     }
   3489 
   3490     @Override
   3491     public boolean isUpgrade() {
   3492         // allow instant applications
   3493         // The system property allows testing ota flow when upgraded to the same image.
   3494         return mIsUpgrade || SystemProperties.getBoolean(
   3495                 "persist.pm.mock-upgrade", false /* default */);
   3496     }
   3497 
   3498     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
   3499         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
   3500 
   3501         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
   3502                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3503                 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
   3504         if (matches.size() == 1) {
   3505             return matches.get(0).getComponentInfo().packageName;
   3506         } else if (matches.size() == 0) {
   3507             Log.e(TAG, "There should probably be a verifier, but, none were found");
   3508             return null;
   3509         }
   3510         throw new RuntimeException("There must be exactly one verifier; found " + matches);
   3511     }
   3512 
   3513     private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
   3514         synchronized (mPackages) {
   3515             SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
   3516             if (libraryEntry == null) {
   3517                 throw new IllegalStateException("Missing required shared library:" + name);
   3518             }
   3519             return libraryEntry.apk;
   3520         }
   3521     }
   3522 
   3523     private @NonNull String getRequiredInstallerLPr() {
   3524         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
   3525         intent.addCategory(Intent.CATEGORY_DEFAULT);
   3526         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
   3527 
   3528         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
   3529                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3530                 UserHandle.USER_SYSTEM);
   3531         if (matches.size() == 1) {
   3532             ResolveInfo resolveInfo = matches.get(0);
   3533             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
   3534                 throw new RuntimeException("The installer must be a privileged app");
   3535             }
   3536             return matches.get(0).getComponentInfo().packageName;
   3537         } else {
   3538             throw new RuntimeException("There must be exactly one installer; found " + matches);
   3539         }
   3540     }
   3541 
   3542     private @NonNull String getRequiredUninstallerLPr() {
   3543         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
   3544         intent.addCategory(Intent.CATEGORY_DEFAULT);
   3545         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
   3546 
   3547         final ResolveInfo resolveInfo = resolveIntent(intent, null,
   3548                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3549                 UserHandle.USER_SYSTEM);
   3550         if (resolveInfo == null ||
   3551                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
   3552             throw new RuntimeException("There must be exactly one uninstaller; found "
   3553                     + resolveInfo);
   3554         }
   3555         return resolveInfo.getComponentInfo().packageName;
   3556     }
   3557 
   3558     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
   3559         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
   3560 
   3561         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
   3562                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   3563                 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
   3564         ResolveInfo best = null;
   3565         final int N = matches.size();
   3566         for (int i = 0; i < N; i++) {
   3567             final ResolveInfo cur = matches.get(i);
   3568             final String packageName = cur.getComponentInfo().packageName;
   3569             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
   3570                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
   3571                 continue;
   3572             }
   3573 
   3574             if (best == null || cur.priority > best.priority) {
   3575                 best = cur;
   3576             }
   3577         }
   3578 
   3579         if (best != null) {
   3580             return best.getComponentInfo().getComponentName();
   3581         }
   3582         Slog.w(TAG, "Intent filter verifier not found");
   3583         return null;
   3584     }
   3585 
   3586     @Override
   3587     public @Nullable ComponentName getInstantAppResolverComponent() {
   3588         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   3589             return null;
   3590         }
   3591         synchronized (mPackages) {
   3592             final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
   3593             if (instantAppResolver == null) {
   3594                 return null;
   3595             }
   3596             return instantAppResolver.first;
   3597         }
   3598     }
   3599 
   3600     private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
   3601         final String[] packageArray =
   3602                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
   3603         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
   3604             if (DEBUG_INSTANT) {
   3605                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
   3606             }
   3607             return null;
   3608         }
   3609 
   3610         final int callingUid = Binder.getCallingUid();
   3611         final int resolveFlags =
   3612                 MATCH_DIRECT_BOOT_AWARE
   3613                 | MATCH_DIRECT_BOOT_UNAWARE
   3614                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
   3615         String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
   3616         final Intent resolverIntent = new Intent(actionName);
   3617         List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
   3618                 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
   3619         final int N = resolvers.size();
   3620         if (N == 0) {
   3621             if (DEBUG_INSTANT) {
   3622                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
   3623             }
   3624             return null;
   3625         }
   3626 
   3627         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
   3628         for (int i = 0; i < N; i++) {
   3629             final ResolveInfo info = resolvers.get(i);
   3630 
   3631             if (info.serviceInfo == null) {
   3632                 continue;
   3633             }
   3634 
   3635             final String packageName = info.serviceInfo.packageName;
   3636             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
   3637                 if (DEBUG_INSTANT) {
   3638                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
   3639                             + " pkg: " + packageName + ", info:" + info);
   3640                 }
   3641                 continue;
   3642             }
   3643 
   3644             if (DEBUG_INSTANT) {
   3645                 Slog.v(TAG, "Ephemeral resolver found;"
   3646                         + " pkg: " + packageName + ", info:" + info);
   3647             }
   3648             return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
   3649         }
   3650         if (DEBUG_INSTANT) {
   3651             Slog.v(TAG, "Ephemeral resolver NOT found");
   3652         }
   3653         return null;
   3654     }
   3655 
   3656     private @Nullable ActivityInfo getInstantAppInstallerLPr() {
   3657         String[] orderedActions = Build.IS_ENG
   3658                 ? new String[]{
   3659                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
   3660                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
   3661                 : new String[]{
   3662                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
   3663 
   3664         final int resolveFlags =
   3665                 MATCH_DIRECT_BOOT_AWARE
   3666                         | MATCH_DIRECT_BOOT_UNAWARE
   3667                         | Intent.FLAG_IGNORE_EPHEMERAL
   3668                         | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
   3669         final Intent intent = new Intent();
   3670         intent.addCategory(Intent.CATEGORY_DEFAULT);
   3671         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
   3672         List<ResolveInfo> matches = null;
   3673         for (String action : orderedActions) {
   3674             intent.setAction(action);
   3675             matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
   3676                     resolveFlags, UserHandle.USER_SYSTEM);
   3677             if (matches.isEmpty()) {
   3678                 if (DEBUG_INSTANT) {
   3679                     Slog.d(TAG, "Instant App installer not found with " + action);
   3680                 }
   3681             } else {
   3682                 break;
   3683             }
   3684         }
   3685         Iterator<ResolveInfo> iter = matches.iterator();
   3686         while (iter.hasNext()) {
   3687             final ResolveInfo rInfo = iter.next();
   3688             final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
   3689             if (ps != null) {
   3690                 final PermissionsState permissionsState = ps.getPermissionsState();
   3691                 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
   3692                         || Build.IS_ENG) {
   3693                     continue;
   3694                 }
   3695             }
   3696             iter.remove();
   3697         }
   3698         if (matches.size() == 0) {
   3699             return null;
   3700         } else if (matches.size() == 1) {
   3701             return (ActivityInfo) matches.get(0).getComponentInfo();
   3702         } else {
   3703             throw new RuntimeException(
   3704                     "There must be at most one ephemeral installer; found " + matches);
   3705         }
   3706     }
   3707 
   3708     private @Nullable ComponentName getInstantAppResolverSettingsLPr(
   3709             @NonNull ComponentName resolver) {
   3710         final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
   3711                 .addCategory(Intent.CATEGORY_DEFAULT)
   3712                 .setPackage(resolver.getPackageName());
   3713         final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
   3714         List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
   3715                 UserHandle.USER_SYSTEM);
   3716         if (matches.isEmpty()) {
   3717             return null;
   3718         }
   3719         return matches.get(0).getComponentInfo().getComponentName();
   3720     }
   3721 
   3722     private void primeDomainVerificationsLPw(int userId) {
   3723         if (DEBUG_DOMAIN_VERIFICATION) {
   3724             Slog.d(TAG, "Priming domain verifications in user " + userId);
   3725         }
   3726 
   3727         SystemConfig systemConfig = SystemConfig.getInstance();
   3728         ArraySet<String> packages = systemConfig.getLinkedApps();
   3729 
   3730         for (String packageName : packages) {
   3731             PackageParser.Package pkg = mPackages.get(packageName);
   3732             if (pkg != null) {
   3733                 if (!pkg.isSystem()) {
   3734                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
   3735                     continue;
   3736                 }
   3737 
   3738                 ArraySet<String> domains = null;
   3739                 for (PackageParser.Activity a : pkg.activities) {
   3740                     for (ActivityIntentInfo filter : a.intents) {
   3741                         if (hasValidDomains(filter)) {
   3742                             if (domains == null) {
   3743                                 domains = new ArraySet<String>();
   3744                             }
   3745                             domains.addAll(filter.getHostsList());
   3746                         }
   3747                     }
   3748                 }
   3749 
   3750                 if (domains != null && domains.size() > 0) {
   3751                     if (DEBUG_DOMAIN_VERIFICATION) {
   3752                         Slog.v(TAG, "      + " + packageName);
   3753                     }
   3754                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
   3755                     // state w.r.t. the formal app-linkage "no verification attempted" state;
   3756                     // and then 'always' in the per-user state actually used for intent resolution.
   3757                     final IntentFilterVerificationInfo ivi;
   3758                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
   3759                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
   3760                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
   3761                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
   3762                 } else {
   3763                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
   3764                             + "' does not handle web links");
   3765                 }
   3766             } else {
   3767                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
   3768             }
   3769         }
   3770 
   3771         scheduleWritePackageRestrictionsLocked(userId);
   3772         scheduleWriteSettingsLocked();
   3773     }
   3774 
   3775     private void applyFactoryDefaultBrowserLPw(int userId) {
   3776         // The default browser app's package name is stored in a string resource,
   3777         // with a product-specific overlay used for vendor customization.
   3778         String browserPkg = mContext.getResources().getString(
   3779                 com.android.internal.R.string.default_browser);
   3780         if (!TextUtils.isEmpty(browserPkg)) {
   3781             // non-empty string => required to be a known package
   3782             PackageSetting ps = mSettings.mPackages.get(browserPkg);
   3783             if (ps == null) {
   3784                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
   3785                 browserPkg = null;
   3786             } else {
   3787                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
   3788             }
   3789         }
   3790 
   3791         // Nothing valid explicitly set? Make the factory-installed browser the explicit
   3792         // default.  If there's more than one, just leave everything alone.
   3793         if (browserPkg == null) {
   3794             calculateDefaultBrowserLPw(userId);
   3795         }
   3796     }
   3797 
   3798     private void calculateDefaultBrowserLPw(int userId) {
   3799         List<String> allBrowsers = resolveAllBrowserApps(userId);
   3800         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
   3801         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
   3802     }
   3803 
   3804     private List<String> resolveAllBrowserApps(int userId) {
   3805         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
   3806         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
   3807                 PackageManager.MATCH_ALL, userId);
   3808 
   3809         final int count = list.size();
   3810         List<String> result = new ArrayList<String>(count);
   3811         for (int i=0; i<count; i++) {
   3812             ResolveInfo info = list.get(i);
   3813             if (info.activityInfo == null
   3814                     || !info.handleAllWebDataURI
   3815                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
   3816                     || result.contains(info.activityInfo.packageName)) {
   3817                 continue;
   3818             }
   3819             result.add(info.activityInfo.packageName);
   3820         }
   3821 
   3822         return result;
   3823     }
   3824 
   3825     private boolean packageIsBrowser(String packageName, int userId) {
   3826         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
   3827                 PackageManager.MATCH_ALL, userId);
   3828         final int N = list.size();
   3829         for (int i = 0; i < N; i++) {
   3830             ResolveInfo info = list.get(i);
   3831             if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
   3832                 return true;
   3833             }
   3834         }
   3835         return false;
   3836     }
   3837 
   3838     private void checkDefaultBrowser() {
   3839         final int myUserId = UserHandle.myUserId();
   3840         final String packageName = getDefaultBrowserPackageName(myUserId);
   3841         if (packageName != null) {
   3842             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
   3843             if (info == null) {
   3844                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
   3845                 synchronized (mPackages) {
   3846                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
   3847                 }
   3848             }
   3849         }
   3850     }
   3851 
   3852     @Override
   3853     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   3854             throws RemoteException {
   3855         try {
   3856             return super.onTransact(code, data, reply, flags);
   3857         } catch (RuntimeException e) {
   3858             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
   3859                 Slog.wtf(TAG, "Package Manager Crash", e);
   3860             }
   3861             throw e;
   3862         }
   3863     }
   3864 
   3865     static int[] appendInts(int[] cur, int[] add) {
   3866         if (add == null) return cur;
   3867         if (cur == null) return add;
   3868         final int N = add.length;
   3869         for (int i=0; i<N; i++) {
   3870             cur = appendInt(cur, add[i]);
   3871         }
   3872         return cur;
   3873     }
   3874 
   3875     /**
   3876      * Returns whether or not a full application can see an instant application.
   3877      * <p>
   3878      * Currently, there are three cases in which this can occur:
   3879      * <ol>
   3880      * <li>The calling application is a "special" process. Special processes
   3881      *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
   3882      * <li>The calling application has the permission
   3883      *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
   3884      * <li>The calling application is the default launcher on the
   3885      *     system partition.</li>
   3886      * </ol>
   3887      */
   3888     private boolean canViewInstantApps(int callingUid, int userId) {
   3889         if (callingUid < Process.FIRST_APPLICATION_UID) {
   3890             return true;
   3891         }
   3892         if (mContext.checkCallingOrSelfPermission(
   3893                 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
   3894             return true;
   3895         }
   3896         if (mContext.checkCallingOrSelfPermission(
   3897                 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
   3898             final ComponentName homeComponent = getDefaultHomeActivity(userId);
   3899             if (homeComponent != null
   3900                     && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
   3901                 return true;
   3902             }
   3903         }
   3904         return false;
   3905     }
   3906 
   3907     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
   3908         if (!sUserManager.exists(userId)) return null;
   3909         if (ps == null) {
   3910             return null;
   3911         }
   3912         final int callingUid = Binder.getCallingUid();
   3913         // Filter out ephemeral app metadata:
   3914         //   * The system/shell/root can see metadata for any app
   3915         //   * An installed app can see metadata for 1) other installed apps
   3916         //     and 2) ephemeral apps that have explicitly interacted with it
   3917         //   * Ephemeral apps can only see their own data and exposed installed apps
   3918         //   * Holding a signature permission allows seeing instant apps
   3919         if (filterAppAccessLPr(ps, callingUid, userId)) {
   3920             return null;
   3921         }
   3922 
   3923         if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
   3924                 && ps.isSystem()) {
   3925             flags |= MATCH_ANY_USER;
   3926         }
   3927 
   3928         final PackageUserState state = ps.readUserState(userId);
   3929         PackageParser.Package p = ps.pkg;
   3930         if (p != null) {
   3931             final PermissionsState permissionsState = ps.getPermissionsState();
   3932 
   3933             // Compute GIDs only if requested
   3934             final int[] gids = (flags & PackageManager.GET_GIDS) == 0
   3935                     ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
   3936             // Compute granted permissions only if package has requested permissions
   3937             final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
   3938                     ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
   3939 
   3940             PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
   3941                     ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
   3942 
   3943             if (packageInfo == null) {
   3944                 return null;
   3945             }
   3946 
   3947             packageInfo.packageName = packageInfo.applicationInfo.packageName =
   3948                     resolveExternalPackageNameLPr(p);
   3949 
   3950             return packageInfo;
   3951         } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
   3952             PackageInfo pi = new PackageInfo();
   3953             pi.packageName = ps.name;
   3954             pi.setLongVersionCode(ps.versionCode);
   3955             pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
   3956             pi.firstInstallTime = ps.firstInstallTime;
   3957             pi.lastUpdateTime = ps.lastUpdateTime;
   3958 
   3959             ApplicationInfo ai = new ApplicationInfo();
   3960             ai.packageName = ps.name;
   3961             ai.uid = UserHandle.getUid(userId, ps.appId);
   3962             ai.primaryCpuAbi = ps.primaryCpuAbiString;
   3963             ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
   3964             ai.setVersionCode(ps.versionCode);
   3965             ai.flags = ps.pkgFlags;
   3966             ai.privateFlags = ps.pkgPrivateFlags;
   3967             pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
   3968 
   3969             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
   3970                     + ps.name + "]. Provides a minimum info.");
   3971             return pi;
   3972         } else {
   3973             return null;
   3974         }
   3975     }
   3976 
   3977     @Override
   3978     public void checkPackageStartable(String packageName, int userId) {
   3979         final int callingUid = Binder.getCallingUid();
   3980         if (getInstantAppPackageName(callingUid) != null) {
   3981             throw new SecurityException("Instant applications don't have access to this method");
   3982         }
   3983         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
   3984         synchronized (mPackages) {
   3985             final PackageSetting ps = mSettings.mPackages.get(packageName);
   3986             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
   3987                 throw new SecurityException("Package " + packageName + " was not found!");
   3988             }
   3989 
   3990             if (!ps.getInstalled(userId)) {
   3991                 throw new SecurityException(
   3992                         "Package " + packageName + " was not installed for user " + userId + "!");
   3993             }
   3994 
   3995             if (mSafeMode && !ps.isSystem()) {
   3996                 throw new SecurityException("Package " + packageName + " not a system app!");
   3997             }
   3998 
   3999             if (mFrozenPackages.contains(packageName)) {
   4000                 throw new SecurityException("Package " + packageName + " is currently frozen!");
   4001             }
   4002 
   4003             if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
   4004                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
   4005             }
   4006         }
   4007     }
   4008 
   4009     @Override
   4010     public boolean isPackageAvailable(String packageName, int userId) {
   4011         if (!sUserManager.exists(userId)) return false;
   4012         final int callingUid = Binder.getCallingUid();
   4013         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   4014                 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
   4015         synchronized (mPackages) {
   4016             PackageParser.Package p = mPackages.get(packageName);
   4017             if (p != null) {
   4018                 final PackageSetting ps = (PackageSetting) p.mExtras;
   4019                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   4020                     return false;
   4021                 }
   4022                 if (ps != null) {
   4023                     final PackageUserState state = ps.readUserState(userId);
   4024                     if (state != null) {
   4025                         return PackageParser.isAvailable(state);
   4026                     }
   4027                 }
   4028             }
   4029         }
   4030         return false;
   4031     }
   4032 
   4033     @Override
   4034     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
   4035         return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
   4036                 flags, Binder.getCallingUid(), userId);
   4037     }
   4038 
   4039     @Override
   4040     public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
   4041             int flags, int userId) {
   4042         return getPackageInfoInternal(versionedPackage.getPackageName(),
   4043                 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
   4044     }
   4045 
   4046     /**
   4047      * Important: The provided filterCallingUid is used exclusively to filter out packages
   4048      * that can be seen based on user state. It's typically the original caller uid prior
   4049      * to clearing. Because it can only be provided by trusted code, it's value can be
   4050      * trusted and will be used as-is; unlike userId which will be validated by this method.
   4051      */
   4052     private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
   4053             int flags, int filterCallingUid, int userId) {
   4054         if (!sUserManager.exists(userId)) return null;
   4055         flags = updateFlagsForPackage(flags, userId, packageName);
   4056         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   4057                 false /* requireFullPermission */, false /* checkShell */, "get package info");
   4058 
   4059         // reader
   4060         synchronized (mPackages) {
   4061             // Normalize package name to handle renamed packages and static libs
   4062             packageName = resolveInternalPackageNameLPr(packageName, versionCode);
   4063 
   4064             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
   4065             if (matchFactoryOnly) {
   4066                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
   4067                 if (ps != null) {
   4068                     if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4069                         return null;
   4070                     }
   4071                     if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4072                         return null;
   4073                     }
   4074                     return generatePackageInfo(ps, flags, userId);
   4075                 }
   4076             }
   4077 
   4078             PackageParser.Package p = mPackages.get(packageName);
   4079             if (matchFactoryOnly && p != null && !isSystemApp(p)) {
   4080                 return null;
   4081             }
   4082             if (DEBUG_PACKAGE_INFO)
   4083                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
   4084             if (p != null) {
   4085                 final PackageSetting ps = (PackageSetting) p.mExtras;
   4086                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4087                     return null;
   4088                 }
   4089                 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4090                     return null;
   4091                 }
   4092                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
   4093             }
   4094             if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
   4095                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   4096                 if (ps == null) return null;
   4097                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4098                     return null;
   4099                 }
   4100                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4101                     return null;
   4102                 }
   4103                 return generatePackageInfo(ps, flags, userId);
   4104             }
   4105         }
   4106         return null;
   4107     }
   4108 
   4109     private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
   4110         if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
   4111             return true;
   4112         }
   4113         if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
   4114             return true;
   4115         }
   4116         if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
   4117             return true;
   4118         }
   4119         return false;
   4120     }
   4121 
   4122     private boolean isComponentVisibleToInstantApp(
   4123             @Nullable ComponentName component, @ComponentType int type) {
   4124         if (type == TYPE_ACTIVITY) {
   4125             final PackageParser.Activity activity = mActivities.mActivities.get(component);
   4126             if (activity == null) {
   4127                 return false;
   4128             }
   4129             final boolean visibleToInstantApp =
   4130                     (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
   4131             final boolean explicitlyVisibleToInstantApp =
   4132                     (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
   4133             return visibleToInstantApp && explicitlyVisibleToInstantApp;
   4134         } else if (type == TYPE_RECEIVER) {
   4135             final PackageParser.Activity activity = mReceivers.mActivities.get(component);
   4136             if (activity == null) {
   4137                 return false;
   4138             }
   4139             final boolean visibleToInstantApp =
   4140                     (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
   4141             final boolean explicitlyVisibleToInstantApp =
   4142                     (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
   4143             return visibleToInstantApp && !explicitlyVisibleToInstantApp;
   4144         } else if (type == TYPE_SERVICE) {
   4145             final PackageParser.Service service = mServices.mServices.get(component);
   4146             return service != null
   4147                     ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
   4148                     : false;
   4149         } else if (type == TYPE_PROVIDER) {
   4150             final PackageParser.Provider provider = mProviders.mProviders.get(component);
   4151             return provider != null
   4152                     ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
   4153                     : false;
   4154         } else if (type == TYPE_UNKNOWN) {
   4155             return isComponentVisibleToInstantApp(component);
   4156         }
   4157         return false;
   4158     }
   4159 
   4160     /**
   4161      * Returns whether or not access to the application should be filtered.
   4162      * <p>
   4163      * Access may be limited based upon whether the calling or target applications
   4164      * are instant applications.
   4165      *
   4166      * @see #canAccessInstantApps(int)
   4167      */
   4168     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
   4169             @Nullable ComponentName component, @ComponentType int componentType, int userId) {
   4170         // if we're in an isolated process, get the real calling UID
   4171         if (Process.isIsolated(callingUid)) {
   4172             callingUid = mIsolatedOwners.get(callingUid);
   4173         }
   4174         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   4175         final boolean callerIsInstantApp = instantAppPkgName != null;
   4176         if (ps == null) {
   4177             if (callerIsInstantApp) {
   4178                 // pretend the application exists, but, needs to be filtered
   4179                 return true;
   4180             }
   4181             return false;
   4182         }
   4183         // if the target and caller are the same application, don't filter
   4184         if (isCallerSameApp(ps.name, callingUid)) {
   4185             return false;
   4186         }
   4187         if (callerIsInstantApp) {
   4188             // both caller and target are both instant, but, different applications, filter
   4189             if (ps.getInstantApp(userId)) {
   4190                 return true;
   4191             }
   4192             // request for a specific component; if it hasn't been explicitly exposed through
   4193             // property or instrumentation target, filter
   4194             if (component != null) {
   4195                 final PackageParser.Instrumentation instrumentation =
   4196                         mInstrumentation.get(component);
   4197                 if (instrumentation != null
   4198                         && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
   4199                     return false;
   4200                 }
   4201                 return !isComponentVisibleToInstantApp(component, componentType);
   4202             }
   4203             // request for application; if no components have been explicitly exposed, filter
   4204             return !ps.pkg.visibleToInstantApps;
   4205         }
   4206         if (ps.getInstantApp(userId)) {
   4207             // caller can see all components of all instant applications, don't filter
   4208             if (canViewInstantApps(callingUid, userId)) {
   4209                 return false;
   4210             }
   4211             // request for a specific instant application component, filter
   4212             if (component != null) {
   4213                 return true;
   4214             }
   4215             // request for an instant application; if the caller hasn't been granted access, filter
   4216             return !mInstantAppRegistry.isInstantAccessGranted(
   4217                     userId, UserHandle.getAppId(callingUid), ps.appId);
   4218         }
   4219         return false;
   4220     }
   4221 
   4222     /**
   4223      * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
   4224      */
   4225     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
   4226         return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
   4227     }
   4228 
   4229     private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
   4230             int flags) {
   4231         // Callers can access only the libs they depend on, otherwise they need to explicitly
   4232         // ask for the shared libraries given the caller is allowed to access all static libs.
   4233         if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
   4234             // System/shell/root get to see all static libs
   4235             final int appId = UserHandle.getAppId(uid);
   4236             if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
   4237                     || appId == Process.ROOT_UID) {
   4238                 return false;
   4239             }
   4240             // Installer gets to see all static libs.
   4241             if (PackageManager.PERMISSION_GRANTED
   4242                     == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
   4243                 return false;
   4244             }
   4245         }
   4246 
   4247         // No package means no static lib as it is always on internal storage
   4248         if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
   4249             return false;
   4250         }
   4251 
   4252         final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
   4253                 ps.pkg.staticSharedLibVersion);
   4254         if (libEntry == null) {
   4255             return false;
   4256         }
   4257 
   4258         final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
   4259         final String[] uidPackageNames = getPackagesForUid(resolvedUid);
   4260         if (uidPackageNames == null) {
   4261             return true;
   4262         }
   4263 
   4264         for (String uidPackageName : uidPackageNames) {
   4265             if (ps.name.equals(uidPackageName)) {
   4266                 return false;
   4267             }
   4268             PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
   4269             if (uidPs != null) {
   4270                 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
   4271                         libEntry.info.getName());
   4272                 if (index < 0) {
   4273                     continue;
   4274                 }
   4275                 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
   4276                     return false;
   4277                 }
   4278             }
   4279         }
   4280         return true;
   4281     }
   4282 
   4283     @Override
   4284     public String[] currentToCanonicalPackageNames(String[] names) {
   4285         final int callingUid = Binder.getCallingUid();
   4286         if (getInstantAppPackageName(callingUid) != null) {
   4287             return names;
   4288         }
   4289         final String[] out = new String[names.length];
   4290         // reader
   4291         synchronized (mPackages) {
   4292             final int callingUserId = UserHandle.getUserId(callingUid);
   4293             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
   4294             for (int i=names.length-1; i>=0; i--) {
   4295                 final PackageSetting ps = mSettings.mPackages.get(names[i]);
   4296                 boolean translateName = false;
   4297                 if (ps != null && ps.realName != null) {
   4298                     final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
   4299                     translateName = !targetIsInstantApp
   4300                             || canViewInstantApps
   4301                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
   4302                                     UserHandle.getAppId(callingUid), ps.appId);
   4303                 }
   4304                 out[i] = translateName ? ps.realName : names[i];
   4305             }
   4306         }
   4307         return out;
   4308     }
   4309 
   4310     @Override
   4311     public String[] canonicalToCurrentPackageNames(String[] names) {
   4312         final int callingUid = Binder.getCallingUid();
   4313         if (getInstantAppPackageName(callingUid) != null) {
   4314             return names;
   4315         }
   4316         final String[] out = new String[names.length];
   4317         // reader
   4318         synchronized (mPackages) {
   4319             final int callingUserId = UserHandle.getUserId(callingUid);
   4320             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
   4321             for (int i=names.length-1; i>=0; i--) {
   4322                 final String cur = mSettings.getRenamedPackageLPr(names[i]);
   4323                 boolean translateName = false;
   4324                 if (cur != null) {
   4325                     final PackageSetting ps = mSettings.mPackages.get(names[i]);
   4326                     final boolean targetIsInstantApp =
   4327                             ps != null && ps.getInstantApp(callingUserId);
   4328                     translateName = !targetIsInstantApp
   4329                             || canViewInstantApps
   4330                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
   4331                                     UserHandle.getAppId(callingUid), ps.appId);
   4332                 }
   4333                 out[i] = translateName ? cur : names[i];
   4334             }
   4335         }
   4336         return out;
   4337     }
   4338 
   4339     @Override
   4340     public int getPackageUid(String packageName, int flags, int userId) {
   4341         if (!sUserManager.exists(userId)) return -1;
   4342         final int callingUid = Binder.getCallingUid();
   4343         flags = updateFlagsForPackage(flags, userId, packageName);
   4344         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   4345                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
   4346 
   4347         // reader
   4348         synchronized (mPackages) {
   4349             final PackageParser.Package p = mPackages.get(packageName);
   4350             if (p != null && p.isMatch(flags)) {
   4351                 PackageSetting ps = (PackageSetting) p.mExtras;
   4352                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   4353                     return -1;
   4354                 }
   4355                 return UserHandle.getUid(userId, p.applicationInfo.uid);
   4356             }
   4357             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
   4358                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   4359                 if (ps != null && ps.isMatch(flags)
   4360                         && !filterAppAccessLPr(ps, callingUid, userId)) {
   4361                     return UserHandle.getUid(userId, ps.appId);
   4362                 }
   4363             }
   4364         }
   4365 
   4366         return -1;
   4367     }
   4368 
   4369     @Override
   4370     public int[] getPackageGids(String packageName, int flags, int userId) {
   4371         if (!sUserManager.exists(userId)) return null;
   4372         final int callingUid = Binder.getCallingUid();
   4373         flags = updateFlagsForPackage(flags, userId, packageName);
   4374         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   4375                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
   4376 
   4377         // reader
   4378         synchronized (mPackages) {
   4379             final PackageParser.Package p = mPackages.get(packageName);
   4380             if (p != null && p.isMatch(flags)) {
   4381                 PackageSetting ps = (PackageSetting) p.mExtras;
   4382                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   4383                     return null;
   4384                 }
   4385                 // TODO: Shouldn't this be checking for package installed state for userId and
   4386                 // return null?
   4387                 return ps.getPermissionsState().computeGids(userId);
   4388             }
   4389             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
   4390                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   4391                 if (ps != null && ps.isMatch(flags)
   4392                         && !filterAppAccessLPr(ps, callingUid, userId)) {
   4393                     return ps.getPermissionsState().computeGids(userId);
   4394                 }
   4395             }
   4396         }
   4397 
   4398         return null;
   4399     }
   4400 
   4401     @Override
   4402     public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
   4403         return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
   4404     }
   4405 
   4406     @Override
   4407     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
   4408             int flags) {
   4409         final List<PermissionInfo> permissionList =
   4410                 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
   4411         return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
   4412     }
   4413 
   4414     @Override
   4415     public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
   4416         return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
   4417     }
   4418 
   4419     @Override
   4420     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
   4421         final List<PermissionGroupInfo> permissionList =
   4422                 mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
   4423         return (permissionList == null)
   4424                 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
   4425     }
   4426 
   4427     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
   4428             int filterCallingUid, int userId) {
   4429         if (!sUserManager.exists(userId)) return null;
   4430         PackageSetting ps = mSettings.mPackages.get(packageName);
   4431         if (ps != null) {
   4432             if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4433                 return null;
   4434             }
   4435             if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4436                 return null;
   4437             }
   4438             if (ps.pkg == null) {
   4439                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
   4440                 if (pInfo != null) {
   4441                     return pInfo.applicationInfo;
   4442                 }
   4443                 return null;
   4444             }
   4445             ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
   4446                     ps.readUserState(userId), userId);
   4447             if (ai != null) {
   4448                 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
   4449             }
   4450             return ai;
   4451         }
   4452         return null;
   4453     }
   4454 
   4455     @Override
   4456     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
   4457         return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
   4458     }
   4459 
   4460     /**
   4461      * Important: The provided filterCallingUid is used exclusively to filter out applications
   4462      * that can be seen based on user state. It's typically the original caller uid prior
   4463      * to clearing. Because it can only be provided by trusted code, it's value can be
   4464      * trusted and will be used as-is; unlike userId which will be validated by this method.
   4465      */
   4466     private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
   4467             int filterCallingUid, int userId) {
   4468         if (!sUserManager.exists(userId)) return null;
   4469         flags = updateFlagsForApplication(flags, userId, packageName);
   4470         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   4471                 false /* requireFullPermission */, false /* checkShell */, "get application info");
   4472 
   4473         // writer
   4474         synchronized (mPackages) {
   4475             // Normalize package name to handle renamed packages and static libs
   4476             packageName = resolveInternalPackageNameLPr(packageName,
   4477                     PackageManager.VERSION_CODE_HIGHEST);
   4478 
   4479             PackageParser.Package p = mPackages.get(packageName);
   4480             if (DEBUG_PACKAGE_INFO) Log.v(
   4481                     TAG, "getApplicationInfo " + packageName
   4482                     + ": " + p);
   4483             if (p != null) {
   4484                 PackageSetting ps = mSettings.mPackages.get(packageName);
   4485                 if (ps == null) return null;
   4486                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
   4487                     return null;
   4488                 }
   4489                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
   4490                     return null;
   4491                 }
   4492                 // Note: isEnabledLP() does not apply here - always return info
   4493                 ApplicationInfo ai = PackageParser.generateApplicationInfo(
   4494                         p, flags, ps.readUserState(userId), userId);
   4495                 if (ai != null) {
   4496                     ai.packageName = resolveExternalPackageNameLPr(p);
   4497                 }
   4498                 return ai;
   4499             }
   4500             if ("android".equals(packageName)||"system".equals(packageName)) {
   4501                 return mAndroidApplication;
   4502             }
   4503             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
   4504                 // Already generates the external package name
   4505                 return generateApplicationInfoFromSettingsLPw(packageName,
   4506                         flags, filterCallingUid, userId);
   4507             }
   4508         }
   4509         return null;
   4510     }
   4511 
   4512     private String normalizePackageNameLPr(String packageName) {
   4513         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
   4514         return normalizedPackageName != null ? normalizedPackageName : packageName;
   4515     }
   4516 
   4517     @Override
   4518     public void deletePreloadsFileCache() {
   4519         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
   4520             throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
   4521         }
   4522         File dir = Environment.getDataPreloadsFileCacheDirectory();
   4523         Slog.i(TAG, "Deleting preloaded file cache " + dir);
   4524         FileUtils.deleteContents(dir);
   4525     }
   4526 
   4527     @Override
   4528     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
   4529             final int storageFlags, final IPackageDataObserver observer) {
   4530         mContext.enforceCallingOrSelfPermission(
   4531                 android.Manifest.permission.CLEAR_APP_CACHE, null);
   4532         mHandler.post(() -> {
   4533             boolean success = false;
   4534             try {
   4535                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
   4536                 success = true;
   4537             } catch (IOException e) {
   4538                 Slog.w(TAG, e);
   4539             }
   4540             if (observer != null) {
   4541                 try {
   4542                     observer.onRemoveCompleted(null, success);
   4543                 } catch (RemoteException e) {
   4544                     Slog.w(TAG, e);
   4545                 }
   4546             }
   4547         });
   4548     }
   4549 
   4550     @Override
   4551     public void freeStorage(final String volumeUuid, final long freeStorageSize,
   4552             final int storageFlags, final IntentSender pi) {
   4553         mContext.enforceCallingOrSelfPermission(
   4554                 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
   4555         mHandler.post(() -> {
   4556             boolean success = false;
   4557             try {
   4558                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
   4559                 success = true;
   4560             } catch (IOException e) {
   4561                 Slog.w(TAG, e);
   4562             }
   4563             if (pi != null) {
   4564                 try {
   4565                     pi.sendIntent(null, success ? 1 : 0, null, null, null);
   4566                 } catch (SendIntentException e) {
   4567                     Slog.w(TAG, e);
   4568                 }
   4569             }
   4570         });
   4571     }
   4572 
   4573     /**
   4574      * Blocking call to clear various types of cached data across the system
   4575      * until the requested bytes are available.
   4576      */
   4577     public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
   4578         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   4579         final File file = storage.findPathForUuid(volumeUuid);
   4580         if (file.getUsableSpace() >= bytes) return;
   4581 
   4582         if (ENABLE_FREE_CACHE_V2) {
   4583             final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
   4584                     volumeUuid);
   4585             final boolean aggressive = (storageFlags
   4586                     & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
   4587             final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
   4588 
   4589             // 1. Pre-flight to determine if we have any chance to succeed
   4590             // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
   4591             if (internalVolume && (aggressive || SystemProperties
   4592                     .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
   4593                 deletePreloadsFileCache();
   4594                 if (file.getUsableSpace() >= bytes) return;
   4595             }
   4596 
   4597             // 3. Consider parsed APK data (aggressive only)
   4598             if (internalVolume && aggressive) {
   4599                 FileUtils.deleteContents(mCacheDir);
   4600                 if (file.getUsableSpace() >= bytes) return;
   4601             }
   4602 
   4603             // 4. Consider cached app data (above quotas)
   4604             try {
   4605                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
   4606                         Installer.FLAG_FREE_CACHE_V2);
   4607             } catch (InstallerException ignored) {
   4608             }
   4609             if (file.getUsableSpace() >= bytes) return;
   4610 
   4611             // 5. Consider shared libraries with refcount=0 and age>min cache period
   4612             if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
   4613                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   4614                             Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
   4615                             DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
   4616                 return;
   4617             }
   4618 
   4619             // 6. Consider dexopt output (aggressive only)
   4620             // TODO: Implement
   4621 
   4622             // 7. Consider installed instant apps unused longer than min cache period
   4623             if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
   4624                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   4625                             Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
   4626                             InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
   4627                 return;
   4628             }
   4629 
   4630             // 8. Consider cached app data (below quotas)
   4631             try {
   4632                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
   4633                         Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
   4634             } catch (InstallerException ignored) {
   4635             }
   4636             if (file.getUsableSpace() >= bytes) return;
   4637 
   4638             // 9. Consider DropBox entries
   4639             // TODO: Implement
   4640 
   4641             // 10. Consider instant meta-data (uninstalled apps) older that min cache period
   4642             if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
   4643                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   4644                             Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
   4645                             InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
   4646                 return;
   4647             }
   4648         } else {
   4649             try {
   4650                 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
   4651             } catch (InstallerException ignored) {
   4652             }
   4653             if (file.getUsableSpace() >= bytes) return;
   4654         }
   4655 
   4656         throw new IOException("Failed to free " + bytes + " on storage device at " + file);
   4657     }
   4658 
   4659     private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
   4660             throws IOException {
   4661         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   4662         final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
   4663 
   4664         List<VersionedPackage> packagesToDelete = null;
   4665         final long now = System.currentTimeMillis();
   4666 
   4667         synchronized (mPackages) {
   4668             final int[] allUsers = sUserManager.getUserIds();
   4669             final int libCount = mSharedLibraries.size();
   4670             for (int i = 0; i < libCount; i++) {
   4671                 final LongSparseArray<SharedLibraryEntry> versionedLib
   4672                         = mSharedLibraries.valueAt(i);
   4673                 if (versionedLib == null) {
   4674                     continue;
   4675                 }
   4676                 final int versionCount = versionedLib.size();
   4677                 for (int j = 0; j < versionCount; j++) {
   4678                     SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
   4679                     // Skip packages that are not static shared libs.
   4680                     if (!libInfo.isStatic()) {
   4681                         break;
   4682                     }
   4683                     // Important: We skip static shared libs used for some user since
   4684                     // in such a case we need to keep the APK on the device. The check for
   4685                     // a lib being used for any user is performed by the uninstall call.
   4686                     final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
   4687                     // Resolve the package name - we use synthetic package names internally
   4688                     final String internalPackageName = resolveInternalPackageNameLPr(
   4689                             declaringPackage.getPackageName(),
   4690                             declaringPackage.getLongVersionCode());
   4691                     final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
   4692                     // Skip unused static shared libs cached less than the min period
   4693                     // to prevent pruning a lib needed by a subsequently installed package.
   4694                     if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
   4695                         continue;
   4696                     }
   4697                     if (packagesToDelete == null) {
   4698                         packagesToDelete = new ArrayList<>();
   4699                     }
   4700                     packagesToDelete.add(new VersionedPackage(internalPackageName,
   4701                             declaringPackage.getLongVersionCode()));
   4702                 }
   4703             }
   4704         }
   4705 
   4706         if (packagesToDelete != null) {
   4707             final int packageCount = packagesToDelete.size();
   4708             for (int i = 0; i < packageCount; i++) {
   4709                 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
   4710                 // Delete the package synchronously (will fail of the lib used for any user).
   4711                 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
   4712                         UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
   4713                                 == PackageManager.DELETE_SUCCEEDED) {
   4714                     if (volume.getUsableSpace() >= neededSpace) {
   4715                         return true;
   4716                     }
   4717                 }
   4718             }
   4719         }
   4720 
   4721         return false;
   4722     }
   4723 
   4724     /**
   4725      * Update given flags based on encryption status of current user.
   4726      */
   4727     private int updateFlags(int flags, int userId) {
   4728         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
   4729                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
   4730             // Caller expressed an explicit opinion about what encryption
   4731             // aware/unaware components they want to see, so fall through and
   4732             // give them what they want
   4733         } else {
   4734             // Caller expressed no opinion, so match based on user state
   4735             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
   4736                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
   4737             } else {
   4738                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
   4739             }
   4740         }
   4741         return flags;
   4742     }
   4743 
   4744     private UserManagerInternal getUserManagerInternal() {
   4745         if (mUserManagerInternal == null) {
   4746             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
   4747         }
   4748         return mUserManagerInternal;
   4749     }
   4750 
   4751     private ActivityManagerInternal getActivityManagerInternal() {
   4752         if (mActivityManagerInternal == null) {
   4753             mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
   4754         }
   4755         return mActivityManagerInternal;
   4756     }
   4757 
   4758 
   4759     private DeviceIdleController.LocalService getDeviceIdleController() {
   4760         if (mDeviceIdleController == null) {
   4761             mDeviceIdleController =
   4762                     LocalServices.getService(DeviceIdleController.LocalService.class);
   4763         }
   4764         return mDeviceIdleController;
   4765     }
   4766 
   4767     /**
   4768      * Update given flags when being used to request {@link PackageInfo}.
   4769      */
   4770     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
   4771         final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
   4772         boolean triaged = true;
   4773         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
   4774                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
   4775             // Caller is asking for component details, so they'd better be
   4776             // asking for specific encryption matching behavior, or be triaged
   4777             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
   4778                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
   4779                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
   4780                 triaged = false;
   4781             }
   4782         }
   4783         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
   4784                 | PackageManager.MATCH_SYSTEM_ONLY
   4785                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
   4786             triaged = false;
   4787         }
   4788         if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
   4789             // require the permission to be held; the calling uid and given user id referring
   4790             // to the same user is not sufficient
   4791             mPermissionManager.enforceCrossUserPermission(
   4792                     Binder.getCallingUid(), userId, false, false,
   4793                     !isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId),
   4794                     "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
   4795                     + Debug.getCallers(5));
   4796         } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
   4797                 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
   4798             // If the caller wants all packages and has a restricted profile associated with it,
   4799             // then match all users. This is to make sure that launchers that need to access work
   4800             // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
   4801             // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
   4802             flags |= PackageManager.MATCH_ANY_USER;
   4803         }
   4804         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
   4805             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
   4806                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
   4807         }
   4808         return updateFlags(flags, userId);
   4809     }
   4810 
   4811     /**
   4812      * Update given flags when being used to request {@link ApplicationInfo}.
   4813      */
   4814     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
   4815         return updateFlagsForPackage(flags, userId, cookie);
   4816     }
   4817 
   4818     /**
   4819      * Update given flags when being used to request {@link ComponentInfo}.
   4820      */
   4821     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
   4822         if (cookie instanceof Intent) {
   4823             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
   4824                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
   4825             }
   4826         }
   4827 
   4828         boolean triaged = true;
   4829         // Caller is asking for component details, so they'd better be
   4830         // asking for specific encryption matching behavior, or be triaged
   4831         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
   4832                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
   4833                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
   4834             triaged = false;
   4835         }
   4836         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
   4837             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
   4838                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
   4839         }
   4840 
   4841         return updateFlags(flags, userId);
   4842     }
   4843 
   4844     /**
   4845      * Update given intent when being used to request {@link ResolveInfo}.
   4846      */
   4847     private Intent updateIntentForResolve(Intent intent) {
   4848         if (intent.getSelector() != null) {
   4849             intent = intent.getSelector();
   4850         }
   4851         if (DEBUG_PREFERRED) {
   4852             intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
   4853         }
   4854         return intent;
   4855     }
   4856 
   4857     /**
   4858      * Update given flags when being used to request {@link ResolveInfo}.
   4859      * <p>Instant apps are resolved specially, depending upon context. Minimally,
   4860      * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
   4861      * flag set. However, this flag is only honoured in three circumstances:
   4862      * <ul>
   4863      * <li>when called from a system process</li>
   4864      * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
   4865      * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
   4866      * action and a {@code android.intent.category.BROWSABLE} category</li>
   4867      * </ul>
   4868      */
   4869     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
   4870         return updateFlagsForResolve(flags, userId, intent, callingUid,
   4871                 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
   4872     }
   4873     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
   4874             boolean wantInstantApps) {
   4875         return updateFlagsForResolve(flags, userId, intent, callingUid,
   4876                 wantInstantApps, false /*onlyExposedExplicitly*/);
   4877     }
   4878     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
   4879             boolean wantInstantApps, boolean onlyExposedExplicitly) {
   4880         // Safe mode means we shouldn't match any third-party components
   4881         if (mSafeMode) {
   4882             flags |= PackageManager.MATCH_SYSTEM_ONLY;
   4883         }
   4884         if (getInstantAppPackageName(callingUid) != null) {
   4885             // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
   4886             if (onlyExposedExplicitly) {
   4887                 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
   4888             }
   4889             flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
   4890             flags |= PackageManager.MATCH_INSTANT;
   4891         } else {
   4892             final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
   4893             final boolean allowMatchInstant = wantInstantApps
   4894                     || (wantMatchInstant && canViewInstantApps(callingUid, userId));
   4895             flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
   4896                     | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
   4897             if (!allowMatchInstant) {
   4898                 flags &= ~PackageManager.MATCH_INSTANT;
   4899             }
   4900         }
   4901         return updateFlagsForComponent(flags, userId, intent /*cookie*/);
   4902     }
   4903 
   4904     @Override
   4905     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
   4906         return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
   4907     }
   4908 
   4909     /**
   4910      * Important: The provided filterCallingUid is used exclusively to filter out activities
   4911      * that can be seen based on user state. It's typically the original caller uid prior
   4912      * to clearing. Because it can only be provided by trusted code, it's value can be
   4913      * trusted and will be used as-is; unlike userId which will be validated by this method.
   4914      */
   4915     private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
   4916             int filterCallingUid, int userId) {
   4917         if (!sUserManager.exists(userId)) return null;
   4918         flags = updateFlagsForComponent(flags, userId, component);
   4919 
   4920         if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
   4921             mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   4922                     false /* requireFullPermission */, false /* checkShell */, "get activity info");
   4923         }
   4924 
   4925         synchronized (mPackages) {
   4926             PackageParser.Activity a = mActivities.mActivities.get(component);
   4927 
   4928             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
   4929             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
   4930                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   4931                 if (ps == null) return null;
   4932                 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
   4933                     return null;
   4934                 }
   4935                 return PackageParser.generateActivityInfo(
   4936                         a, flags, ps.readUserState(userId), userId);
   4937             }
   4938             if (mResolveComponentName.equals(component)) {
   4939                 return PackageParser.generateActivityInfo(
   4940                         mResolveActivity, flags, new PackageUserState(), userId);
   4941             }
   4942         }
   4943         return null;
   4944     }
   4945 
   4946     private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
   4947         if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
   4948             return false;
   4949         }
   4950         final long token = Binder.clearCallingIdentity();
   4951         try {
   4952             final int callingUserId = UserHandle.getUserId(callingUid);
   4953             if (ActivityManager.getCurrentUser() != callingUserId) {
   4954                 return false;
   4955             }
   4956             return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
   4957         } finally {
   4958             Binder.restoreCallingIdentity(token);
   4959         }
   4960     }
   4961 
   4962     @Override
   4963     public boolean activitySupportsIntent(ComponentName component, Intent intent,
   4964             String resolvedType) {
   4965         synchronized (mPackages) {
   4966             if (component.equals(mResolveComponentName)) {
   4967                 // The resolver supports EVERYTHING!
   4968                 return true;
   4969             }
   4970             final int callingUid = Binder.getCallingUid();
   4971             final int callingUserId = UserHandle.getUserId(callingUid);
   4972             PackageParser.Activity a = mActivities.mActivities.get(component);
   4973             if (a == null) {
   4974                 return false;
   4975             }
   4976             PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   4977             if (ps == null) {
   4978                 return false;
   4979             }
   4980             if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
   4981                 return false;
   4982             }
   4983             for (int i=0; i<a.intents.size(); i++) {
   4984                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
   4985                         intent.getData(), intent.getCategories(), TAG) >= 0) {
   4986                     return true;
   4987                 }
   4988             }
   4989             return false;
   4990         }
   4991     }
   4992 
   4993     @Override
   4994     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
   4995         if (!sUserManager.exists(userId)) return null;
   4996         final int callingUid = Binder.getCallingUid();
   4997         flags = updateFlagsForComponent(flags, userId, component);
   4998         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   4999                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
   5000         synchronized (mPackages) {
   5001             PackageParser.Activity a = mReceivers.mActivities.get(component);
   5002             if (DEBUG_PACKAGE_INFO) Log.v(
   5003                 TAG, "getReceiverInfo " + component + ": " + a);
   5004             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
   5005                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   5006                 if (ps == null) return null;
   5007                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
   5008                     return null;
   5009                 }
   5010                 return PackageParser.generateActivityInfo(
   5011                         a, flags, ps.readUserState(userId), userId);
   5012             }
   5013         }
   5014         return null;
   5015     }
   5016 
   5017     @Override
   5018     public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
   5019             int flags, int userId) {
   5020         if (!sUserManager.exists(userId)) return null;
   5021         Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
   5022         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5023             return null;
   5024         }
   5025 
   5026         flags = updateFlagsForPackage(flags, userId, null);
   5027 
   5028         final boolean canSeeStaticLibraries =
   5029                 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
   5030                         == PERMISSION_GRANTED
   5031                 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
   5032                         == PERMISSION_GRANTED
   5033                 || canRequestPackageInstallsInternal(packageName,
   5034                         PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
   5035                         false  /* throwIfPermNotDeclared*/)
   5036                 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
   5037                         == PERMISSION_GRANTED;
   5038 
   5039         synchronized (mPackages) {
   5040             List<SharedLibraryInfo> result = null;
   5041 
   5042             final int libCount = mSharedLibraries.size();
   5043             for (int i = 0; i < libCount; i++) {
   5044                 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
   5045                 if (versionedLib == null) {
   5046                     continue;
   5047                 }
   5048 
   5049                 final int versionCount = versionedLib.size();
   5050                 for (int j = 0; j < versionCount; j++) {
   5051                     SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
   5052                     if (!canSeeStaticLibraries && libInfo.isStatic()) {
   5053                         break;
   5054                     }
   5055                     final long identity = Binder.clearCallingIdentity();
   5056                     try {
   5057                         PackageInfo packageInfo = getPackageInfoVersioned(
   5058                                 libInfo.getDeclaringPackage(), flags
   5059                                         | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
   5060                         if (packageInfo == null) {
   5061                             continue;
   5062                         }
   5063                     } finally {
   5064                         Binder.restoreCallingIdentity(identity);
   5065                     }
   5066 
   5067                     SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
   5068                             libInfo.getLongVersion(), libInfo.getType(),
   5069                             libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
   5070                             flags, userId));
   5071 
   5072                     if (result == null) {
   5073                         result = new ArrayList<>();
   5074                     }
   5075                     result.add(resLibInfo);
   5076                 }
   5077             }
   5078 
   5079             return result != null ? new ParceledListSlice<>(result) : null;
   5080         }
   5081     }
   5082 
   5083     private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
   5084             SharedLibraryInfo libInfo, int flags, int userId) {
   5085         List<VersionedPackage> versionedPackages = null;
   5086         final int packageCount = mSettings.mPackages.size();
   5087         for (int i = 0; i < packageCount; i++) {
   5088             PackageSetting ps = mSettings.mPackages.valueAt(i);
   5089 
   5090             if (ps == null) {
   5091                 continue;
   5092             }
   5093 
   5094             if (!ps.getUserState().get(userId).isAvailable(flags)) {
   5095                 continue;
   5096             }
   5097 
   5098             final String libName = libInfo.getName();
   5099             if (libInfo.isStatic()) {
   5100                 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
   5101                 if (libIdx < 0) {
   5102                     continue;
   5103                 }
   5104                 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
   5105                     continue;
   5106                 }
   5107                 if (versionedPackages == null) {
   5108                     versionedPackages = new ArrayList<>();
   5109                 }
   5110                 // If the dependent is a static shared lib, use the public package name
   5111                 String dependentPackageName = ps.name;
   5112                 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
   5113                     dependentPackageName = ps.pkg.manifestPackageName;
   5114                 }
   5115                 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
   5116             } else if (ps.pkg != null) {
   5117                 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
   5118                         || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
   5119                     if (versionedPackages == null) {
   5120                         versionedPackages = new ArrayList<>();
   5121                     }
   5122                     versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
   5123                 }
   5124             }
   5125         }
   5126 
   5127         return versionedPackages;
   5128     }
   5129 
   5130     @Override
   5131     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
   5132         if (!sUserManager.exists(userId)) return null;
   5133         final int callingUid = Binder.getCallingUid();
   5134         flags = updateFlagsForComponent(flags, userId, component);
   5135         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   5136                 false /* requireFullPermission */, false /* checkShell */, "get service info");
   5137         synchronized (mPackages) {
   5138             PackageParser.Service s = mServices.mServices.get(component);
   5139             if (DEBUG_PACKAGE_INFO) Log.v(
   5140                 TAG, "getServiceInfo " + component + ": " + s);
   5141             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
   5142                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   5143                 if (ps == null) return null;
   5144                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
   5145                     return null;
   5146                 }
   5147                 return PackageParser.generateServiceInfo(
   5148                         s, flags, ps.readUserState(userId), userId);
   5149             }
   5150         }
   5151         return null;
   5152     }
   5153 
   5154     @Override
   5155     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
   5156         if (!sUserManager.exists(userId)) return null;
   5157         final int callingUid = Binder.getCallingUid();
   5158         flags = updateFlagsForComponent(flags, userId, component);
   5159         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   5160                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
   5161         synchronized (mPackages) {
   5162             PackageParser.Provider p = mProviders.mProviders.get(component);
   5163             if (DEBUG_PACKAGE_INFO) Log.v(
   5164                 TAG, "getProviderInfo " + component + ": " + p);
   5165             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
   5166                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   5167                 if (ps == null) return null;
   5168                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
   5169                     return null;
   5170                 }
   5171                 return PackageParser.generateProviderInfo(
   5172                         p, flags, ps.readUserState(userId), userId);
   5173             }
   5174         }
   5175         return null;
   5176     }
   5177 
   5178     @Override
   5179     public String[] getSystemSharedLibraryNames() {
   5180         // allow instant applications
   5181         synchronized (mPackages) {
   5182             Set<String> libs = null;
   5183             final int libCount = mSharedLibraries.size();
   5184             for (int i = 0; i < libCount; i++) {
   5185                 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
   5186                 if (versionedLib == null) {
   5187                     continue;
   5188                 }
   5189                 final int versionCount = versionedLib.size();
   5190                 for (int j = 0; j < versionCount; j++) {
   5191                     SharedLibraryEntry libEntry = versionedLib.valueAt(j);
   5192                     if (!libEntry.info.isStatic()) {
   5193                         if (libs == null) {
   5194                             libs = new ArraySet<>();
   5195                         }
   5196                         libs.add(libEntry.info.getName());
   5197                         break;
   5198                     }
   5199                     PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
   5200                     if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
   5201                             UserHandle.getUserId(Binder.getCallingUid()),
   5202                             PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
   5203                         if (libs == null) {
   5204                             libs = new ArraySet<>();
   5205                         }
   5206                         libs.add(libEntry.info.getName());
   5207                         break;
   5208                     }
   5209                 }
   5210             }
   5211 
   5212             if (libs != null) {
   5213                 String[] libsArray = new String[libs.size()];
   5214                 libs.toArray(libsArray);
   5215                 return libsArray;
   5216             }
   5217 
   5218             return null;
   5219         }
   5220     }
   5221 
   5222     @Override
   5223     public @NonNull String getServicesSystemSharedLibraryPackageName() {
   5224         // allow instant applications
   5225         synchronized (mPackages) {
   5226             return mServicesSystemSharedLibraryPackageName;
   5227         }
   5228     }
   5229 
   5230     @Override
   5231     public @NonNull String getSharedSystemSharedLibraryPackageName() {
   5232         // allow instant applications
   5233         synchronized (mPackages) {
   5234             return mSharedSystemSharedLibraryPackageName;
   5235         }
   5236     }
   5237 
   5238     private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
   5239         for (int i = userList.length - 1; i >= 0; --i) {
   5240             final int userId = userList[i];
   5241             // don't add instant app to the list of updates
   5242             if (pkgSetting.getInstantApp(userId)) {
   5243                 continue;
   5244             }
   5245             SparseArray<String> changedPackages = mChangedPackages.get(userId);
   5246             if (changedPackages == null) {
   5247                 changedPackages = new SparseArray<>();
   5248                 mChangedPackages.put(userId, changedPackages);
   5249             }
   5250             Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
   5251             if (sequenceNumbers == null) {
   5252                 sequenceNumbers = new HashMap<>();
   5253                 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
   5254             }
   5255             final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
   5256             if (sequenceNumber != null) {
   5257                 changedPackages.remove(sequenceNumber);
   5258             }
   5259             changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
   5260             sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
   5261         }
   5262         mChangedPackagesSequenceNumber++;
   5263     }
   5264 
   5265     @Override
   5266     public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
   5267         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5268             return null;
   5269         }
   5270         synchronized (mPackages) {
   5271             if (sequenceNumber >= mChangedPackagesSequenceNumber) {
   5272                 return null;
   5273             }
   5274             final SparseArray<String> changedPackages = mChangedPackages.get(userId);
   5275             if (changedPackages == null) {
   5276                 return null;
   5277             }
   5278             final List<String> packageNames =
   5279                     new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
   5280             for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
   5281                 final String packageName = changedPackages.get(i);
   5282                 if (packageName != null) {
   5283                     packageNames.add(packageName);
   5284                 }
   5285             }
   5286             return packageNames.isEmpty()
   5287                     ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
   5288         }
   5289     }
   5290 
   5291     @Override
   5292     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
   5293         // allow instant applications
   5294         ArrayList<FeatureInfo> res;
   5295         synchronized (mAvailableFeatures) {
   5296             res = new ArrayList<>(mAvailableFeatures.size() + 1);
   5297             res.addAll(mAvailableFeatures.values());
   5298         }
   5299         final FeatureInfo fi = new FeatureInfo();
   5300         fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
   5301                 FeatureInfo.GL_ES_VERSION_UNDEFINED);
   5302         res.add(fi);
   5303 
   5304         return new ParceledListSlice<>(res);
   5305     }
   5306 
   5307     @Override
   5308     public boolean hasSystemFeature(String name, int version) {
   5309         // allow instant applications
   5310         synchronized (mAvailableFeatures) {
   5311             final FeatureInfo feat = mAvailableFeatures.get(name);
   5312             if (feat == null) {
   5313                 return false;
   5314             } else {
   5315                 return feat.version >= version;
   5316             }
   5317         }
   5318     }
   5319 
   5320     @Override
   5321     public int checkPermission(String permName, String pkgName, int userId) {
   5322         return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
   5323     }
   5324 
   5325     @Override
   5326     public int checkUidPermission(String permName, int uid) {
   5327         synchronized (mPackages) {
   5328             final String[] packageNames = getPackagesForUid(uid);
   5329             final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
   5330                     ? mPackages.get(packageNames[0])
   5331                     : null;
   5332             return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
   5333         }
   5334     }
   5335 
   5336     @Override
   5337     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
   5338         if (UserHandle.getCallingUserId() != userId) {
   5339             mContext.enforceCallingPermission(
   5340                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   5341                     "isPermissionRevokedByPolicy for user " + userId);
   5342         }
   5343 
   5344         if (checkPermission(permission, packageName, userId)
   5345                 == PackageManager.PERMISSION_GRANTED) {
   5346             return false;
   5347         }
   5348 
   5349         final int callingUid = Binder.getCallingUid();
   5350         if (getInstantAppPackageName(callingUid) != null) {
   5351             if (!isCallerSameApp(packageName, callingUid)) {
   5352                 return false;
   5353             }
   5354         } else {
   5355             if (isInstantApp(packageName, userId)) {
   5356                 return false;
   5357             }
   5358         }
   5359 
   5360         final long identity = Binder.clearCallingIdentity();
   5361         try {
   5362             final int flags = getPermissionFlags(permission, packageName, userId);
   5363             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
   5364         } finally {
   5365             Binder.restoreCallingIdentity(identity);
   5366         }
   5367     }
   5368 
   5369     @Override
   5370     public String getPermissionControllerPackageName() {
   5371         synchronized (mPackages) {
   5372             return mRequiredInstallerPackage;
   5373         }
   5374     }
   5375 
   5376     private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
   5377         return mPermissionManager.addDynamicPermission(
   5378                 info, async, getCallingUid(), new PermissionCallback() {
   5379                     @Override
   5380                     public void onPermissionChanged() {
   5381                         if (!async) {
   5382                             mSettings.writeLPr();
   5383                         } else {
   5384                             scheduleWriteSettingsLocked();
   5385                         }
   5386                     }
   5387                 });
   5388     }
   5389 
   5390     @Override
   5391     public boolean addPermission(PermissionInfo info) {
   5392         synchronized (mPackages) {
   5393             return addDynamicPermission(info, false);
   5394         }
   5395     }
   5396 
   5397     @Override
   5398     public boolean addPermissionAsync(PermissionInfo info) {
   5399         synchronized (mPackages) {
   5400             return addDynamicPermission(info, true);
   5401         }
   5402     }
   5403 
   5404     @Override
   5405     public void removePermission(String permName) {
   5406         mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
   5407     }
   5408 
   5409     @Override
   5410     public void grantRuntimePermission(String packageName, String permName, final int userId) {
   5411         mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
   5412                 getCallingUid(), userId, mPermissionCallback);
   5413     }
   5414 
   5415     @Override
   5416     public void revokeRuntimePermission(String packageName, String permName, int userId) {
   5417         mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
   5418                 getCallingUid(), userId, mPermissionCallback);
   5419     }
   5420 
   5421     @Override
   5422     public void resetRuntimePermissions() {
   5423         mContext.enforceCallingOrSelfPermission(
   5424                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
   5425                 "revokeRuntimePermission");
   5426 
   5427         int callingUid = Binder.getCallingUid();
   5428         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
   5429             mContext.enforceCallingOrSelfPermission(
   5430                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   5431                     "resetRuntimePermissions");
   5432         }
   5433 
   5434         synchronized (mPackages) {
   5435             mPermissionManager.updateAllPermissions(
   5436                     StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
   5437                     mPermissionCallback);
   5438             for (int userId : UserManagerService.getInstance().getUserIds()) {
   5439                 final int packageCount = mPackages.size();
   5440                 for (int i = 0; i < packageCount; i++) {
   5441                     PackageParser.Package pkg = mPackages.valueAt(i);
   5442                     if (!(pkg.mExtras instanceof PackageSetting)) {
   5443                         continue;
   5444                     }
   5445                     PackageSetting ps = (PackageSetting) pkg.mExtras;
   5446                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
   5447                 }
   5448             }
   5449         }
   5450     }
   5451 
   5452     @Override
   5453     public int getPermissionFlags(String permName, String packageName, int userId) {
   5454         return mPermissionManager.getPermissionFlags(
   5455                 permName, packageName, getCallingUid(), userId);
   5456     }
   5457 
   5458     @Override
   5459     public void updatePermissionFlags(String permName, String packageName, int flagMask,
   5460             int flagValues, int userId) {
   5461         mPermissionManager.updatePermissionFlags(
   5462                 permName, packageName, flagMask, flagValues, getCallingUid(), userId,
   5463                 mPermissionCallback);
   5464     }
   5465 
   5466     /**
   5467      * Update the permission flags for all packages and runtime permissions of a user in order
   5468      * to allow device or profile owner to remove POLICY_FIXED.
   5469      */
   5470     @Override
   5471     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
   5472         synchronized (mPackages) {
   5473             final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
   5474                     flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
   5475                     mPermissionCallback);
   5476             if (changed) {
   5477                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   5478             }
   5479         }
   5480     }
   5481 
   5482     @Override
   5483     public boolean shouldShowRequestPermissionRationale(String permissionName,
   5484             String packageName, int userId) {
   5485         if (UserHandle.getCallingUserId() != userId) {
   5486             mContext.enforceCallingPermission(
   5487                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   5488                     "canShowRequestPermissionRationale for user " + userId);
   5489         }
   5490 
   5491         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
   5492         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
   5493             return false;
   5494         }
   5495 
   5496         if (checkPermission(permissionName, packageName, userId)
   5497                 == PackageManager.PERMISSION_GRANTED) {
   5498             return false;
   5499         }
   5500 
   5501         final int flags;
   5502 
   5503         final long identity = Binder.clearCallingIdentity();
   5504         try {
   5505             flags = getPermissionFlags(permissionName,
   5506                     packageName, userId);
   5507         } finally {
   5508             Binder.restoreCallingIdentity(identity);
   5509         }
   5510 
   5511         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
   5512                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
   5513                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
   5514 
   5515         if ((flags & fixedFlags) != 0) {
   5516             return false;
   5517         }
   5518 
   5519         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
   5520     }
   5521 
   5522     @Override
   5523     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
   5524         mContext.enforceCallingOrSelfPermission(
   5525                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
   5526                 "addOnPermissionsChangeListener");
   5527 
   5528         synchronized (mPackages) {
   5529             mOnPermissionChangeListeners.addListenerLocked(listener);
   5530         }
   5531     }
   5532 
   5533     @Override
   5534     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
   5535         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5536             throw new SecurityException("Instant applications don't have access to this method");
   5537         }
   5538         synchronized (mPackages) {
   5539             mOnPermissionChangeListeners.removeListenerLocked(listener);
   5540         }
   5541     }
   5542 
   5543     @Override
   5544     public boolean isProtectedBroadcast(String actionName) {
   5545         // allow instant applications
   5546         synchronized (mProtectedBroadcasts) {
   5547             if (mProtectedBroadcasts.contains(actionName)) {
   5548                 return true;
   5549             } else if (actionName != null) {
   5550                 // TODO: remove these terrible hacks
   5551                 if (actionName.startsWith("android.net.netmon.lingerExpired")
   5552                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
   5553                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
   5554                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
   5555                     return true;
   5556                 }
   5557             }
   5558         }
   5559         return false;
   5560     }
   5561 
   5562     @Override
   5563     public int checkSignatures(String pkg1, String pkg2) {
   5564         synchronized (mPackages) {
   5565             final PackageParser.Package p1 = mPackages.get(pkg1);
   5566             final PackageParser.Package p2 = mPackages.get(pkg2);
   5567             if (p1 == null || p1.mExtras == null
   5568                     || p2 == null || p2.mExtras == null) {
   5569                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5570             }
   5571             final int callingUid = Binder.getCallingUid();
   5572             final int callingUserId = UserHandle.getUserId(callingUid);
   5573             final PackageSetting ps1 = (PackageSetting) p1.mExtras;
   5574             final PackageSetting ps2 = (PackageSetting) p2.mExtras;
   5575             if (filterAppAccessLPr(ps1, callingUid, callingUserId)
   5576                     || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
   5577                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5578             }
   5579             return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
   5580         }
   5581     }
   5582 
   5583     @Override
   5584     public int checkUidSignatures(int uid1, int uid2) {
   5585         final int callingUid = Binder.getCallingUid();
   5586         final int callingUserId = UserHandle.getUserId(callingUid);
   5587         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
   5588         // Map to base uids.
   5589         uid1 = UserHandle.getAppId(uid1);
   5590         uid2 = UserHandle.getAppId(uid2);
   5591         // reader
   5592         synchronized (mPackages) {
   5593             Signature[] s1;
   5594             Signature[] s2;
   5595             Object obj = mSettings.getUserIdLPr(uid1);
   5596             if (obj != null) {
   5597                 if (obj instanceof SharedUserSetting) {
   5598                     if (isCallerInstantApp) {
   5599                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5600                     }
   5601                     s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
   5602                 } else if (obj instanceof PackageSetting) {
   5603                     final PackageSetting ps = (PackageSetting) obj;
   5604                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   5605                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5606                     }
   5607                     s1 = ps.signatures.mSigningDetails.signatures;
   5608                 } else {
   5609                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5610                 }
   5611             } else {
   5612                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5613             }
   5614             obj = mSettings.getUserIdLPr(uid2);
   5615             if (obj != null) {
   5616                 if (obj instanceof SharedUserSetting) {
   5617                     if (isCallerInstantApp) {
   5618                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5619                     }
   5620                     s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
   5621                 } else if (obj instanceof PackageSetting) {
   5622                     final PackageSetting ps = (PackageSetting) obj;
   5623                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   5624                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5625                     }
   5626                     s2 = ps.signatures.mSigningDetails.signatures;
   5627                 } else {
   5628                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5629                 }
   5630             } else {
   5631                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   5632             }
   5633             return compareSignatures(s1, s2);
   5634         }
   5635     }
   5636 
   5637     @Override
   5638     public boolean hasSigningCertificate(
   5639             String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
   5640 
   5641         synchronized (mPackages) {
   5642             final PackageParser.Package p = mPackages.get(packageName);
   5643             if (p == null || p.mExtras == null) {
   5644                 return false;
   5645             }
   5646             final int callingUid = Binder.getCallingUid();
   5647             final int callingUserId = UserHandle.getUserId(callingUid);
   5648             final PackageSetting ps = (PackageSetting) p.mExtras;
   5649             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   5650                 return false;
   5651             }
   5652             switch (type) {
   5653                 case CERT_INPUT_RAW_X509:
   5654                     return p.mSigningDetails.hasCertificate(certificate);
   5655                 case CERT_INPUT_SHA256:
   5656                     return p.mSigningDetails.hasSha256Certificate(certificate);
   5657                 default:
   5658                     return false;
   5659             }
   5660         }
   5661     }
   5662 
   5663     @Override
   5664     public boolean hasUidSigningCertificate(
   5665             int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
   5666         final int callingUid = Binder.getCallingUid();
   5667         final int callingUserId = UserHandle.getUserId(callingUid);
   5668         // Map to base uids.
   5669         uid = UserHandle.getAppId(uid);
   5670         // reader
   5671         synchronized (mPackages) {
   5672             final PackageParser.SigningDetails signingDetails;
   5673             final Object obj = mSettings.getUserIdLPr(uid);
   5674             if (obj != null) {
   5675                 if (obj instanceof SharedUserSetting) {
   5676                     final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
   5677                     if (isCallerInstantApp) {
   5678                         return false;
   5679                     }
   5680                     signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
   5681                 } else if (obj instanceof PackageSetting) {
   5682                     final PackageSetting ps = (PackageSetting) obj;
   5683                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   5684                         return false;
   5685                     }
   5686                     signingDetails = ps.signatures.mSigningDetails;
   5687                 } else {
   5688                     return false;
   5689                 }
   5690             } else {
   5691                 return false;
   5692             }
   5693             switch (type) {
   5694                 case CERT_INPUT_RAW_X509:
   5695                     return signingDetails.hasCertificate(certificate);
   5696                 case CERT_INPUT_SHA256:
   5697                     return signingDetails.hasSha256Certificate(certificate);
   5698                 default:
   5699                     return false;
   5700             }
   5701         }
   5702     }
   5703 
   5704     /**
   5705      * This method should typically only be used when granting or revoking
   5706      * permissions, since the app may immediately restart after this call.
   5707      * <p>
   5708      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
   5709      * guard your work against the app being relaunched.
   5710      */
   5711     private void killUid(int appId, int userId, String reason) {
   5712         final long identity = Binder.clearCallingIdentity();
   5713         try {
   5714             IActivityManager am = ActivityManager.getService();
   5715             if (am != null) {
   5716                 try {
   5717                     am.killUid(appId, userId, reason);
   5718                 } catch (RemoteException e) {
   5719                     /* ignore - same process */
   5720                 }
   5721             }
   5722         } finally {
   5723             Binder.restoreCallingIdentity(identity);
   5724         }
   5725     }
   5726 
   5727     /**
   5728      * If the database version for this type of package (internal storage or
   5729      * external storage) is less than the version where package signatures
   5730      * were updated, return true.
   5731      */
   5732     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
   5733         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
   5734         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
   5735     }
   5736 
   5737     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
   5738         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
   5739         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
   5740     }
   5741 
   5742     @Override
   5743     public List<String> getAllPackages() {
   5744         final int callingUid = Binder.getCallingUid();
   5745         final int callingUserId = UserHandle.getUserId(callingUid);
   5746         synchronized (mPackages) {
   5747             if (canViewInstantApps(callingUid, callingUserId)) {
   5748                 return new ArrayList<String>(mPackages.keySet());
   5749             }
   5750             final String instantAppPkgName = getInstantAppPackageName(callingUid);
   5751             final List<String> result = new ArrayList<>();
   5752             if (instantAppPkgName != null) {
   5753                 // caller is an instant application; filter unexposed applications
   5754                 for (PackageParser.Package pkg : mPackages.values()) {
   5755                     if (!pkg.visibleToInstantApps) {
   5756                         continue;
   5757                     }
   5758                     result.add(pkg.packageName);
   5759                 }
   5760             } else {
   5761                 // caller is a normal application; filter instant applications
   5762                 for (PackageParser.Package pkg : mPackages.values()) {
   5763                     final PackageSetting ps =
   5764                             pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
   5765                     if (ps != null
   5766                             && ps.getInstantApp(callingUserId)
   5767                             && !mInstantAppRegistry.isInstantAccessGranted(
   5768                                     callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
   5769                         continue;
   5770                     }
   5771                     result.add(pkg.packageName);
   5772                 }
   5773             }
   5774             return result;
   5775         }
   5776     }
   5777 
   5778     @Override
   5779     public String[] getPackagesForUid(int uid) {
   5780         final int callingUid = Binder.getCallingUid();
   5781         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
   5782         final int userId = UserHandle.getUserId(uid);
   5783         uid = UserHandle.getAppId(uid);
   5784         // reader
   5785         synchronized (mPackages) {
   5786             Object obj = mSettings.getUserIdLPr(uid);
   5787             if (obj instanceof SharedUserSetting) {
   5788                 if (isCallerInstantApp) {
   5789                     return null;
   5790                 }
   5791                 final SharedUserSetting sus = (SharedUserSetting) obj;
   5792                 final int N = sus.packages.size();
   5793                 String[] res = new String[N];
   5794                 final Iterator<PackageSetting> it = sus.packages.iterator();
   5795                 int i = 0;
   5796                 while (it.hasNext()) {
   5797                     PackageSetting ps = it.next();
   5798                     if (ps.getInstalled(userId)) {
   5799                         res[i++] = ps.name;
   5800                     } else {
   5801                         res = ArrayUtils.removeElement(String.class, res, res[i]);
   5802                     }
   5803                 }
   5804                 return res;
   5805             } else if (obj instanceof PackageSetting) {
   5806                 final PackageSetting ps = (PackageSetting) obj;
   5807                 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
   5808                     return new String[]{ps.name};
   5809                 }
   5810             }
   5811         }
   5812         return null;
   5813     }
   5814 
   5815     @Override
   5816     public String getNameForUid(int uid) {
   5817         final int callingUid = Binder.getCallingUid();
   5818         if (getInstantAppPackageName(callingUid) != null) {
   5819             return null;
   5820         }
   5821         synchronized (mPackages) {
   5822             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   5823             if (obj instanceof SharedUserSetting) {
   5824                 final SharedUserSetting sus = (SharedUserSetting) obj;
   5825                 return sus.name + ":" + sus.userId;
   5826             } else if (obj instanceof PackageSetting) {
   5827                 final PackageSetting ps = (PackageSetting) obj;
   5828                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   5829                     return null;
   5830                 }
   5831                 return ps.name;
   5832             }
   5833             return null;
   5834         }
   5835     }
   5836 
   5837     @Override
   5838     public String[] getNamesForUids(int[] uids) {
   5839         if (uids == null || uids.length == 0) {
   5840             return null;
   5841         }
   5842         final int callingUid = Binder.getCallingUid();
   5843         if (getInstantAppPackageName(callingUid) != null) {
   5844             return null;
   5845         }
   5846         final String[] names = new String[uids.length];
   5847         synchronized (mPackages) {
   5848             for (int i = uids.length - 1; i >= 0; i--) {
   5849                 final int uid = uids[i];
   5850                 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   5851                 if (obj instanceof SharedUserSetting) {
   5852                     final SharedUserSetting sus = (SharedUserSetting) obj;
   5853                     names[i] = "shared:" + sus.name;
   5854                 } else if (obj instanceof PackageSetting) {
   5855                     final PackageSetting ps = (PackageSetting) obj;
   5856                     if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   5857                         names[i] = null;
   5858                     } else {
   5859                         names[i] = ps.name;
   5860                     }
   5861                 } else {
   5862                     names[i] = null;
   5863                 }
   5864             }
   5865         }
   5866         return names;
   5867     }
   5868 
   5869     @Override
   5870     public int getUidForSharedUser(String sharedUserName) {
   5871         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5872             return -1;
   5873         }
   5874         if (sharedUserName == null) {
   5875             return -1;
   5876         }
   5877         // reader
   5878         synchronized (mPackages) {
   5879             SharedUserSetting suid;
   5880             try {
   5881                 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
   5882                 if (suid != null) {
   5883                     return suid.userId;
   5884                 }
   5885             } catch (PackageManagerException ignore) {
   5886                 // can't happen, but, still need to catch it
   5887             }
   5888             return -1;
   5889         }
   5890     }
   5891 
   5892     @Override
   5893     public int getFlagsForUid(int uid) {
   5894         final int callingUid = Binder.getCallingUid();
   5895         if (getInstantAppPackageName(callingUid) != null) {
   5896             return 0;
   5897         }
   5898         synchronized (mPackages) {
   5899             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   5900             if (obj instanceof SharedUserSetting) {
   5901                 final SharedUserSetting sus = (SharedUserSetting) obj;
   5902                 return sus.pkgFlags;
   5903             } else if (obj instanceof PackageSetting) {
   5904                 final PackageSetting ps = (PackageSetting) obj;
   5905                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   5906                     return 0;
   5907                 }
   5908                 return ps.pkgFlags;
   5909             }
   5910         }
   5911         return 0;
   5912     }
   5913 
   5914     @Override
   5915     public int getPrivateFlagsForUid(int uid) {
   5916         final int callingUid = Binder.getCallingUid();
   5917         if (getInstantAppPackageName(callingUid) != null) {
   5918             return 0;
   5919         }
   5920         synchronized (mPackages) {
   5921             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   5922             if (obj instanceof SharedUserSetting) {
   5923                 final SharedUserSetting sus = (SharedUserSetting) obj;
   5924                 return sus.pkgPrivateFlags;
   5925             } else if (obj instanceof PackageSetting) {
   5926                 final PackageSetting ps = (PackageSetting) obj;
   5927                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   5928                     return 0;
   5929                 }
   5930                 return ps.pkgPrivateFlags;
   5931             }
   5932         }
   5933         return 0;
   5934     }
   5935 
   5936     @Override
   5937     public boolean isUidPrivileged(int uid) {
   5938         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   5939             return false;
   5940         }
   5941         uid = UserHandle.getAppId(uid);
   5942         // reader
   5943         synchronized (mPackages) {
   5944             Object obj = mSettings.getUserIdLPr(uid);
   5945             if (obj instanceof SharedUserSetting) {
   5946                 final SharedUserSetting sus = (SharedUserSetting) obj;
   5947                 final Iterator<PackageSetting> it = sus.packages.iterator();
   5948                 while (it.hasNext()) {
   5949                     if (it.next().isPrivileged()) {
   5950                         return true;
   5951                     }
   5952                 }
   5953             } else if (obj instanceof PackageSetting) {
   5954                 final PackageSetting ps = (PackageSetting) obj;
   5955                 return ps.isPrivileged();
   5956             }
   5957         }
   5958         return false;
   5959     }
   5960 
   5961     @Override
   5962     public String[] getAppOpPermissionPackages(String permName) {
   5963         return mPermissionManager.getAppOpPermissionPackages(permName);
   5964     }
   5965 
   5966     @Override
   5967     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
   5968             int flags, int userId) {
   5969         return resolveIntentInternal(intent, resolvedType, flags, userId, false,
   5970                 Binder.getCallingUid());
   5971     }
   5972 
   5973     /**
   5974      * Normally instant apps can only be resolved when they're visible to the caller.
   5975      * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
   5976      * since we need to allow the system to start any installed application.
   5977      */
   5978     private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
   5979             int flags, int userId, boolean resolveForStart, int filterCallingUid) {
   5980         try {
   5981             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
   5982 
   5983             if (!sUserManager.exists(userId)) return null;
   5984             final int callingUid = Binder.getCallingUid();
   5985             flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
   5986             mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   5987                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
   5988 
   5989             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
   5990             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
   5991                     flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
   5992             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   5993 
   5994             final ResolveInfo bestChoice =
   5995                     chooseBestActivity(intent, resolvedType, flags, query, userId);
   5996             return bestChoice;
   5997         } finally {
   5998             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   5999         }
   6000     }
   6001 
   6002     @Override
   6003     public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
   6004         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
   6005             throw new SecurityException(
   6006                     "findPersistentPreferredActivity can only be run by the system");
   6007         }
   6008         if (!sUserManager.exists(userId)) {
   6009             return null;
   6010         }
   6011         final int callingUid = Binder.getCallingUid();
   6012         intent = updateIntentForResolve(intent);
   6013         final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
   6014         final int flags = updateFlagsForResolve(
   6015                 0, userId, intent, callingUid, false /*includeInstantApps*/);
   6016         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
   6017                 userId);
   6018         synchronized (mPackages) {
   6019             return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
   6020                     userId);
   6021         }
   6022     }
   6023 
   6024     @Override
   6025     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
   6026             IntentFilter filter, int match, ComponentName activity) {
   6027         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6028             return;
   6029         }
   6030         final int userId = UserHandle.getCallingUserId();
   6031         if (DEBUG_PREFERRED) {
   6032             Log.v(TAG, "setLastChosenActivity intent=" + intent
   6033                 + " resolvedType=" + resolvedType
   6034                 + " flags=" + flags
   6035                 + " filter=" + filter
   6036                 + " match=" + match
   6037                 + " activity=" + activity);
   6038             filter.dump(new PrintStreamPrinter(System.out), "    ");
   6039         }
   6040         intent.setComponent(null);
   6041         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
   6042                 userId);
   6043         // Find any earlier preferred or last chosen entries and nuke them
   6044         findPreferredActivity(intent, resolvedType,
   6045                 flags, query, 0, false, true, false, userId);
   6046         // Add the new activity as the last chosen for this filter
   6047         addPreferredActivityInternal(filter, match, null, activity, false, userId,
   6048                 "Setting last chosen");
   6049     }
   6050 
   6051     @Override
   6052     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
   6053         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   6054             return null;
   6055         }
   6056         final int userId = UserHandle.getCallingUserId();
   6057         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
   6058         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
   6059                 userId);
   6060         return findPreferredActivity(intent, resolvedType, flags, query, 0,
   6061                 false, false, false, userId);
   6062     }
   6063 
   6064     /**
   6065      * Returns whether or not instant apps have been disabled remotely.
   6066      */
   6067     private boolean areWebInstantAppsDisabled() {
   6068         return mWebInstantAppsDisabled;
   6069     }
   6070 
   6071     private boolean isInstantAppResolutionAllowed(
   6072             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
   6073             boolean skipPackageCheck) {
   6074         if (mInstantAppResolverConnection == null) {
   6075             return false;
   6076         }
   6077         if (mInstantAppInstallerActivity == null) {
   6078             return false;
   6079         }
   6080         if (intent.getComponent() != null) {
   6081             return false;
   6082         }
   6083         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
   6084             return false;
   6085         }
   6086         if (!skipPackageCheck && intent.getPackage() != null) {
   6087             return false;
   6088         }
   6089         if (!intent.isWebIntent()) {
   6090             // for non web intents, we should not resolve externally if an app already exists to
   6091             // handle it or if the caller didn't explicitly request it.
   6092             if ((resolvedActivities != null && resolvedActivities.size() != 0)
   6093                     || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
   6094                 return false;
   6095             }
   6096         } else {
   6097             if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
   6098                 return false;
   6099             } else if (areWebInstantAppsDisabled()) {
   6100                 return false;
   6101             }
   6102         }
   6103         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
   6104         // Or if there's already an ephemeral app installed that handles the action
   6105         synchronized (mPackages) {
   6106             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
   6107             for (int n = 0; n < count; n++) {
   6108                 final ResolveInfo info = resolvedActivities.get(n);
   6109                 final String packageName = info.activityInfo.packageName;
   6110                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   6111                 if (ps != null) {
   6112                     // only check domain verification status if the app is not a browser
   6113                     if (!info.handleAllWebDataURI) {
   6114                         // Try to get the status from User settings first
   6115                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   6116                         final int status = (int) (packedStatus >> 32);
   6117                         if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
   6118                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
   6119                             if (DEBUG_INSTANT) {
   6120                                 Slog.v(TAG, "DENY instant app;"
   6121                                     + " pkg: " + packageName + ", status: " + status);
   6122                             }
   6123                             return false;
   6124                         }
   6125                     }
   6126                     if (ps.getInstantApp(userId)) {
   6127                         if (DEBUG_INSTANT) {
   6128                             Slog.v(TAG, "DENY instant app installed;"
   6129                                     + " pkg: " + packageName);
   6130                         }
   6131                         return false;
   6132                     }
   6133                 }
   6134             }
   6135         }
   6136         // We've exhausted all ways to deny ephemeral application; let the system look for them.
   6137         return true;
   6138     }
   6139 
   6140     private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
   6141             Intent origIntent, String resolvedType, String callingPackage,
   6142             Bundle verificationBundle, int userId) {
   6143         final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
   6144                 new InstantAppRequest(responseObj, origIntent, resolvedType,
   6145                         callingPackage, userId, verificationBundle, false /*resolveForStart*/));
   6146         mHandler.sendMessage(msg);
   6147     }
   6148 
   6149     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
   6150             int flags, List<ResolveInfo> query, int userId) {
   6151         if (query != null) {
   6152             final int N = query.size();
   6153             if (N == 1) {
   6154                 return query.get(0);
   6155             } else if (N > 1) {
   6156                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
   6157                 // If there is more than one activity with the same priority,
   6158                 // then let the user decide between them.
   6159                 ResolveInfo r0 = query.get(0);
   6160                 ResolveInfo r1 = query.get(1);
   6161                 if (DEBUG_INTENT_MATCHING || debug) {
   6162                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
   6163                             + r1.activityInfo.name + "=" + r1.priority);
   6164                 }
   6165                 // If the first activity has a higher priority, or a different
   6166                 // default, then it is always desirable to pick it.
   6167                 if (r0.priority != r1.priority
   6168                         || r0.preferredOrder != r1.preferredOrder
   6169                         || r0.isDefault != r1.isDefault) {
   6170                     return query.get(0);
   6171                 }
   6172                 // If we have saved a preference for a preferred activity for
   6173                 // this Intent, use that.
   6174                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
   6175                         flags, query, r0.priority, true, false, debug, userId);
   6176                 if (ri != null) {
   6177                     return ri;
   6178                 }
   6179                 // If we have an ephemeral app, use it
   6180                 for (int i = 0; i < N; i++) {
   6181                     ri = query.get(i);
   6182                     if (ri.activityInfo.applicationInfo.isInstantApp()) {
   6183                         final String packageName = ri.activityInfo.packageName;
   6184                         final PackageSetting ps = mSettings.mPackages.get(packageName);
   6185                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   6186                         final int status = (int)(packedStatus >> 32);
   6187                         if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
   6188                             return ri;
   6189                         }
   6190                     }
   6191                 }
   6192                 ri = new ResolveInfo(mResolveInfo);
   6193                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
   6194                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
   6195                 // If all of the options come from the same package, show the application's
   6196                 // label and icon instead of the generic resolver's.
   6197                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
   6198                 // and then throw away the ResolveInfo itself, meaning that the caller loses
   6199                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
   6200                 // a fallback for this case; we only set the target package's resources on
   6201                 // the ResolveInfo, not the ActivityInfo.
   6202                 final String intentPackage = intent.getPackage();
   6203                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
   6204                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
   6205                     ri.resolvePackageName = intentPackage;
   6206                     if (userNeedsBadging(userId)) {
   6207                         ri.noResourceId = true;
   6208                     } else {
   6209                         ri.icon = appi.icon;
   6210                     }
   6211                     ri.iconResourceId = appi.icon;
   6212                     ri.labelRes = appi.labelRes;
   6213                 }
   6214                 ri.activityInfo.applicationInfo = new ApplicationInfo(
   6215                         ri.activityInfo.applicationInfo);
   6216                 if (userId != 0) {
   6217                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
   6218                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
   6219                 }
   6220                 // Make sure that the resolver is displayable in car mode
   6221                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
   6222                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
   6223                 return ri;
   6224             }
   6225         }
   6226         return null;
   6227     }
   6228 
   6229     /**
   6230      * Return true if the given list is not empty and all of its contents have
   6231      * an activityInfo with the given package name.
   6232      */
   6233     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
   6234         if (ArrayUtils.isEmpty(list)) {
   6235             return false;
   6236         }
   6237         for (int i = 0, N = list.size(); i < N; i++) {
   6238             final ResolveInfo ri = list.get(i);
   6239             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
   6240             if (ai == null || !packageName.equals(ai.packageName)) {
   6241                 return false;
   6242             }
   6243         }
   6244         return true;
   6245     }
   6246 
   6247     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
   6248             int flags, List<ResolveInfo> query, boolean debug, int userId) {
   6249         final int N = query.size();
   6250         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
   6251                 .get(userId);
   6252         // Get the list of persistent preferred activities that handle the intent
   6253         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
   6254         List<PersistentPreferredActivity> pprefs = ppir != null
   6255                 ? ppir.queryIntent(intent, resolvedType,
   6256                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   6257                         userId)
   6258                 : null;
   6259         if (pprefs != null && pprefs.size() > 0) {
   6260             final int M = pprefs.size();
   6261             for (int i=0; i<M; i++) {
   6262                 final PersistentPreferredActivity ppa = pprefs.get(i);
   6263                 if (DEBUG_PREFERRED || debug) {
   6264                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
   6265                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
   6266                             + "\n  component=" + ppa.mComponent);
   6267                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   6268                 }
   6269                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
   6270                         flags | MATCH_DISABLED_COMPONENTS, userId);
   6271                 if (DEBUG_PREFERRED || debug) {
   6272                     Slog.v(TAG, "Found persistent preferred activity:");
   6273                     if (ai != null) {
   6274                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   6275                     } else {
   6276                         Slog.v(TAG, "  null");
   6277                     }
   6278                 }
   6279                 if (ai == null) {
   6280                     // This previously registered persistent preferred activity
   6281                     // component is no longer known. Ignore it and do NOT remove it.
   6282                     continue;
   6283                 }
   6284                 for (int j=0; j<N; j++) {
   6285                     final ResolveInfo ri = query.get(j);
   6286                     if (!ri.activityInfo.applicationInfo.packageName
   6287                             .equals(ai.applicationInfo.packageName)) {
   6288                         continue;
   6289                     }
   6290                     if (!ri.activityInfo.name.equals(ai.name)) {
   6291                         continue;
   6292                     }
   6293                     //  Found a persistent preference that can handle the intent.
   6294                     if (DEBUG_PREFERRED || debug) {
   6295                         Slog.v(TAG, "Returning persistent preferred activity: " +
   6296                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
   6297                     }
   6298                     return ri;
   6299                 }
   6300             }
   6301         }
   6302         return null;
   6303     }
   6304 
   6305     // TODO: handle preferred activities missing while user has amnesia
   6306     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
   6307             List<ResolveInfo> query, int priority, boolean always,
   6308             boolean removeMatches, boolean debug, int userId) {
   6309         if (!sUserManager.exists(userId)) return null;
   6310         final int callingUid = Binder.getCallingUid();
   6311         flags = updateFlagsForResolve(
   6312                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
   6313         intent = updateIntentForResolve(intent);
   6314         // writer
   6315         synchronized (mPackages) {
   6316             // Try to find a matching persistent preferred activity.
   6317             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
   6318                     debug, userId);
   6319 
   6320             // If a persistent preferred activity matched, use it.
   6321             if (pri != null) {
   6322                 return pri;
   6323             }
   6324 
   6325             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   6326             // Get the list of preferred activities that handle the intent
   6327             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
   6328             List<PreferredActivity> prefs = pir != null
   6329                     ? pir.queryIntent(intent, resolvedType,
   6330                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   6331                             userId)
   6332                     : null;
   6333             if (prefs != null && prefs.size() > 0) {
   6334                 boolean changed = false;
   6335                 try {
   6336                     // First figure out how good the original match set is.
   6337                     // We will only allow preferred activities that came
   6338                     // from the same match quality.
   6339                     int match = 0;
   6340 
   6341                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
   6342 
   6343                     final int N = query.size();
   6344                     for (int j=0; j<N; j++) {
   6345                         final ResolveInfo ri = query.get(j);
   6346                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
   6347                                 + ": 0x" + Integer.toHexString(match));
   6348                         if (ri.match > match) {
   6349                             match = ri.match;
   6350                         }
   6351                     }
   6352 
   6353                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
   6354                             + Integer.toHexString(match));
   6355 
   6356                     match &= IntentFilter.MATCH_CATEGORY_MASK;
   6357                     final int M = prefs.size();
   6358                     for (int i=0; i<M; i++) {
   6359                         final PreferredActivity pa = prefs.get(i);
   6360                         if (DEBUG_PREFERRED || debug) {
   6361                             Slog.v(TAG, "Checking PreferredActivity ds="
   6362                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
   6363                                     + "\n  component=" + pa.mPref.mComponent);
   6364                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   6365                         }
   6366                         if (pa.mPref.mMatch != match) {
   6367                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
   6368                                     + Integer.toHexString(pa.mPref.mMatch));
   6369                             continue;
   6370                         }
   6371                         // If it's not an "always" type preferred activity and that's what we're
   6372                         // looking for, skip it.
   6373                         if (always && !pa.mPref.mAlways) {
   6374                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
   6375                             continue;
   6376                         }
   6377                         final ActivityInfo ai = getActivityInfo(
   6378                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
   6379                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
   6380                                 userId);
   6381                         if (DEBUG_PREFERRED || debug) {
   6382                             Slog.v(TAG, "Found preferred activity:");
   6383                             if (ai != null) {
   6384                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   6385                             } else {
   6386                                 Slog.v(TAG, "  null");
   6387                             }
   6388                         }
   6389                         if (ai == null) {
   6390                             // This previously registered preferred activity
   6391                             // component is no longer known.  Most likely an update
   6392                             // to the app was installed and in the new version this
   6393                             // component no longer exists.  Clean it up by removing
   6394                             // it from the preferred activities list, and skip it.
   6395                             Slog.w(TAG, "Removing dangling preferred activity: "
   6396                                     + pa.mPref.mComponent);
   6397                             pir.removeFilter(pa);
   6398                             changed = true;
   6399                             continue;
   6400                         }
   6401                         for (int j=0; j<N; j++) {
   6402                             final ResolveInfo ri = query.get(j);
   6403                             if (!ri.activityInfo.applicationInfo.packageName
   6404                                     .equals(ai.applicationInfo.packageName)) {
   6405                                 continue;
   6406                             }
   6407                             if (!ri.activityInfo.name.equals(ai.name)) {
   6408                                 continue;
   6409                             }
   6410 
   6411                             if (removeMatches) {
   6412                                 pir.removeFilter(pa);
   6413                                 changed = true;
   6414                                 if (DEBUG_PREFERRED) {
   6415                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
   6416                                 }
   6417                                 break;
   6418                             }
   6419 
   6420                             // Okay we found a previously set preferred or last chosen app.
   6421                             // If the result set is different from when this
   6422                             // was created, and is not a subset of the preferred set, we need to
   6423                             // clear it and re-ask the user their preference, if we're looking for
   6424                             // an "always" type entry.
   6425                             if (always && !pa.mPref.sameSet(query)) {
   6426                                 if (pa.mPref.isSuperset(query)) {
   6427                                     // some components of the set are no longer present in
   6428                                     // the query, but the preferred activity can still be reused
   6429                                     if (DEBUG_PREFERRED) {
   6430                                         Slog.i(TAG, "Result set changed, but PreferredActivity is"
   6431                                                 + " still valid as only non-preferred components"
   6432                                                 + " were removed for " + intent + " type "
   6433                                                 + resolvedType);
   6434                                     }
   6435                                     // remove obsolete components and re-add the up-to-date filter
   6436                                     PreferredActivity freshPa = new PreferredActivity(pa,
   6437                                             pa.mPref.mMatch,
   6438                                             pa.mPref.discardObsoleteComponents(query),
   6439                                             pa.mPref.mComponent,
   6440                                             pa.mPref.mAlways);
   6441                                     pir.removeFilter(pa);
   6442                                     pir.addFilter(freshPa);
   6443                                     changed = true;
   6444                                 } else {
   6445                                     Slog.i(TAG,
   6446                                             "Result set changed, dropping preferred activity for "
   6447                                                     + intent + " type " + resolvedType);
   6448                                     if (DEBUG_PREFERRED) {
   6449                                         Slog.v(TAG, "Removing preferred activity since set changed "
   6450                                                 + pa.mPref.mComponent);
   6451                                     }
   6452                                     pir.removeFilter(pa);
   6453                                     // Re-add the filter as a "last chosen" entry (!always)
   6454                                     PreferredActivity lastChosen = new PreferredActivity(
   6455                                             pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
   6456                                     pir.addFilter(lastChosen);
   6457                                     changed = true;
   6458                                     return null;
   6459                                 }
   6460                             }
   6461 
   6462                             // Yay! Either the set matched or we're looking for the last chosen
   6463                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
   6464                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
   6465                             return ri;
   6466                         }
   6467                     }
   6468                 } finally {
   6469                     if (changed) {
   6470                         if (DEBUG_PREFERRED) {
   6471                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
   6472                         }
   6473                         scheduleWritePackageRestrictionsLocked(userId);
   6474                     }
   6475                 }
   6476             }
   6477         }
   6478         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
   6479         return null;
   6480     }
   6481 
   6482     /*
   6483      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
   6484      */
   6485     @Override
   6486     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
   6487             int targetUserId) {
   6488         mContext.enforceCallingOrSelfPermission(
   6489                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   6490         List<CrossProfileIntentFilter> matches =
   6491                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
   6492         if (matches != null) {
   6493             int size = matches.size();
   6494             for (int i = 0; i < size; i++) {
   6495                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
   6496             }
   6497         }
   6498         if (intent.hasWebURI()) {
   6499             // cross-profile app linking works only towards the parent.
   6500             final int callingUid = Binder.getCallingUid();
   6501             final UserInfo parent = getProfileParent(sourceUserId);
   6502             synchronized(mPackages) {
   6503                 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
   6504                         false /*includeInstantApps*/);
   6505                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
   6506                         intent, resolvedType, flags, sourceUserId, parent.id);
   6507                 return xpDomainInfo != null;
   6508             }
   6509         }
   6510         return false;
   6511     }
   6512 
   6513     private UserInfo getProfileParent(int userId) {
   6514         final long identity = Binder.clearCallingIdentity();
   6515         try {
   6516             return sUserManager.getProfileParent(userId);
   6517         } finally {
   6518             Binder.restoreCallingIdentity(identity);
   6519         }
   6520     }
   6521 
   6522     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
   6523             String resolvedType, int userId) {
   6524         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
   6525         if (resolver != null) {
   6526             return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
   6527         }
   6528         return null;
   6529     }
   6530 
   6531     @Override
   6532     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
   6533             String resolvedType, int flags, int userId) {
   6534         try {
   6535             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
   6536 
   6537             return new ParceledListSlice<>(
   6538                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
   6539         } finally {
   6540             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   6541         }
   6542     }
   6543 
   6544     /**
   6545      * Returns the package name of the calling Uid if it's an instant app. If it isn't
   6546      * instant, returns {@code null}.
   6547      */
   6548     private String getInstantAppPackageName(int callingUid) {
   6549         synchronized (mPackages) {
   6550             // If the caller is an isolated app use the owner's uid for the lookup.
   6551             if (Process.isIsolated(callingUid)) {
   6552                 callingUid = mIsolatedOwners.get(callingUid);
   6553             }
   6554             final int appId = UserHandle.getAppId(callingUid);
   6555             final Object obj = mSettings.getUserIdLPr(appId);
   6556             if (obj instanceof PackageSetting) {
   6557                 final PackageSetting ps = (PackageSetting) obj;
   6558                 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
   6559                 return isInstantApp ? ps.pkg.packageName : null;
   6560             }
   6561         }
   6562         return null;
   6563     }
   6564 
   6565     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
   6566             String resolvedType, int flags, int userId) {
   6567         return queryIntentActivitiesInternal(
   6568                 intent, resolvedType, flags, Binder.getCallingUid(), userId,
   6569                 false /*resolveForStart*/, true /*allowDynamicSplits*/);
   6570     }
   6571 
   6572     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
   6573             String resolvedType, int flags, int filterCallingUid, int userId,
   6574             boolean resolveForStart, boolean allowDynamicSplits) {
   6575         if (!sUserManager.exists(userId)) return Collections.emptyList();
   6576         final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
   6577         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   6578                 false /* requireFullPermission */, false /* checkShell */,
   6579                 "query intent activities");
   6580         final String pkgName = intent.getPackage();
   6581         ComponentName comp = intent.getComponent();
   6582         if (comp == null) {
   6583             if (intent.getSelector() != null) {
   6584                 intent = intent.getSelector();
   6585                 comp = intent.getComponent();
   6586             }
   6587         }
   6588 
   6589         flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
   6590                 comp != null || pkgName != null /*onlyExposedExplicitly*/);
   6591         if (comp != null) {
   6592             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   6593             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
   6594             if (ai != null) {
   6595                 // When specifying an explicit component, we prevent the activity from being
   6596                 // used when either 1) the calling package is normal and the activity is within
   6597                 // an ephemeral application or 2) the calling package is ephemeral and the
   6598                 // activity is not visible to ephemeral applications.
   6599                 final boolean matchInstantApp =
   6600                         (flags & PackageManager.MATCH_INSTANT) != 0;
   6601                 final boolean matchVisibleToInstantAppOnly =
   6602                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   6603                 final boolean matchExplicitlyVisibleOnly =
   6604                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
   6605                 final boolean isCallerInstantApp =
   6606                         instantAppPkgName != null;
   6607                 final boolean isTargetSameInstantApp =
   6608                         comp.getPackageName().equals(instantAppPkgName);
   6609                 final boolean isTargetInstantApp =
   6610                         (ai.applicationInfo.privateFlags
   6611                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   6612                 final boolean isTargetVisibleToInstantApp =
   6613                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
   6614                 final boolean isTargetExplicitlyVisibleToInstantApp =
   6615                         isTargetVisibleToInstantApp
   6616                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
   6617                 final boolean isTargetHiddenFromInstantApp =
   6618                         !isTargetVisibleToInstantApp
   6619                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
   6620                 final boolean blockResolution =
   6621                         !isTargetSameInstantApp
   6622                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   6623                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   6624                                         && isTargetHiddenFromInstantApp));
   6625                 if (!blockResolution) {
   6626                     final ResolveInfo ri = new ResolveInfo();
   6627                     ri.activityInfo = ai;
   6628                     list.add(ri);
   6629                 }
   6630             }
   6631             return applyPostResolutionFilter(
   6632                     list, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart,
   6633                     userId, intent);
   6634         }
   6635 
   6636         // reader
   6637         boolean sortResult = false;
   6638         boolean addInstant = false;
   6639         List<ResolveInfo> result;
   6640         synchronized (mPackages) {
   6641             if (pkgName == null) {
   6642                 List<CrossProfileIntentFilter> matchingFilters =
   6643                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
   6644                 // Check for results that need to skip the current profile.
   6645                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
   6646                         resolvedType, flags, userId);
   6647                 if (xpResolveInfo != null) {
   6648                     List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
   6649                     xpResult.add(xpResolveInfo);
   6650                     return applyPostResolutionFilter(
   6651                             filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
   6652                             allowDynamicSplits, filterCallingUid, resolveForStart, userId, intent);
   6653                 }
   6654 
   6655                 // Check for results in the current profile.
   6656                 result = filterIfNotSystemUser(mActivities.queryIntent(
   6657                         intent, resolvedType, flags, userId), userId);
   6658                 addInstant = isInstantAppResolutionAllowed(intent, result, userId,
   6659                         false /*skipPackageCheck*/);
   6660                 // Check for cross profile results.
   6661                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
   6662                 xpResolveInfo = queryCrossProfileIntents(
   6663                         matchingFilters, intent, resolvedType, flags, userId,
   6664                         hasNonNegativePriorityResult);
   6665                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
   6666                     boolean isVisibleToUser = filterIfNotSystemUser(
   6667                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
   6668                     if (isVisibleToUser) {
   6669                         result.add(xpResolveInfo);
   6670                         sortResult = true;
   6671                     }
   6672                 }
   6673                 if (intent.hasWebURI()) {
   6674                     CrossProfileDomainInfo xpDomainInfo = null;
   6675                     final UserInfo parent = getProfileParent(userId);
   6676                     if (parent != null) {
   6677                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
   6678                                 flags, userId, parent.id);
   6679                     }
   6680                     if (xpDomainInfo != null) {
   6681                         if (xpResolveInfo != null) {
   6682                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
   6683                             // in the result.
   6684                             result.remove(xpResolveInfo);
   6685                         }
   6686                         if (result.size() == 0 && !addInstant) {
   6687                             // No result in current profile, but found candidate in parent user.
   6688                             // And we are not going to add emphemeral app, so we can return the
   6689                             // result straight away.
   6690                             result.add(xpDomainInfo.resolveInfo);
   6691                             return applyPostResolutionFilter(result, instantAppPkgName,
   6692                                     allowDynamicSplits, filterCallingUid, resolveForStart, userId,
   6693                                     intent);
   6694                         }
   6695                     } else if (result.size() <= 1 && !addInstant) {
   6696                         // No result in parent user and <= 1 result in current profile, and we
   6697                         // are not going to add emphemeral app, so we can return the result without
   6698                         // further processing.
   6699                         return applyPostResolutionFilter(result, instantAppPkgName,
   6700                                 allowDynamicSplits, filterCallingUid, resolveForStart, userId,
   6701                                 intent);
   6702                     }
   6703                     // We have more than one candidate (combining results from current and parent
   6704                     // profile), so we need filtering and sorting.
   6705                     result = filterCandidatesWithDomainPreferredActivitiesLPr(
   6706                             intent, flags, result, xpDomainInfo, userId);
   6707                     sortResult = true;
   6708                 }
   6709             } else {
   6710                 final PackageParser.Package pkg = mPackages.get(pkgName);
   6711                 result = null;
   6712                 if (pkg != null) {
   6713                     result = filterIfNotSystemUser(
   6714                             mActivities.queryIntentForPackage(
   6715                                     intent, resolvedType, flags, pkg.activities, userId),
   6716                             userId);
   6717                 }
   6718                 if (result == null || result.size() == 0) {
   6719                     // the caller wants to resolve for a particular package; however, there
   6720                     // were no installed results, so, try to find an ephemeral result
   6721                     addInstant = isInstantAppResolutionAllowed(
   6722                                     intent, null /*result*/, userId, true /*skipPackageCheck*/);
   6723                     if (result == null) {
   6724                         result = new ArrayList<>();
   6725                     }
   6726                 }
   6727             }
   6728         }
   6729         if (addInstant) {
   6730             result = maybeAddInstantAppInstaller(
   6731                     result, intent, resolvedType, flags, userId, resolveForStart);
   6732         }
   6733         if (sortResult) {
   6734             Collections.sort(result, mResolvePrioritySorter);
   6735         }
   6736         return applyPostResolutionFilter(
   6737                 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart,
   6738                 userId, intent);
   6739     }
   6740 
   6741     private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
   6742             String resolvedType, int flags, int userId, boolean resolveForStart) {
   6743         // first, check to see if we've got an instant app already installed
   6744         final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
   6745         ResolveInfo localInstantApp = null;
   6746         boolean blockResolution = false;
   6747         if (!alreadyResolvedLocally) {
   6748             final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
   6749                     flags
   6750                         | PackageManager.GET_RESOLVED_FILTER
   6751                         | PackageManager.MATCH_INSTANT
   6752                         | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
   6753                     userId);
   6754             for (int i = instantApps.size() - 1; i >= 0; --i) {
   6755                 final ResolveInfo info = instantApps.get(i);
   6756                 final String packageName = info.activityInfo.packageName;
   6757                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   6758                 if (ps.getInstantApp(userId)) {
   6759                     final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   6760                     final int status = (int)(packedStatus >> 32);
   6761                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   6762                         // there's a local instant application installed, but, the user has
   6763                         // chosen to never use it; skip resolution and don't acknowledge
   6764                         // an instant application is even available
   6765                         if (DEBUG_INSTANT) {
   6766                             Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
   6767                         }
   6768                         blockResolution = true;
   6769                         break;
   6770                     } else {
   6771                         // we have a locally installed instant application; skip resolution
   6772                         // but acknowledge there's an instant application available
   6773                         if (DEBUG_INSTANT) {
   6774                             Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
   6775                         }
   6776                         localInstantApp = info;
   6777                         break;
   6778                     }
   6779                 }
   6780             }
   6781         }
   6782         // no app installed, let's see if one's available
   6783         AuxiliaryResolveInfo auxiliaryResponse = null;
   6784         if (!blockResolution) {
   6785             if (localInstantApp == null) {
   6786                 // we don't have an instant app locally, resolve externally
   6787                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
   6788                 final InstantAppRequest requestObject = new InstantAppRequest(
   6789                         null /*responseObj*/, intent /*origIntent*/, resolvedType,
   6790                         null /*callingPackage*/, userId, null /*verificationBundle*/,
   6791                         resolveForStart);
   6792                 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
   6793                         mInstantAppResolverConnection, requestObject);
   6794                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   6795             } else {
   6796                 // we have an instant application locally, but, we can't admit that since
   6797                 // callers shouldn't be able to determine prior browsing. create a dummy
   6798                 // auxiliary response so the downstream code behaves as if there's an
   6799                 // instant application available externally. when it comes time to start
   6800                 // the instant application, we'll do the right thing.
   6801                 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
   6802                 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
   6803                                         ai.packageName, ai.longVersionCode, null /* splitName */);
   6804             }
   6805         }
   6806         if (intent.isWebIntent() && auxiliaryResponse == null) {
   6807             return result;
   6808         }
   6809         final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
   6810         if (ps == null
   6811                 || ps.getUserState().get(userId) == null
   6812                 || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
   6813             return result;
   6814         }
   6815         final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
   6816         ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
   6817                 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
   6818         ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
   6819                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
   6820         // add a non-generic filter
   6821         ephemeralInstaller.filter = new IntentFilter();
   6822         if (intent.getAction() != null) {
   6823             ephemeralInstaller.filter.addAction(intent.getAction());
   6824         }
   6825         if (intent.getData() != null && intent.getData().getPath() != null) {
   6826             ephemeralInstaller.filter.addDataPath(
   6827                     intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
   6828         }
   6829         ephemeralInstaller.isInstantAppAvailable = true;
   6830         // make sure this resolver is the default
   6831         ephemeralInstaller.isDefault = true;
   6832         ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
   6833         if (DEBUG_INSTANT) {
   6834             Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
   6835         }
   6836 
   6837         result.add(ephemeralInstaller);
   6838         return result;
   6839     }
   6840 
   6841     private static class CrossProfileDomainInfo {
   6842         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
   6843         ResolveInfo resolveInfo;
   6844         /* Best domain verification status of the activities found in the other profile */
   6845         int bestDomainVerificationStatus;
   6846     }
   6847 
   6848     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
   6849             String resolvedType, int flags, int sourceUserId, int parentUserId) {
   6850         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
   6851                 sourceUserId)) {
   6852             return null;
   6853         }
   6854         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
   6855                 resolvedType, flags, parentUserId);
   6856 
   6857         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
   6858             return null;
   6859         }
   6860         CrossProfileDomainInfo result = null;
   6861         int size = resultTargetUser.size();
   6862         for (int i = 0; i < size; i++) {
   6863             ResolveInfo riTargetUser = resultTargetUser.get(i);
   6864             // Intent filter verification is only for filters that specify a host. So don't return
   6865             // those that handle all web uris.
   6866             if (riTargetUser.handleAllWebDataURI) {
   6867                 continue;
   6868             }
   6869             String packageName = riTargetUser.activityInfo.packageName;
   6870             PackageSetting ps = mSettings.mPackages.get(packageName);
   6871             if (ps == null) {
   6872                 continue;
   6873             }
   6874             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
   6875             int status = (int)(verificationState >> 32);
   6876             if (result == null) {
   6877                 result = new CrossProfileDomainInfo();
   6878                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
   6879                         sourceUserId, parentUserId);
   6880                 result.bestDomainVerificationStatus = status;
   6881             } else {
   6882                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
   6883                         result.bestDomainVerificationStatus);
   6884             }
   6885         }
   6886         // Don't consider matches with status NEVER across profiles.
   6887         if (result != null && result.bestDomainVerificationStatus
   6888                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   6889             return null;
   6890         }
   6891         return result;
   6892     }
   6893 
   6894     /**
   6895      * Verification statuses are ordered from the worse to the best, except for
   6896      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
   6897      */
   6898     private int bestDomainVerificationStatus(int status1, int status2) {
   6899         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   6900             return status2;
   6901         }
   6902         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   6903             return status1;
   6904         }
   6905         return (int) MathUtils.max(status1, status2);
   6906     }
   6907 
   6908     private boolean isUserEnabled(int userId) {
   6909         long callingId = Binder.clearCallingIdentity();
   6910         try {
   6911             UserInfo userInfo = sUserManager.getUserInfo(userId);
   6912             return userInfo != null && userInfo.isEnabled();
   6913         } finally {
   6914             Binder.restoreCallingIdentity(callingId);
   6915         }
   6916     }
   6917 
   6918     /**
   6919      * Filter out activities with systemUserOnly flag set, when current user is not System.
   6920      *
   6921      * @return filtered list
   6922      */
   6923     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
   6924         if (userId == UserHandle.USER_SYSTEM) {
   6925             return resolveInfos;
   6926         }
   6927         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   6928             ResolveInfo info = resolveInfos.get(i);
   6929             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
   6930                 resolveInfos.remove(i);
   6931             }
   6932         }
   6933         return resolveInfos;
   6934     }
   6935 
   6936     /**
   6937      * Filters out ephemeral activities.
   6938      * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
   6939      * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
   6940      *
   6941      * @param resolveInfos The pre-filtered list of resolved activities
   6942      * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
   6943      *          is performed.
   6944      * @param intent
   6945      * @return A filtered list of resolved activities.
   6946      */
   6947     private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
   6948             String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid,
   6949             boolean resolveForStart, int userId, Intent intent) {
   6950         final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
   6951         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   6952             final ResolveInfo info = resolveInfos.get(i);
   6953             // remove locally resolved instant app web results when disabled
   6954             if (info.isInstantAppAvailable && blockInstant) {
   6955                 resolveInfos.remove(i);
   6956                 continue;
   6957             }
   6958             // allow activities that are defined in the provided package
   6959             if (allowDynamicSplits
   6960                     && info.activityInfo != null
   6961                     && info.activityInfo.splitName != null
   6962                     && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
   6963                             info.activityInfo.splitName)) {
   6964                 if (mInstantAppInstallerActivity == null) {
   6965                     if (DEBUG_INSTALL) {
   6966                         Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
   6967                     }
   6968                     resolveInfos.remove(i);
   6969                     continue;
   6970                 }
   6971                 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
   6972                     resolveInfos.remove(i);
   6973                     continue;
   6974                 }
   6975                 // requested activity is defined in a split that hasn't been installed yet.
   6976                 // add the installer to the resolve list
   6977                 if (DEBUG_INSTALL) {
   6978                     Slog.v(TAG, "Adding installer to the ResolveInfo list");
   6979                 }
   6980                 final ResolveInfo installerInfo = new ResolveInfo(
   6981                         mInstantAppInstallerInfo);
   6982                 final ComponentName installFailureActivity = findInstallFailureActivity(
   6983                         info.activityInfo.packageName,  filterCallingUid, userId);
   6984                 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
   6985                         installFailureActivity,
   6986                         info.activityInfo.packageName,
   6987                         info.activityInfo.applicationInfo.longVersionCode,
   6988                         info.activityInfo.splitName);
   6989                 // add a non-generic filter
   6990                 installerInfo.filter = new IntentFilter();
   6991 
   6992                 // This resolve info may appear in the chooser UI, so let us make it
   6993                 // look as the one it replaces as far as the user is concerned which
   6994                 // requires loading the correct label and icon for the resolve info.
   6995                 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
   6996                 installerInfo.labelRes = info.resolveLabelResId();
   6997                 installerInfo.icon = info.resolveIconResId();
   6998                 installerInfo.isInstantAppAvailable = true;
   6999                 resolveInfos.set(i, installerInfo);
   7000                 continue;
   7001             }
   7002             // caller is a full app, don't need to apply any other filtering
   7003             if (ephemeralPkgName == null) {
   7004                 continue;
   7005             } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
   7006                 // caller is same app; don't need to apply any other filtering
   7007                 continue;
   7008             } else if (resolveForStart
   7009                     && (intent.isWebIntent()
   7010                             || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0)
   7011                     && intent.getPackage() == null
   7012                     && intent.getComponent() == null) {
   7013                 // ephemeral apps can launch other ephemeral apps indirectly
   7014                 continue;
   7015             }
   7016             // allow activities that have been explicitly exposed to ephemeral apps
   7017             final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
   7018             if (!isEphemeralApp
   7019                     && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
   7020                 continue;
   7021             }
   7022             resolveInfos.remove(i);
   7023         }
   7024         return resolveInfos;
   7025     }
   7026 
   7027     /**
   7028      * Returns the activity component that can handle install failures.
   7029      * <p>By default, the instant application installer handles failures. However, an
   7030      * application may want to handle failures on its own. Applications do this by
   7031      * creating an activity with an intent filter that handles the action
   7032      * {@link Intent#ACTION_INSTALL_FAILURE}.
   7033      */
   7034     private @Nullable ComponentName findInstallFailureActivity(
   7035             String packageName, int filterCallingUid, int userId) {
   7036         final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
   7037         failureActivityIntent.setPackage(packageName);
   7038         // IMPORTANT: disallow dynamic splits to avoid an infinite loop
   7039         final List<ResolveInfo> result = queryIntentActivitiesInternal(
   7040                 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
   7041                 false /*resolveForStart*/, false /*allowDynamicSplits*/);
   7042         final int NR = result.size();
   7043         if (NR > 0) {
   7044             for (int i = 0; i < NR; i++) {
   7045                 final ResolveInfo info = result.get(i);
   7046                 if (info.activityInfo.splitName != null) {
   7047                     continue;
   7048                 }
   7049                 return new ComponentName(packageName, info.activityInfo.name);
   7050             }
   7051         }
   7052         return null;
   7053     }
   7054 
   7055     /**
   7056      * @param resolveInfos list of resolve infos in descending priority order
   7057      * @return if the list contains a resolve info with non-negative priority
   7058      */
   7059     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
   7060         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
   7061     }
   7062 
   7063     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
   7064             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
   7065             int userId) {
   7066         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
   7067 
   7068         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
   7069             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
   7070                     candidates.size());
   7071         }
   7072 
   7073         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
   7074         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
   7075         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
   7076         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
   7077         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
   7078         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
   7079 
   7080         synchronized (mPackages) {
   7081             final int count = candidates.size();
   7082             // First, try to use linked apps. Partition the candidates into four lists:
   7083             // one for the final results, one for the "do not use ever", one for "undefined status"
   7084             // and finally one for "browser app type".
   7085             for (int n=0; n<count; n++) {
   7086                 ResolveInfo info = candidates.get(n);
   7087                 String packageName = info.activityInfo.packageName;
   7088                 PackageSetting ps = mSettings.mPackages.get(packageName);
   7089                 if (ps != null) {
   7090                     // Add to the special match all list (Browser use case)
   7091                     if (info.handleAllWebDataURI) {
   7092                         matchAllList.add(info);
   7093                         continue;
   7094                     }
   7095                     // Try to get the status from User settings first
   7096                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
   7097                     int status = (int)(packedStatus >> 32);
   7098                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
   7099                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
   7100                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7101                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
   7102                                     + " : linkgen=" + linkGeneration);
   7103                         }
   7104                         // Use link-enabled generation as preferredOrder, i.e.
   7105                         // prefer newly-enabled over earlier-enabled.
   7106                         info.preferredOrder = linkGeneration;
   7107                         alwaysList.add(info);
   7108                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
   7109                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7110                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
   7111                         }
   7112                         neverList.add(info);
   7113                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
   7114                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7115                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
   7116                         }
   7117                         alwaysAskList.add(info);
   7118                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
   7119                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
   7120                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
   7121                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
   7122                         }
   7123                         undefinedList.add(info);
   7124                     }
   7125                 }
   7126             }
   7127 
   7128             // We'll want to include browser possibilities in a few cases
   7129             boolean includeBrowser = false;
   7130 
   7131             // First try to add the "always" resolution(s) for the current user, if any
   7132             if (alwaysList.size() > 0) {
   7133                 result.addAll(alwaysList);
   7134             } else {
   7135                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
   7136                 result.addAll(undefinedList);
   7137                 // Maybe add one for the other profile.
   7138                 if (xpDomainInfo != null && (
   7139                         xpDomainInfo.bestDomainVerificationStatus
   7140                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
   7141                     result.add(xpDomainInfo.resolveInfo);
   7142                 }
   7143                 includeBrowser = true;
   7144             }
   7145 
   7146             // The presence of any 'always ask' alternatives means we'll also offer browsers.
   7147             // If there were 'always' entries their preferred order has been set, so we also
   7148             // back that off to make the alternatives equivalent
   7149             if (alwaysAskList.size() > 0) {
   7150                 for (ResolveInfo i : result) {
   7151                     i.preferredOrder = 0;
   7152                 }
   7153                 result.addAll(alwaysAskList);
   7154                 includeBrowser = true;
   7155             }
   7156 
   7157             if (includeBrowser) {
   7158                 // Also add browsers (all of them or only the default one)
   7159                 if (DEBUG_DOMAIN_VERIFICATION) {
   7160                     Slog.v(TAG, "   ...including browsers in candidate set");
   7161                 }
   7162                 if ((matchFlags & MATCH_ALL) != 0) {
   7163                     result.addAll(matchAllList);
   7164                 } else {
   7165                     // Browser/generic handling case.  If there's a default browser, go straight
   7166                     // to that (but only if there is no other higher-priority match).
   7167                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
   7168                     int maxMatchPrio = 0;
   7169                     ResolveInfo defaultBrowserMatch = null;
   7170                     final int numCandidates = matchAllList.size();
   7171                     for (int n = 0; n < numCandidates; n++) {
   7172                         ResolveInfo info = matchAllList.get(n);
   7173                         // track the highest overall match priority...
   7174                         if (info.priority > maxMatchPrio) {
   7175                             maxMatchPrio = info.priority;
   7176                         }
   7177                         // ...and the highest-priority default browser match
   7178                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
   7179                             if (defaultBrowserMatch == null
   7180                                     || (defaultBrowserMatch.priority < info.priority)) {
   7181                                 if (debug) {
   7182                                     Slog.v(TAG, "Considering default browser match " + info);
   7183                                 }
   7184                                 defaultBrowserMatch = info;
   7185                             }
   7186                         }
   7187                     }
   7188                     if (defaultBrowserMatch != null
   7189                             && defaultBrowserMatch.priority >= maxMatchPrio
   7190                             && !TextUtils.isEmpty(defaultBrowserPackageName))
   7191                     {
   7192                         if (debug) {
   7193                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
   7194                         }
   7195                         result.add(defaultBrowserMatch);
   7196                     } else {
   7197                         result.addAll(matchAllList);
   7198                     }
   7199                 }
   7200 
   7201                 // If there is nothing selected, add all candidates and remove the ones that the user
   7202                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
   7203                 if (result.size() == 0) {
   7204                     result.addAll(candidates);
   7205                     result.removeAll(neverList);
   7206                 }
   7207             }
   7208         }
   7209         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
   7210             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
   7211                     result.size());
   7212             for (ResolveInfo info : result) {
   7213                 Slog.v(TAG, "  + " + info.activityInfo);
   7214             }
   7215         }
   7216         return result;
   7217     }
   7218 
   7219     // Returns a packed value as a long:
   7220     //
   7221     // high 'int'-sized word: link status: undefined/ask/never/always.
   7222     // low 'int'-sized word: relative priority among 'always' results.
   7223     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
   7224         long result = ps.getDomainVerificationStatusForUser(userId);
   7225         // if none available, get the master status
   7226         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
   7227             if (ps.getIntentFilterVerificationInfo() != null) {
   7228                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
   7229             }
   7230         }
   7231         return result;
   7232     }
   7233 
   7234     private ResolveInfo querySkipCurrentProfileIntents(
   7235             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
   7236             int flags, int sourceUserId) {
   7237         if (matchingFilters != null) {
   7238             int size = matchingFilters.size();
   7239             for (int i = 0; i < size; i ++) {
   7240                 CrossProfileIntentFilter filter = matchingFilters.get(i);
   7241                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
   7242                     // Checking if there are activities in the target user that can handle the
   7243                     // intent.
   7244                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
   7245                             resolvedType, flags, sourceUserId);
   7246                     if (resolveInfo != null) {
   7247                         return resolveInfo;
   7248                     }
   7249                 }
   7250             }
   7251         }
   7252         return null;
   7253     }
   7254 
   7255     // Return matching ResolveInfo in target user if any.
   7256     private ResolveInfo queryCrossProfileIntents(
   7257             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
   7258             int flags, int sourceUserId, boolean matchInCurrentProfile) {
   7259         if (matchingFilters != null) {
   7260             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
   7261             // match the same intent. For performance reasons, it is better not to
   7262             // run queryIntent twice for the same userId
   7263             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
   7264             int size = matchingFilters.size();
   7265             for (int i = 0; i < size; i++) {
   7266                 CrossProfileIntentFilter filter = matchingFilters.get(i);
   7267                 int targetUserId = filter.getTargetUserId();
   7268                 boolean skipCurrentProfile =
   7269                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
   7270                 boolean skipCurrentProfileIfNoMatchFound =
   7271                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
   7272                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
   7273                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
   7274                     // Checking if there are activities in the target user that can handle the
   7275                     // intent.
   7276                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
   7277                             resolvedType, flags, sourceUserId);
   7278                     if (resolveInfo != null) return resolveInfo;
   7279                     alreadyTriedUserIds.put(targetUserId, true);
   7280                 }
   7281             }
   7282         }
   7283         return null;
   7284     }
   7285 
   7286     /**
   7287      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
   7288      * will forward the intent to the filter's target user.
   7289      * Otherwise, returns null.
   7290      */
   7291     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
   7292             String resolvedType, int flags, int sourceUserId) {
   7293         int targetUserId = filter.getTargetUserId();
   7294         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
   7295                 resolvedType, flags, targetUserId);
   7296         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
   7297             // If all the matches in the target profile are suspended, return null.
   7298             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
   7299                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
   7300                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
   7301                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
   7302                             targetUserId);
   7303                 }
   7304             }
   7305         }
   7306         return null;
   7307     }
   7308 
   7309     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
   7310             int sourceUserId, int targetUserId) {
   7311         ResolveInfo forwardingResolveInfo = new ResolveInfo();
   7312         long ident = Binder.clearCallingIdentity();
   7313         boolean targetIsProfile;
   7314         try {
   7315             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
   7316         } finally {
   7317             Binder.restoreCallingIdentity(ident);
   7318         }
   7319         String className;
   7320         if (targetIsProfile) {
   7321             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
   7322         } else {
   7323             className = FORWARD_INTENT_TO_PARENT;
   7324         }
   7325         ComponentName forwardingActivityComponentName = new ComponentName(
   7326                 mAndroidApplication.packageName, className);
   7327         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
   7328                 sourceUserId);
   7329         if (!targetIsProfile) {
   7330             forwardingActivityInfo.showUserIcon = targetUserId;
   7331             forwardingResolveInfo.noResourceId = true;
   7332         }
   7333         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
   7334         forwardingResolveInfo.priority = 0;
   7335         forwardingResolveInfo.preferredOrder = 0;
   7336         forwardingResolveInfo.match = 0;
   7337         forwardingResolveInfo.isDefault = true;
   7338         forwardingResolveInfo.filter = filter;
   7339         forwardingResolveInfo.targetUserId = targetUserId;
   7340         return forwardingResolveInfo;
   7341     }
   7342 
   7343     @Override
   7344     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
   7345             Intent[] specifics, String[] specificTypes, Intent intent,
   7346             String resolvedType, int flags, int userId) {
   7347         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
   7348                 specificTypes, intent, resolvedType, flags, userId));
   7349     }
   7350 
   7351     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
   7352             Intent[] specifics, String[] specificTypes, Intent intent,
   7353             String resolvedType, int flags, int userId) {
   7354         if (!sUserManager.exists(userId)) return Collections.emptyList();
   7355         final int callingUid = Binder.getCallingUid();
   7356         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
   7357                 false /*includeInstantApps*/);
   7358         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   7359                 false /*requireFullPermission*/, false /*checkShell*/,
   7360                 "query intent activity options");
   7361         final String resultsAction = intent.getAction();
   7362 
   7363         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
   7364                 | PackageManager.GET_RESOLVED_FILTER, userId);
   7365 
   7366         if (DEBUG_INTENT_MATCHING) {
   7367             Log.v(TAG, "Query " + intent + ": " + results);
   7368         }
   7369 
   7370         int specificsPos = 0;
   7371         int N;
   7372 
   7373         // todo: note that the algorithm used here is O(N^2).  This
   7374         // isn't a problem in our current environment, but if we start running
   7375         // into situations where we have more than 5 or 10 matches then this
   7376         // should probably be changed to something smarter...
   7377 
   7378         // First we go through and resolve each of the specific items
   7379         // that were supplied, taking care of removing any corresponding
   7380         // duplicate items in the generic resolve list.
   7381         if (specifics != null) {
   7382             for (int i=0; i<specifics.length; i++) {
   7383                 final Intent sintent = specifics[i];
   7384                 if (sintent == null) {
   7385                     continue;
   7386                 }
   7387 
   7388                 if (DEBUG_INTENT_MATCHING) {
   7389                     Log.v(TAG, "Specific #" + i + ": " + sintent);
   7390                 }
   7391 
   7392                 String action = sintent.getAction();
   7393                 if (resultsAction != null && resultsAction.equals(action)) {
   7394                     // If this action was explicitly requested, then don't
   7395                     // remove things that have it.
   7396                     action = null;
   7397                 }
   7398 
   7399                 ResolveInfo ri = null;
   7400                 ActivityInfo ai = null;
   7401 
   7402                 ComponentName comp = sintent.getComponent();
   7403                 if (comp == null) {
   7404                     ri = resolveIntent(
   7405                         sintent,
   7406                         specificTypes != null ? specificTypes[i] : null,
   7407                             flags, userId);
   7408                     if (ri == null) {
   7409                         continue;
   7410                     }
   7411                     if (ri == mResolveInfo) {
   7412                         // ACK!  Must do something better with this.
   7413                     }
   7414                     ai = ri.activityInfo;
   7415                     comp = new ComponentName(ai.applicationInfo.packageName,
   7416                             ai.name);
   7417                 } else {
   7418                     ai = getActivityInfo(comp, flags, userId);
   7419                     if (ai == null) {
   7420                         continue;
   7421                     }
   7422                 }
   7423 
   7424                 // Look for any generic query activities that are duplicates
   7425                 // of this specific one, and remove them from the results.
   7426                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
   7427                 N = results.size();
   7428                 int j;
   7429                 for (j=specificsPos; j<N; j++) {
   7430                     ResolveInfo sri = results.get(j);
   7431                     if ((sri.activityInfo.name.equals(comp.getClassName())
   7432                             && sri.activityInfo.applicationInfo.packageName.equals(
   7433                                     comp.getPackageName()))
   7434                         || (action != null && sri.filter.matchAction(action))) {
   7435                         results.remove(j);
   7436                         if (DEBUG_INTENT_MATCHING) Log.v(
   7437                             TAG, "Removing duplicate item from " + j
   7438                             + " due to specific " + specificsPos);
   7439                         if (ri == null) {
   7440                             ri = sri;
   7441                         }
   7442                         j--;
   7443                         N--;
   7444                     }
   7445                 }
   7446 
   7447                 // Add this specific item to its proper place.
   7448                 if (ri == null) {
   7449                     ri = new ResolveInfo();
   7450                     ri.activityInfo = ai;
   7451                 }
   7452                 results.add(specificsPos, ri);
   7453                 ri.specificIndex = i;
   7454                 specificsPos++;
   7455             }
   7456         }
   7457 
   7458         // Now we go through the remaining generic results and remove any
   7459         // duplicate actions that are found here.
   7460         N = results.size();
   7461         for (int i=specificsPos; i<N-1; i++) {
   7462             final ResolveInfo rii = results.get(i);
   7463             if (rii.filter == null) {
   7464                 continue;
   7465             }
   7466 
   7467             // Iterate over all of the actions of this result's intent
   7468             // filter...  typically this should be just one.
   7469             final Iterator<String> it = rii.filter.actionsIterator();
   7470             if (it == null) {
   7471                 continue;
   7472             }
   7473             while (it.hasNext()) {
   7474                 final String action = it.next();
   7475                 if (resultsAction != null && resultsAction.equals(action)) {
   7476                     // If this action was explicitly requested, then don't
   7477                     // remove things that have it.
   7478                     continue;
   7479                 }
   7480                 for (int j=i+1; j<N; j++) {
   7481                     final ResolveInfo rij = results.get(j);
   7482                     if (rij.filter != null && rij.filter.hasAction(action)) {
   7483                         results.remove(j);
   7484                         if (DEBUG_INTENT_MATCHING) Log.v(
   7485                             TAG, "Removing duplicate item from " + j
   7486                             + " due to action " + action + " at " + i);
   7487                         j--;
   7488                         N--;
   7489                     }
   7490                 }
   7491             }
   7492 
   7493             // If the caller didn't request filter information, drop it now
   7494             // so we don't have to marshall/unmarshall it.
   7495             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
   7496                 rii.filter = null;
   7497             }
   7498         }
   7499 
   7500         // Filter out the caller activity if so requested.
   7501         if (caller != null) {
   7502             N = results.size();
   7503             for (int i=0; i<N; i++) {
   7504                 ActivityInfo ainfo = results.get(i).activityInfo;
   7505                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
   7506                         && caller.getClassName().equals(ainfo.name)) {
   7507                     results.remove(i);
   7508                     break;
   7509                 }
   7510             }
   7511         }
   7512 
   7513         // If the caller didn't request filter information,
   7514         // drop them now so we don't have to
   7515         // marshall/unmarshall it.
   7516         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
   7517             N = results.size();
   7518             for (int i=0; i<N; i++) {
   7519                 results.get(i).filter = null;
   7520             }
   7521         }
   7522 
   7523         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
   7524         return results;
   7525     }
   7526 
   7527     @Override
   7528     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
   7529             String resolvedType, int flags, int userId) {
   7530         return new ParceledListSlice<>(
   7531                 queryIntentReceiversInternal(intent, resolvedType, flags, userId,
   7532                         false /*allowDynamicSplits*/));
   7533     }
   7534 
   7535     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
   7536             String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
   7537         if (!sUserManager.exists(userId)) return Collections.emptyList();
   7538         final int callingUid = Binder.getCallingUid();
   7539         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   7540                 false /*requireFullPermission*/, false /*checkShell*/,
   7541                 "query intent receivers");
   7542         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   7543         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
   7544                 false /*includeInstantApps*/);
   7545         ComponentName comp = intent.getComponent();
   7546         if (comp == null) {
   7547             if (intent.getSelector() != null) {
   7548                 intent = intent.getSelector();
   7549                 comp = intent.getComponent();
   7550             }
   7551         }
   7552         if (comp != null) {
   7553             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   7554             final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
   7555             if (ai != null) {
   7556                 // When specifying an explicit component, we prevent the activity from being
   7557                 // used when either 1) the calling package is normal and the activity is within
   7558                 // an instant application or 2) the calling package is ephemeral and the
   7559                 // activity is not visible to instant applications.
   7560                 final boolean matchInstantApp =
   7561                         (flags & PackageManager.MATCH_INSTANT) != 0;
   7562                 final boolean matchVisibleToInstantAppOnly =
   7563                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   7564                 final boolean matchExplicitlyVisibleOnly =
   7565                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
   7566                 final boolean isCallerInstantApp =
   7567                         instantAppPkgName != null;
   7568                 final boolean isTargetSameInstantApp =
   7569                         comp.getPackageName().equals(instantAppPkgName);
   7570                 final boolean isTargetInstantApp =
   7571                         (ai.applicationInfo.privateFlags
   7572                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   7573                 final boolean isTargetVisibleToInstantApp =
   7574                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
   7575                 final boolean isTargetExplicitlyVisibleToInstantApp =
   7576                         isTargetVisibleToInstantApp
   7577                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
   7578                 final boolean isTargetHiddenFromInstantApp =
   7579                         !isTargetVisibleToInstantApp
   7580                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
   7581                 final boolean blockResolution =
   7582                         !isTargetSameInstantApp
   7583                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   7584                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   7585                                         && isTargetHiddenFromInstantApp));
   7586                 if (!blockResolution) {
   7587                     ResolveInfo ri = new ResolveInfo();
   7588                     ri.activityInfo = ai;
   7589                     list.add(ri);
   7590                 }
   7591             }
   7592             return applyPostResolutionFilter(
   7593                     list, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
   7594                     intent);
   7595         }
   7596 
   7597         // reader
   7598         synchronized (mPackages) {
   7599             String pkgName = intent.getPackage();
   7600             if (pkgName == null) {
   7601                 final List<ResolveInfo> result =
   7602                         mReceivers.queryIntent(intent, resolvedType, flags, userId);
   7603                 return applyPostResolutionFilter(
   7604                         result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
   7605                         intent);
   7606             }
   7607             final PackageParser.Package pkg = mPackages.get(pkgName);
   7608             if (pkg != null) {
   7609                 final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
   7610                         intent, resolvedType, flags, pkg.receivers, userId);
   7611                 return applyPostResolutionFilter(
   7612                         result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
   7613                         intent);
   7614             }
   7615             return Collections.emptyList();
   7616         }
   7617     }
   7618 
   7619     @Override
   7620     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
   7621         final int callingUid = Binder.getCallingUid();
   7622         return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
   7623     }
   7624 
   7625     private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
   7626             int userId, int callingUid) {
   7627         if (!sUserManager.exists(userId)) return null;
   7628         flags = updateFlagsForResolve(
   7629                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
   7630         List<ResolveInfo> query = queryIntentServicesInternal(
   7631                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
   7632         if (query != null) {
   7633             if (query.size() >= 1) {
   7634                 // If there is more than one service with the same priority,
   7635                 // just arbitrarily pick the first one.
   7636                 return query.get(0);
   7637             }
   7638         }
   7639         return null;
   7640     }
   7641 
   7642     @Override
   7643     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
   7644             String resolvedType, int flags, int userId) {
   7645         final int callingUid = Binder.getCallingUid();
   7646         return new ParceledListSlice<>(queryIntentServicesInternal(
   7647                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
   7648     }
   7649 
   7650     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
   7651             String resolvedType, int flags, int userId, int callingUid,
   7652             boolean includeInstantApps) {
   7653         if (!sUserManager.exists(userId)) return Collections.emptyList();
   7654         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   7655                 false /*requireFullPermission*/, false /*checkShell*/,
   7656                 "query intent receivers");
   7657         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   7658         flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
   7659         ComponentName comp = intent.getComponent();
   7660         if (comp == null) {
   7661             if (intent.getSelector() != null) {
   7662                 intent = intent.getSelector();
   7663                 comp = intent.getComponent();
   7664             }
   7665         }
   7666         if (comp != null) {
   7667             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   7668             final ServiceInfo si = getServiceInfo(comp, flags, userId);
   7669             if (si != null) {
   7670                 // When specifying an explicit component, we prevent the service from being
   7671                 // used when either 1) the service is in an instant application and the
   7672                 // caller is not the same instant application or 2) the calling package is
   7673                 // ephemeral and the activity is not visible to ephemeral applications.
   7674                 final boolean matchInstantApp =
   7675                         (flags & PackageManager.MATCH_INSTANT) != 0;
   7676                 final boolean matchVisibleToInstantAppOnly =
   7677                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   7678                 final boolean isCallerInstantApp =
   7679                         instantAppPkgName != null;
   7680                 final boolean isTargetSameInstantApp =
   7681                         comp.getPackageName().equals(instantAppPkgName);
   7682                 final boolean isTargetInstantApp =
   7683                         (si.applicationInfo.privateFlags
   7684                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   7685                 final boolean isTargetHiddenFromInstantApp =
   7686                         (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
   7687                 final boolean blockResolution =
   7688                         !isTargetSameInstantApp
   7689                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   7690                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   7691                                         && isTargetHiddenFromInstantApp));
   7692                 if (!blockResolution) {
   7693                     final ResolveInfo ri = new ResolveInfo();
   7694                     ri.serviceInfo = si;
   7695                     list.add(ri);
   7696                 }
   7697             }
   7698             return list;
   7699         }
   7700 
   7701         // reader
   7702         synchronized (mPackages) {
   7703             String pkgName = intent.getPackage();
   7704             if (pkgName == null) {
   7705                 return applyPostServiceResolutionFilter(
   7706                         mServices.queryIntent(intent, resolvedType, flags, userId),
   7707                         instantAppPkgName);
   7708             }
   7709             final PackageParser.Package pkg = mPackages.get(pkgName);
   7710             if (pkg != null) {
   7711                 return applyPostServiceResolutionFilter(
   7712                         mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
   7713                                 userId),
   7714                         instantAppPkgName);
   7715             }
   7716             return Collections.emptyList();
   7717         }
   7718     }
   7719 
   7720     private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
   7721             String instantAppPkgName) {
   7722         if (instantAppPkgName == null) {
   7723             return resolveInfos;
   7724         }
   7725         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   7726             final ResolveInfo info = resolveInfos.get(i);
   7727             final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
   7728             // allow services that are defined in the provided package
   7729             if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
   7730                 if (info.serviceInfo.splitName != null
   7731                         && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
   7732                                 info.serviceInfo.splitName)) {
   7733                     // requested service is defined in a split that hasn't been installed yet.
   7734                     // add the installer to the resolve list
   7735                     if (DEBUG_INSTANT) {
   7736                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
   7737                     }
   7738                     final ResolveInfo installerInfo = new ResolveInfo(
   7739                             mInstantAppInstallerInfo);
   7740                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
   7741                             null /* installFailureActivity */,
   7742                             info.serviceInfo.packageName,
   7743                             info.serviceInfo.applicationInfo.longVersionCode,
   7744                             info.serviceInfo.splitName);
   7745                     // add a non-generic filter
   7746                     installerInfo.filter = new IntentFilter();
   7747                     // load resources from the correct package
   7748                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
   7749                     resolveInfos.set(i, installerInfo);
   7750                 }
   7751                 continue;
   7752             }
   7753             // allow services that have been explicitly exposed to ephemeral apps
   7754             if (!isEphemeralApp
   7755                     && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
   7756                 continue;
   7757             }
   7758             resolveInfos.remove(i);
   7759         }
   7760         return resolveInfos;
   7761     }
   7762 
   7763     @Override
   7764     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
   7765             String resolvedType, int flags, int userId) {
   7766         return new ParceledListSlice<>(
   7767                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
   7768     }
   7769 
   7770     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
   7771             Intent intent, String resolvedType, int flags, int userId) {
   7772         if (!sUserManager.exists(userId)) return Collections.emptyList();
   7773         final int callingUid = Binder.getCallingUid();
   7774         final String instantAppPkgName = getInstantAppPackageName(callingUid);
   7775         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
   7776                 false /*includeInstantApps*/);
   7777         ComponentName comp = intent.getComponent();
   7778         if (comp == null) {
   7779             if (intent.getSelector() != null) {
   7780                 intent = intent.getSelector();
   7781                 comp = intent.getComponent();
   7782             }
   7783         }
   7784         if (comp != null) {
   7785             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   7786             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
   7787             if (pi != null) {
   7788                 // When specifying an explicit component, we prevent the provider from being
   7789                 // used when either 1) the provider is in an instant application and the
   7790                 // caller is not the same instant application or 2) the calling package is an
   7791                 // instant application and the provider is not visible to instant applications.
   7792                 final boolean matchInstantApp =
   7793                         (flags & PackageManager.MATCH_INSTANT) != 0;
   7794                 final boolean matchVisibleToInstantAppOnly =
   7795                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   7796                 final boolean isCallerInstantApp =
   7797                         instantAppPkgName != null;
   7798                 final boolean isTargetSameInstantApp =
   7799                         comp.getPackageName().equals(instantAppPkgName);
   7800                 final boolean isTargetInstantApp =
   7801                         (pi.applicationInfo.privateFlags
   7802                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
   7803                 final boolean isTargetHiddenFromInstantApp =
   7804                         (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
   7805                 final boolean blockResolution =
   7806                         !isTargetSameInstantApp
   7807                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
   7808                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
   7809                                         && isTargetHiddenFromInstantApp));
   7810                 if (!blockResolution) {
   7811                     final ResolveInfo ri = new ResolveInfo();
   7812                     ri.providerInfo = pi;
   7813                     list.add(ri);
   7814                 }
   7815             }
   7816             return list;
   7817         }
   7818 
   7819         // reader
   7820         synchronized (mPackages) {
   7821             String pkgName = intent.getPackage();
   7822             if (pkgName == null) {
   7823                 return applyPostContentProviderResolutionFilter(
   7824                         mProviders.queryIntent(intent, resolvedType, flags, userId),
   7825                         instantAppPkgName);
   7826             }
   7827             final PackageParser.Package pkg = mPackages.get(pkgName);
   7828             if (pkg != null) {
   7829                 return applyPostContentProviderResolutionFilter(
   7830                         mProviders.queryIntentForPackage(
   7831                         intent, resolvedType, flags, pkg.providers, userId),
   7832                         instantAppPkgName);
   7833             }
   7834             return Collections.emptyList();
   7835         }
   7836     }
   7837 
   7838     private List<ResolveInfo> applyPostContentProviderResolutionFilter(
   7839             List<ResolveInfo> resolveInfos, String instantAppPkgName) {
   7840         if (instantAppPkgName == null) {
   7841             return resolveInfos;
   7842         }
   7843         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
   7844             final ResolveInfo info = resolveInfos.get(i);
   7845             final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
   7846             // allow providers that are defined in the provided package
   7847             if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
   7848                 if (info.providerInfo.splitName != null
   7849                         && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
   7850                                 info.providerInfo.splitName)) {
   7851                     // requested provider is defined in a split that hasn't been installed yet.
   7852                     // add the installer to the resolve list
   7853                     if (DEBUG_INSTANT) {
   7854                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
   7855                     }
   7856                     final ResolveInfo installerInfo = new ResolveInfo(
   7857                             mInstantAppInstallerInfo);
   7858                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
   7859                             null /*failureActivity*/,
   7860                             info.providerInfo.packageName,
   7861                             info.providerInfo.applicationInfo.longVersionCode,
   7862                             info.providerInfo.splitName);
   7863                     // add a non-generic filter
   7864                     installerInfo.filter = new IntentFilter();
   7865                     // load resources from the correct package
   7866                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
   7867                     resolveInfos.set(i, installerInfo);
   7868                 }
   7869                 continue;
   7870             }
   7871             // allow providers that have been explicitly exposed to instant applications
   7872             if (!isEphemeralApp
   7873                     && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
   7874                 continue;
   7875             }
   7876             resolveInfos.remove(i);
   7877         }
   7878         return resolveInfos;
   7879     }
   7880 
   7881     @Override
   7882     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
   7883         final int callingUid = Binder.getCallingUid();
   7884         if (getInstantAppPackageName(callingUid) != null) {
   7885             return ParceledListSlice.emptyList();
   7886         }
   7887         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   7888         flags = updateFlagsForPackage(flags, userId, null);
   7889         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
   7890         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   7891                 false /* requireFullPermission */, false /* checkShell */,
   7892                 "get installed packages");
   7893 
   7894         // writer
   7895         synchronized (mPackages) {
   7896             ArrayList<PackageInfo> list;
   7897             if (listUninstalled) {
   7898                 list = new ArrayList<>(mSettings.mPackages.size());
   7899                 for (PackageSetting ps : mSettings.mPackages.values()) {
   7900                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
   7901                         continue;
   7902                     }
   7903                     if (filterAppAccessLPr(ps, callingUid, userId)) {
   7904                         continue;
   7905                     }
   7906                     final PackageInfo pi = generatePackageInfo(ps, flags, userId);
   7907                     if (pi != null) {
   7908                         list.add(pi);
   7909                     }
   7910                 }
   7911             } else {
   7912                 list = new ArrayList<>(mPackages.size());
   7913                 for (PackageParser.Package p : mPackages.values()) {
   7914                     final PackageSetting ps = (PackageSetting) p.mExtras;
   7915                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
   7916                         continue;
   7917                     }
   7918                     if (filterAppAccessLPr(ps, callingUid, userId)) {
   7919                         continue;
   7920                     }
   7921                     final PackageInfo pi = generatePackageInfo((PackageSetting)
   7922                             p.mExtras, flags, userId);
   7923                     if (pi != null) {
   7924                         list.add(pi);
   7925                     }
   7926                 }
   7927             }
   7928 
   7929             return new ParceledListSlice<>(list);
   7930         }
   7931     }
   7932 
   7933     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
   7934             String[] permissions, boolean[] tmp, int flags, int userId) {
   7935         int numMatch = 0;
   7936         final PermissionsState permissionsState = ps.getPermissionsState();
   7937         for (int i=0; i<permissions.length; i++) {
   7938             final String permission = permissions[i];
   7939             if (permissionsState.hasPermission(permission, userId)) {
   7940                 tmp[i] = true;
   7941                 numMatch++;
   7942             } else {
   7943                 tmp[i] = false;
   7944             }
   7945         }
   7946         if (numMatch == 0) {
   7947             return;
   7948         }
   7949         final PackageInfo pi = generatePackageInfo(ps, flags, userId);
   7950 
   7951         // The above might return null in cases of uninstalled apps or install-state
   7952         // skew across users/profiles.
   7953         if (pi != null) {
   7954             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
   7955                 if (numMatch == permissions.length) {
   7956                     pi.requestedPermissions = permissions;
   7957                 } else {
   7958                     pi.requestedPermissions = new String[numMatch];
   7959                     numMatch = 0;
   7960                     for (int i=0; i<permissions.length; i++) {
   7961                         if (tmp[i]) {
   7962                             pi.requestedPermissions[numMatch] = permissions[i];
   7963                             numMatch++;
   7964                         }
   7965                     }
   7966                 }
   7967             }
   7968             list.add(pi);
   7969         }
   7970     }
   7971 
   7972     @Override
   7973     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
   7974             String[] permissions, int flags, int userId) {
   7975         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   7976         flags = updateFlagsForPackage(flags, userId, permissions);
   7977         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   7978                 true /* requireFullPermission */, false /* checkShell */,
   7979                 "get packages holding permissions");
   7980         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
   7981 
   7982         // writer
   7983         synchronized (mPackages) {
   7984             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
   7985             boolean[] tmpBools = new boolean[permissions.length];
   7986             if (listUninstalled) {
   7987                 for (PackageSetting ps : mSettings.mPackages.values()) {
   7988                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
   7989                             userId);
   7990                 }
   7991             } else {
   7992                 for (PackageParser.Package pkg : mPackages.values()) {
   7993                     PackageSetting ps = (PackageSetting)pkg.mExtras;
   7994                     if (ps != null) {
   7995                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
   7996                                 userId);
   7997                     }
   7998                 }
   7999             }
   8000 
   8001             return new ParceledListSlice<PackageInfo>(list);
   8002         }
   8003     }
   8004 
   8005     @Override
   8006     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
   8007         final int callingUid = Binder.getCallingUid();
   8008         if (getInstantAppPackageName(callingUid) != null) {
   8009             return ParceledListSlice.emptyList();
   8010         }
   8011         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   8012         flags = updateFlagsForApplication(flags, userId, null);
   8013         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
   8014 
   8015         mPermissionManager.enforceCrossUserPermission(
   8016             callingUid,
   8017             userId,
   8018             false /* requireFullPermission */,
   8019             false /* checkShell */,
   8020             "get installed application info");
   8021 
   8022         // writer
   8023         synchronized (mPackages) {
   8024             ArrayList<ApplicationInfo> list;
   8025             if (listUninstalled) {
   8026                 list = new ArrayList<>(mSettings.mPackages.size());
   8027                 for (PackageSetting ps : mSettings.mPackages.values()) {
   8028                     ApplicationInfo ai;
   8029                     int effectiveFlags = flags;
   8030                     if (ps.isSystem()) {
   8031                         effectiveFlags |= PackageManager.MATCH_ANY_USER;
   8032                     }
   8033                     if (ps.pkg != null) {
   8034                         if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
   8035                             continue;
   8036                         }
   8037                         if (filterAppAccessLPr(ps, callingUid, userId)) {
   8038                             continue;
   8039                         }
   8040                         ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
   8041                                 ps.readUserState(userId), userId);
   8042                         if (ai != null) {
   8043                             ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
   8044                         }
   8045                     } else {
   8046                         // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
   8047                         // and already converts to externally visible package name
   8048                         ai = generateApplicationInfoFromSettingsLPw(ps.name,
   8049                                 callingUid, effectiveFlags, userId);
   8050                     }
   8051                     if (ai != null) {
   8052                         list.add(ai);
   8053                     }
   8054                 }
   8055             } else {
   8056                 list = new ArrayList<>(mPackages.size());
   8057                 for (PackageParser.Package p : mPackages.values()) {
   8058                     if (p.mExtras != null) {
   8059                         PackageSetting ps = (PackageSetting) p.mExtras;
   8060                         if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
   8061                             continue;
   8062                         }
   8063                         if (filterAppAccessLPr(ps, callingUid, userId)) {
   8064                             continue;
   8065                         }
   8066                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
   8067                                 ps.readUserState(userId), userId);
   8068                         if (ai != null) {
   8069                             ai.packageName = resolveExternalPackageNameLPr(p);
   8070                             list.add(ai);
   8071                         }
   8072                     }
   8073                 }
   8074             }
   8075 
   8076             return new ParceledListSlice<>(list);
   8077         }
   8078     }
   8079 
   8080     @Override
   8081     public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
   8082         if (HIDE_EPHEMERAL_APIS) {
   8083             return null;
   8084         }
   8085         if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
   8086             mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
   8087                     "getEphemeralApplications");
   8088         }
   8089         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8090                 true /* requireFullPermission */, false /* checkShell */,
   8091                 "getEphemeralApplications");
   8092         synchronized (mPackages) {
   8093             List<InstantAppInfo> instantApps = mInstantAppRegistry
   8094                     .getInstantAppsLPr(userId);
   8095             if (instantApps != null) {
   8096                 return new ParceledListSlice<>(instantApps);
   8097             }
   8098         }
   8099         return null;
   8100     }
   8101 
   8102     @Override
   8103     public boolean isInstantApp(String packageName, int userId) {
   8104         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8105                 true /* requireFullPermission */, false /* checkShell */,
   8106                 "isInstantApp");
   8107         if (HIDE_EPHEMERAL_APIS) {
   8108             return false;
   8109         }
   8110 
   8111         synchronized (mPackages) {
   8112             int callingUid = Binder.getCallingUid();
   8113             if (Process.isIsolated(callingUid)) {
   8114                 callingUid = mIsolatedOwners.get(callingUid);
   8115             }
   8116             final PackageSetting ps = mSettings.mPackages.get(packageName);
   8117             PackageParser.Package pkg = mPackages.get(packageName);
   8118             final boolean returnAllowed =
   8119                     ps != null
   8120                     && (isCallerSameApp(packageName, callingUid)
   8121                             || canViewInstantApps(callingUid, userId)
   8122                             || mInstantAppRegistry.isInstantAccessGranted(
   8123                                     userId, UserHandle.getAppId(callingUid), ps.appId));
   8124             if (returnAllowed) {
   8125                 return ps.getInstantApp(userId);
   8126             }
   8127         }
   8128         return false;
   8129     }
   8130 
   8131     @Override
   8132     public byte[] getInstantAppCookie(String packageName, int userId) {
   8133         if (HIDE_EPHEMERAL_APIS) {
   8134             return null;
   8135         }
   8136 
   8137         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8138                 true /* requireFullPermission */, false /* checkShell */,
   8139                 "getInstantAppCookie");
   8140         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
   8141             return null;
   8142         }
   8143         synchronized (mPackages) {
   8144             return mInstantAppRegistry.getInstantAppCookieLPw(
   8145                     packageName, userId);
   8146         }
   8147     }
   8148 
   8149     @Override
   8150     public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
   8151         if (HIDE_EPHEMERAL_APIS) {
   8152             return true;
   8153         }
   8154 
   8155         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8156                 true /* requireFullPermission */, true /* checkShell */,
   8157                 "setInstantAppCookie");
   8158         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
   8159             return false;
   8160         }
   8161         synchronized (mPackages) {
   8162             return mInstantAppRegistry.setInstantAppCookieLPw(
   8163                     packageName, cookie, userId);
   8164         }
   8165     }
   8166 
   8167     @Override
   8168     public Bitmap getInstantAppIcon(String packageName, int userId) {
   8169         if (HIDE_EPHEMERAL_APIS) {
   8170             return null;
   8171         }
   8172 
   8173         if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
   8174             mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
   8175                     "getInstantAppIcon");
   8176         }
   8177         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   8178                 true /* requireFullPermission */, false /* checkShell */,
   8179                 "getInstantAppIcon");
   8180 
   8181         synchronized (mPackages) {
   8182             return mInstantAppRegistry.getInstantAppIconLPw(
   8183                     packageName, userId);
   8184         }
   8185     }
   8186 
   8187     private boolean isCallerSameApp(String packageName, int uid) {
   8188         PackageParser.Package pkg = mPackages.get(packageName);
   8189         return pkg != null
   8190                 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
   8191     }
   8192 
   8193     @Override
   8194     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
   8195         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   8196             return ParceledListSlice.emptyList();
   8197         }
   8198         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
   8199     }
   8200 
   8201     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
   8202         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
   8203 
   8204         // reader
   8205         synchronized (mPackages) {
   8206             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
   8207             final int userId = UserHandle.getCallingUserId();
   8208             while (i.hasNext()) {
   8209                 final PackageParser.Package p = i.next();
   8210                 if (p.applicationInfo == null) continue;
   8211 
   8212                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
   8213                         && !p.applicationInfo.isDirectBootAware();
   8214                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
   8215                         && p.applicationInfo.isDirectBootAware();
   8216 
   8217                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
   8218                         && (!mSafeMode || isSystemApp(p))
   8219                         && (matchesUnaware || matchesAware)) {
   8220                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
   8221                     if (ps != null) {
   8222                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
   8223                                 ps.readUserState(userId), userId);
   8224                         if (ai != null) {
   8225                             finalList.add(ai);
   8226                         }
   8227                     }
   8228                 }
   8229             }
   8230         }
   8231 
   8232         return finalList;
   8233     }
   8234 
   8235     @Override
   8236     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
   8237         return resolveContentProviderInternal(name, flags, userId);
   8238     }
   8239 
   8240     private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
   8241         if (!sUserManager.exists(userId)) return null;
   8242         flags = updateFlagsForComponent(flags, userId, name);
   8243         final int callingUid = Binder.getCallingUid();
   8244         synchronized (mPackages) {
   8245             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
   8246             PackageSetting ps = provider != null
   8247                     ? mSettings.mPackages.get(provider.owner.packageName)
   8248                     : null;
   8249             if (ps != null) {
   8250                 // provider not enabled
   8251                 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
   8252                     return null;
   8253                 }
   8254                 final ComponentName component =
   8255                         new ComponentName(provider.info.packageName, provider.info.name);
   8256                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
   8257                     return null;
   8258                 }
   8259                 return PackageParser.generateProviderInfo(
   8260                         provider, flags, ps.readUserState(userId), userId);
   8261             }
   8262             return null;
   8263         }
   8264     }
   8265 
   8266     /**
   8267      * @deprecated
   8268      */
   8269     @Deprecated
   8270     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
   8271         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   8272             return;
   8273         }
   8274         // reader
   8275         synchronized (mPackages) {
   8276             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
   8277                     .entrySet().iterator();
   8278             final int userId = UserHandle.getCallingUserId();
   8279             while (i.hasNext()) {
   8280                 Map.Entry<String, PackageParser.Provider> entry = i.next();
   8281                 PackageParser.Provider p = entry.getValue();
   8282                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
   8283 
   8284                 if (ps != null && p.syncable
   8285                         && (!mSafeMode || (p.info.applicationInfo.flags
   8286                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
   8287                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
   8288                             ps.readUserState(userId), userId);
   8289                     if (info != null) {
   8290                         outNames.add(entry.getKey());
   8291                         outInfo.add(info);
   8292                     }
   8293                 }
   8294             }
   8295         }
   8296     }
   8297 
   8298     @Override
   8299     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
   8300             int uid, int flags, String metaDataKey) {
   8301         final int callingUid = Binder.getCallingUid();
   8302         final int userId = processName != null ? UserHandle.getUserId(uid)
   8303                 : UserHandle.getCallingUserId();
   8304         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
   8305         flags = updateFlagsForComponent(flags, userId, processName);
   8306         ArrayList<ProviderInfo> finalList = null;
   8307         // reader
   8308         synchronized (mPackages) {
   8309             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
   8310             while (i.hasNext()) {
   8311                 final PackageParser.Provider p = i.next();
   8312                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
   8313                 if (ps != null && p.info.authority != null
   8314                         && (processName == null
   8315                                 || (p.info.processName.equals(processName)
   8316                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
   8317                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
   8318 
   8319                     // See PM.queryContentProviders()'s javadoc for why we have the metaData
   8320                     // parameter.
   8321                     if (metaDataKey != null
   8322                             && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
   8323                         continue;
   8324                     }
   8325                     final ComponentName component =
   8326                             new ComponentName(p.info.packageName, p.info.name);
   8327                     if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
   8328                         continue;
   8329                     }
   8330                     if (finalList == null) {
   8331                         finalList = new ArrayList<ProviderInfo>(3);
   8332                     }
   8333                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
   8334                             ps.readUserState(userId), userId);
   8335                     if (info != null) {
   8336                         finalList.add(info);
   8337                     }
   8338                 }
   8339             }
   8340         }
   8341 
   8342         if (finalList != null) {
   8343             Collections.sort(finalList, mProviderInitOrderSorter);
   8344             return new ParceledListSlice<ProviderInfo>(finalList);
   8345         }
   8346 
   8347         return ParceledListSlice.emptyList();
   8348     }
   8349 
   8350     @Override
   8351     public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
   8352         // reader
   8353         synchronized (mPackages) {
   8354             final int callingUid = Binder.getCallingUid();
   8355             final int callingUserId = UserHandle.getUserId(callingUid);
   8356             final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   8357             if (ps == null) return null;
   8358             if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
   8359                 return null;
   8360             }
   8361             final PackageParser.Instrumentation i = mInstrumentation.get(component);
   8362             return PackageParser.generateInstrumentationInfo(i, flags);
   8363         }
   8364     }
   8365 
   8366     @Override
   8367     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
   8368             String targetPackage, int flags) {
   8369         final int callingUid = Binder.getCallingUid();
   8370         final int callingUserId = UserHandle.getUserId(callingUid);
   8371         final PackageSetting ps = mSettings.mPackages.get(targetPackage);
   8372         if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   8373             return ParceledListSlice.emptyList();
   8374         }
   8375         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
   8376     }
   8377 
   8378     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
   8379             int flags) {
   8380         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
   8381 
   8382         // reader
   8383         synchronized (mPackages) {
   8384             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
   8385             while (i.hasNext()) {
   8386                 final PackageParser.Instrumentation p = i.next();
   8387                 if (targetPackage == null
   8388                         || targetPackage.equals(p.info.targetPackage)) {
   8389                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
   8390                             flags);
   8391                     if (ii != null) {
   8392                         finalList.add(ii);
   8393                     }
   8394                 }
   8395             }
   8396         }
   8397 
   8398         return finalList;
   8399     }
   8400 
   8401     private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
   8402         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
   8403         try {
   8404             scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
   8405         } finally {
   8406             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   8407         }
   8408     }
   8409 
   8410     private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
   8411         final File[] files = scanDir.listFiles();
   8412         if (ArrayUtils.isEmpty(files)) {
   8413             Log.d(TAG, "No files in app dir " + scanDir);
   8414             return;
   8415         }
   8416 
   8417         if (DEBUG_PACKAGE_SCANNING) {
   8418             Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
   8419                     + " flags=0x" + Integer.toHexString(parseFlags));
   8420         }
   8421         try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
   8422                 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
   8423                 mParallelPackageParserCallback)) {
   8424             // Submit files for parsing in parallel
   8425             int fileCount = 0;
   8426             for (File file : files) {
   8427                 final boolean isPackage = (isApkFile(file) || file.isDirectory())
   8428                         && !PackageInstallerService.isStageName(file.getName());
   8429                 if (!isPackage) {
   8430                     // Ignore entries which are not packages
   8431                     continue;
   8432                 }
   8433                 parallelPackageParser.submit(file, parseFlags);
   8434                 fileCount++;
   8435             }
   8436 
   8437             // Process results one by one
   8438             for (; fileCount > 0; fileCount--) {
   8439                 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
   8440                 Throwable throwable = parseResult.throwable;
   8441                 int errorCode = PackageManager.INSTALL_SUCCEEDED;
   8442 
   8443                 if (throwable == null) {
   8444                     // TODO(toddke): move lower in the scan chain
   8445                     // Static shared libraries have synthetic package names
   8446                     if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
   8447                         renameStaticSharedLibraryPackage(parseResult.pkg);
   8448                     }
   8449                     try {
   8450                         if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
   8451                             scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
   8452                                     currentTime, null);
   8453                         }
   8454                     } catch (PackageManagerException e) {
   8455                         errorCode = e.error;
   8456                         Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
   8457                     }
   8458                 } else if (throwable instanceof PackageParser.PackageParserException) {
   8459                     PackageParser.PackageParserException e = (PackageParser.PackageParserException)
   8460                             throwable;
   8461                     errorCode = e.error;
   8462                     Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
   8463                 } else {
   8464                     throw new IllegalStateException("Unexpected exception occurred while parsing "
   8465                             + parseResult.scanFile, throwable);
   8466                 }
   8467 
   8468                 // Delete invalid userdata apps
   8469                 if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
   8470                         errorCode != PackageManager.INSTALL_SUCCEEDED) {
   8471                     logCriticalInfo(Log.WARN,
   8472                             "Deleting invalid package at " + parseResult.scanFile);
   8473                     removeCodePathLI(parseResult.scanFile);
   8474                 }
   8475             }
   8476         }
   8477     }
   8478 
   8479     public static void reportSettingsProblem(int priority, String msg) {
   8480         logCriticalInfo(priority, msg);
   8481     }
   8482 
   8483     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
   8484             boolean forceCollect, boolean skipVerify) throws PackageManagerException {
   8485         // When upgrading from pre-N MR1, verify the package time stamp using the package
   8486         // directory and not the APK file.
   8487         final long lastModifiedTime = mIsPreNMR1Upgrade
   8488                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
   8489         if (ps != null && !forceCollect
   8490                 && ps.codePathString.equals(pkg.codePath)
   8491                 && ps.timeStamp == lastModifiedTime
   8492                 && !isCompatSignatureUpdateNeeded(pkg)
   8493                 && !isRecoverSignatureUpdateNeeded(pkg)) {
   8494             if (ps.signatures.mSigningDetails.signatures != null
   8495                     && ps.signatures.mSigningDetails.signatures.length != 0
   8496                     && ps.signatures.mSigningDetails.signatureSchemeVersion
   8497                             != SignatureSchemeVersion.UNKNOWN) {
   8498                 // Optimization: reuse the existing cached signing data
   8499                 // if the package appears to be unchanged.
   8500                 pkg.mSigningDetails =
   8501                         new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
   8502                 return;
   8503             }
   8504 
   8505             Slog.w(TAG, "PackageSetting for " + ps.name
   8506                     + " is missing signatures.  Collecting certs again to recover them.");
   8507         } else {
   8508             Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
   8509                     (forceCollect ? " (forced)" : ""));
   8510         }
   8511 
   8512         try {
   8513             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
   8514             PackageParser.collectCertificates(pkg, skipVerify);
   8515         } catch (PackageParserException e) {
   8516             throw PackageManagerException.from(e);
   8517         } finally {
   8518             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   8519         }
   8520     }
   8521 
   8522     /**
   8523      * Clear the package profile if this was an upgrade and the package
   8524      * version was updated.
   8525      */
   8526     private void maybeClearProfilesForUpgradesLI(
   8527             @Nullable PackageSetting originalPkgSetting,
   8528             @NonNull PackageParser.Package currentPkg) {
   8529         if (originalPkgSetting == null || !isUpgrade()) {
   8530           return;
   8531         }
   8532         if (originalPkgSetting.versionCode == currentPkg.mVersionCode) {
   8533           return;
   8534         }
   8535 
   8536         clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL);
   8537         if (DEBUG_INSTALL) {
   8538             Slog.d(TAG, originalPkgSetting.name
   8539                   + " clear profile due to version change "
   8540                   + originalPkgSetting.versionCode + " != "
   8541                   + currentPkg.mVersionCode);
   8542         }
   8543     }
   8544 
   8545     /**
   8546      *  Traces a package scan.
   8547      *  @see #scanPackageLI(File, int, int, long, UserHandle)
   8548      */
   8549     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
   8550             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
   8551         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
   8552         try {
   8553             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
   8554         } finally {
   8555             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   8556         }
   8557     }
   8558 
   8559     /**
   8560      *  Scans a package and returns the newly parsed package.
   8561      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
   8562      */
   8563     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
   8564             long currentTime, UserHandle user) throws PackageManagerException {
   8565         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
   8566         PackageParser pp = new PackageParser();
   8567         pp.setSeparateProcesses(mSeparateProcesses);
   8568         pp.setOnlyCoreApps(mOnlyCore);
   8569         pp.setDisplayMetrics(mMetrics);
   8570         pp.setCallback(mPackageParserCallback);
   8571 
   8572         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
   8573         final PackageParser.Package pkg;
   8574         try {
   8575             pkg = pp.parsePackage(scanFile, parseFlags);
   8576         } catch (PackageParserException e) {
   8577             throw PackageManagerException.from(e);
   8578         } finally {
   8579             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   8580         }
   8581 
   8582         // Static shared libraries have synthetic package names
   8583         if (pkg.applicationInfo.isStaticSharedLibrary()) {
   8584             renameStaticSharedLibraryPackage(pkg);
   8585         }
   8586 
   8587         return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
   8588     }
   8589 
   8590     /**
   8591      *  Scans a package and returns the newly parsed package.
   8592      *  @throws PackageManagerException on a parse error.
   8593      */
   8594     private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
   8595             final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
   8596             @Nullable UserHandle user)
   8597                     throws PackageManagerException {
   8598         // If the package has children and this is the first dive in the function
   8599         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
   8600         // packages (parent and children) would be successfully scanned before the
   8601         // actual scan since scanning mutates internal state and we want to atomically
   8602         // install the package and its children.
   8603         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
   8604             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
   8605                 scanFlags |= SCAN_CHECK_ONLY;
   8606             }
   8607         } else {
   8608             scanFlags &= ~SCAN_CHECK_ONLY;
   8609         }
   8610 
   8611         // Scan the parent
   8612         PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
   8613                 scanFlags, currentTime, user);
   8614 
   8615         // Scan the children
   8616         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   8617         for (int i = 0; i < childCount; i++) {
   8618             PackageParser.Package childPackage = pkg.childPackages.get(i);
   8619             addForInitLI(childPackage, parseFlags, scanFlags,
   8620                     currentTime, user);
   8621         }
   8622 
   8623 
   8624         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
   8625             return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
   8626         }
   8627 
   8628         return scannedPkg;
   8629     }
   8630 
   8631     /**
   8632      * Returns if full apk verification can be skipped for the whole package, including the splits.
   8633      */
   8634     private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
   8635         if (!canSkipFullApkVerification(pkg.baseCodePath)) {
   8636             return false;
   8637         }
   8638         // TODO: Allow base and splits to be verified individually.
   8639         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
   8640             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
   8641                 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
   8642                     return false;
   8643                 }
   8644             }
   8645         }
   8646         return true;
   8647     }
   8648 
   8649     /**
   8650      * Returns if full apk verification can be skipped, depending on current FSVerity setup and
   8651      * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
   8652      * match one in a trusted source, and should be done separately.
   8653      */
   8654     private boolean canSkipFullApkVerification(String apkPath) {
   8655         byte[] rootHashObserved = null;
   8656         try {
   8657             rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
   8658             if (rootHashObserved == null) {
   8659                 return false;  // APK does not contain Merkle tree root hash.
   8660             }
   8661             synchronized (mInstallLock) {
   8662                 // Returns whether the observed root hash matches what kernel has.
   8663                 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
   8664                 return true;
   8665             }
   8666         } catch (InstallerException | IOException | DigestException |
   8667                 NoSuchAlgorithmException e) {
   8668             Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
   8669         }
   8670         return false;
   8671     }
   8672 
   8673     /**
   8674      * Adds a new package to the internal data structures during platform initialization.
   8675      * <p>After adding, the package is known to the system and available for querying.
   8676      * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
   8677      * etc...], additional checks are performed. Basic verification [such as ensuring
   8678      * matching signatures, checking version codes, etc...] occurs if the package is
   8679      * identical to a previously known package. If the package fails a signature check,
   8680      * the version installed on /data will be removed. If the version of the new package
   8681      * is less than or equal than the version on /data, it will be ignored.
   8682      * <p>Regardless of the package location, the results are applied to the internal
   8683      * structures and the package is made available to the rest of the system.
   8684      * <p>NOTE: The return value should be removed. It's the passed in package object.
   8685      */
   8686     private PackageParser.Package addForInitLI(PackageParser.Package pkg,
   8687             @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
   8688             @Nullable UserHandle user)
   8689                     throws PackageManagerException {
   8690         final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
   8691         final String renamedPkgName;
   8692         final PackageSetting disabledPkgSetting;
   8693         final boolean isSystemPkgUpdated;
   8694         final boolean pkgAlreadyExists;
   8695         PackageSetting pkgSetting;
   8696 
   8697         // NOTE: installPackageLI() has the same code to setup the package's
   8698         // application info. This probably should be done lower in the call
   8699         // stack [such as scanPackageOnly()]. However, we verify the application
   8700         // info prior to that [in scanPackageNew()] and thus have to setup
   8701         // the application info early.
   8702         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
   8703         pkg.setApplicationInfoCodePath(pkg.codePath);
   8704         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
   8705         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
   8706         pkg.setApplicationInfoResourcePath(pkg.codePath);
   8707         pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
   8708         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
   8709 
   8710         synchronized (mPackages) {
   8711             renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
   8712             final String realPkgName = getRealPackageName(pkg, renamedPkgName);
   8713             if (realPkgName != null) {
   8714                 ensurePackageRenamed(pkg, renamedPkgName);
   8715             }
   8716             final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
   8717             final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
   8718             pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
   8719             pkgAlreadyExists = pkgSetting != null;
   8720             final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
   8721             disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
   8722             isSystemPkgUpdated = disabledPkgSetting != null;
   8723 
   8724             if (DEBUG_INSTALL && isSystemPkgUpdated) {
   8725                 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
   8726             }
   8727 
   8728             final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
   8729                     ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
   8730                             0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
   8731                     : null;
   8732             if (DEBUG_PACKAGE_SCANNING
   8733                     && (parseFlags & PackageParser.PARSE_CHATTY) != 0
   8734                     && sharedUserSetting != null) {
   8735                 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
   8736                         + " (uid=" + sharedUserSetting.userId + "):"
   8737                         + " packages=" + sharedUserSetting.packages);
   8738             }
   8739 
   8740             if (scanSystemPartition) {
   8741                 // Potentially prune child packages. If the application on the /system
   8742                 // partition has been updated via OTA, but, is still disabled by a
   8743                 // version on /data, cycle through all of its children packages and
   8744                 // remove children that are no longer defined.
   8745                 if (isSystemPkgUpdated) {
   8746                     final int scannedChildCount = (pkg.childPackages != null)
   8747                             ? pkg.childPackages.size() : 0;
   8748                     final int disabledChildCount = disabledPkgSetting.childPackageNames != null
   8749                             ? disabledPkgSetting.childPackageNames.size() : 0;
   8750                     for (int i = 0; i < disabledChildCount; i++) {
   8751                         String disabledChildPackageName =
   8752                                 disabledPkgSetting.childPackageNames.get(i);
   8753                         boolean disabledPackageAvailable = false;
   8754                         for (int j = 0; j < scannedChildCount; j++) {
   8755                             PackageParser.Package childPkg = pkg.childPackages.get(j);
   8756                             if (childPkg.packageName.equals(disabledChildPackageName)) {
   8757                                 disabledPackageAvailable = true;
   8758                                 break;
   8759                             }
   8760                         }
   8761                         if (!disabledPackageAvailable) {
   8762                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
   8763                         }
   8764                     }
   8765                     // we're updating the disabled package, so, scan it as the package setting
   8766                     final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
   8767                             disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
   8768                             null /* originalPkgSetting */, null, parseFlags, scanFlags,
   8769                             (pkg == mPlatformPackage), user);
   8770                     applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
   8771                     scanPackageOnlyLI(request, mFactoryTest, -1L);
   8772                 }
   8773             }
   8774         }
   8775 
   8776         final boolean newPkgChangedPaths =
   8777                 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
   8778         final boolean newPkgVersionGreater =
   8779                 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
   8780         final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
   8781                 && newPkgChangedPaths && newPkgVersionGreater;
   8782         if (isSystemPkgBetter) {
   8783             // The version of the application on /system is greater than the version on
   8784             // /data. Switch back to the application on /system.
   8785             // It's safe to assume the application on /system will correctly scan. If not,
   8786             // there won't be a working copy of the application.
   8787             synchronized (mPackages) {
   8788                 // just remove the loaded entries from package lists
   8789                 mPackages.remove(pkgSetting.name);
   8790             }
   8791 
   8792             logCriticalInfo(Log.WARN,
   8793                     "System package updated;"
   8794                     + " name: " + pkgSetting.name
   8795                     + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
   8796                     + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
   8797 
   8798             final InstallArgs args = createInstallArgsForExisting(
   8799                     packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
   8800                     pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
   8801             args.cleanUpResourcesLI();
   8802             synchronized (mPackages) {
   8803                 mSettings.enableSystemPackageLPw(pkgSetting.name);
   8804             }
   8805         }
   8806 
   8807         if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
   8808             // The version of the application on the /system partition is less than or
   8809             // equal to the version on the /data partition. Even though the disabled system package
   8810             // is likely to be replaced by a version on the /data partition, we make assumptions
   8811             // that it's part of the mPackages collection during package manager initialization. So,
   8812             // add it to mPackages if there isn't already a package in the collection and then throw
   8813             // an exception to use the application already installed on the /data partition.
   8814             synchronized (mPackages) {
   8815                 if (!mPackages.containsKey(pkg.packageName)) {
   8816                     mPackages.put(pkg.packageName, pkg);
   8817                 }
   8818             }
   8819             throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
   8820                     + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode
   8821                     + " better than this " + pkg.getLongVersionCode());
   8822         }
   8823 
   8824         // Verify certificates against what was last scanned. If it is an updated priv app, we will
   8825         // force re-collecting certificate.
   8826         final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
   8827                 disabledPkgSetting);
   8828         // Full APK verification can be skipped during certificate collection, only if the file is
   8829         // in verified partition, or can be verified on access (when apk verity is enabled). In both
   8830         // cases, only data in Signing Block is verified instead of the whole file.
   8831         final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
   8832                 (forceCollect && canSkipFullPackageVerification(pkg));
   8833         collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
   8834 
   8835         // Reset profile if the application version is changed
   8836         maybeClearProfilesForUpgradesLI(pkgSetting, pkg);
   8837 
   8838         /*
   8839          * A new system app appeared, but we already had a non-system one of the
   8840          * same name installed earlier.
   8841          */
   8842         boolean shouldHideSystemApp = false;
   8843         // A new application appeared on /system, but, we already have a copy of
   8844         // the application installed on /data.
   8845         if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
   8846                 && !pkgSetting.isSystem()) {
   8847 
   8848             if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
   8849                     PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
   8850                             && !pkgSetting.signatures.mSigningDetails.checkCapability(
   8851                                     pkg.mSigningDetails,
   8852                                     PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
   8853                 logCriticalInfo(Log.WARN,
   8854                         "System package signature mismatch;"
   8855                         + " name: " + pkgSetting.name);
   8856                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
   8857                         "scanPackageInternalLI")) {
   8858                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
   8859                 }
   8860                 pkgSetting = null;
   8861             } else if (newPkgVersionGreater) {
   8862                 // The application on /system is newer than the application on /data.
   8863                 // Simply remove the application on /data [keeping application data]
   8864                 // and replace it with the version on /system.
   8865                 logCriticalInfo(Log.WARN,
   8866                         "System package enabled;"
   8867                         + " name: " + pkgSetting.name
   8868                         + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
   8869                         + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
   8870                 InstallArgs args = createInstallArgsForExisting(
   8871                         packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
   8872                         pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
   8873                 synchronized (mInstallLock) {
   8874                     args.cleanUpResourcesLI();
   8875                 }
   8876             } else {
   8877                 // The application on /system is older than the application on /data. Hide
   8878                 // the application on /system and the version on /data will be scanned later
   8879                 // and re-added like an update.
   8880                 shouldHideSystemApp = true;
   8881                 logCriticalInfo(Log.INFO,
   8882                         "System package disabled;"
   8883                         + " name: " + pkgSetting.name
   8884                         + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
   8885                         + "; new: " + pkg.codePath + " @ " + pkg.codePath);
   8886             }
   8887         }
   8888 
   8889         final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
   8890                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
   8891 
   8892         if (shouldHideSystemApp) {
   8893             synchronized (mPackages) {
   8894                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
   8895             }
   8896         }
   8897         return scannedPkg;
   8898     }
   8899 
   8900     private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
   8901         // Derive the new package synthetic package name
   8902         pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
   8903                 + pkg.staticSharedLibVersion);
   8904     }
   8905 
   8906     private static String fixProcessName(String defProcessName,
   8907             String processName) {
   8908         if (processName == null) {
   8909             return defProcessName;
   8910         }
   8911         return processName;
   8912     }
   8913 
   8914     /**
   8915      * Enforces that only the system UID or root's UID can call a method exposed
   8916      * via Binder.
   8917      *
   8918      * @param message used as message if SecurityException is thrown
   8919      * @throws SecurityException if the caller is not system or root
   8920      */
   8921     private static final void enforceSystemOrRoot(String message) {
   8922         final int uid = Binder.getCallingUid();
   8923         if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
   8924             throw new SecurityException(message);
   8925         }
   8926     }
   8927 
   8928     @Override
   8929     public void performFstrimIfNeeded() {
   8930         enforceSystemOrRoot("Only the system can request fstrim");
   8931 
   8932         // Before everything else, see whether we need to fstrim.
   8933         try {
   8934             IStorageManager sm = PackageHelper.getStorageManager();
   8935             if (sm != null) {
   8936                 boolean doTrim = false;
   8937                 final long interval = android.provider.Settings.Global.getLong(
   8938                         mContext.getContentResolver(),
   8939                         android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
   8940                         DEFAULT_MANDATORY_FSTRIM_INTERVAL);
   8941                 if (interval > 0) {
   8942                     final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
   8943                     if (timeSinceLast > interval) {
   8944                         doTrim = true;
   8945                         Slog.w(TAG, "No disk maintenance in " + timeSinceLast
   8946                                 + "; running immediately");
   8947                     }
   8948                 }
   8949                 if (doTrim) {
   8950                     final boolean dexOptDialogShown;
   8951                     synchronized (mPackages) {
   8952                         dexOptDialogShown = mDexOptDialogShown;
   8953                     }
   8954                     if (!isFirstBoot() && dexOptDialogShown) {
   8955                         try {
   8956                             ActivityManager.getService().showBootMessage(
   8957                                     mContext.getResources().getString(
   8958                                             R.string.android_upgrading_fstrim), true);
   8959                         } catch (RemoteException e) {
   8960                         }
   8961                     }
   8962                     sm.runMaintenance();
   8963                 }
   8964             } else {
   8965                 Slog.e(TAG, "storageManager service unavailable!");
   8966             }
   8967         } catch (RemoteException e) {
   8968             // Can't happen; StorageManagerService is local
   8969         }
   8970     }
   8971 
   8972     @Override
   8973     public void updatePackagesIfNeeded() {
   8974         enforceSystemOrRoot("Only the system can request package update");
   8975 
   8976         // We need to re-extract after an OTA.
   8977         boolean causeUpgrade = isUpgrade();
   8978 
   8979         // First boot or factory reset.
   8980         // Note: we also handle devices that are upgrading to N right now as if it is their
   8981         //       first boot, as they do not have profile data.
   8982         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
   8983 
   8984         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
   8985         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
   8986 
   8987         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
   8988             return;
   8989         }
   8990 
   8991         List<PackageParser.Package> pkgs;
   8992         synchronized (mPackages) {
   8993             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
   8994         }
   8995 
   8996         final long startTime = System.nanoTime();
   8997         final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
   8998                     causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
   8999                     false /* bootComplete */);
   9000 
   9001         final int elapsedTimeSeconds =
   9002                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
   9003 
   9004         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
   9005         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
   9006         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
   9007         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
   9008         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
   9009     }
   9010 
   9011     /*
   9012      * Return the prebuilt profile path given a package base code path.
   9013      */
   9014     private static String getPrebuildProfilePath(PackageParser.Package pkg) {
   9015         return pkg.baseCodePath + ".prof";
   9016     }
   9017 
   9018     /**
   9019      * Performs dexopt on the set of packages in {@code packages} and returns an int array
   9020      * containing statistics about the invocation. The array consists of three elements,
   9021      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
   9022      * and {@code numberOfPackagesFailed}.
   9023      */
   9024     private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
   9025             final int compilationReason, boolean bootComplete) {
   9026 
   9027         int numberOfPackagesVisited = 0;
   9028         int numberOfPackagesOptimized = 0;
   9029         int numberOfPackagesSkipped = 0;
   9030         int numberOfPackagesFailed = 0;
   9031         final int numberOfPackagesToDexopt = pkgs.size();
   9032 
   9033         for (PackageParser.Package pkg : pkgs) {
   9034             numberOfPackagesVisited++;
   9035 
   9036             boolean useProfileForDexopt = false;
   9037 
   9038             if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
   9039                 // Copy over initial preopt profiles since we won't get any JIT samples for methods
   9040                 // that are already compiled.
   9041                 File profileFile = new File(getPrebuildProfilePath(pkg));
   9042                 // Copy profile if it exists.
   9043                 if (profileFile.exists()) {
   9044                     try {
   9045                         // We could also do this lazily before calling dexopt in
   9046                         // PackageDexOptimizer to prevent this happening on first boot. The issue
   9047                         // is that we don't have a good way to say "do this only once".
   9048                         if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
   9049                                 pkg.applicationInfo.uid, pkg.packageName,
   9050                                 ArtManager.getProfileName(null))) {
   9051                             Log.e(TAG, "Installer failed to copy system profile!");
   9052                         } else {
   9053                             // Disabled as this causes speed-profile compilation during first boot
   9054                             // even if things are already compiled.
   9055                             // useProfileForDexopt = true;
   9056                         }
   9057                     } catch (Exception e) {
   9058                         Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
   9059                                 e);
   9060                     }
   9061                 } else {
   9062                     PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
   9063                     // Handle compressed APKs in this path. Only do this for stubs with profiles to
   9064                     // minimize the number off apps being speed-profile compiled during first boot.
   9065                     // The other paths will not change the filter.
   9066                     if (disabledPs != null && disabledPs.pkg.isStub) {
   9067                         // The package is the stub one, remove the stub suffix to get the normal
   9068                         // package and APK names.
   9069                         String systemProfilePath =
   9070                                 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
   9071                         profileFile = new File(systemProfilePath);
   9072                         // If we have a profile for a compressed APK, copy it to the reference
   9073                         // location.
   9074                         // Note that copying the profile here will cause it to override the
   9075                         // reference profile every OTA even though the existing reference profile
   9076                         // may have more data. We can't copy during decompression since the
   9077                         // directories are not set up at that point.
   9078                         if (profileFile.exists()) {
   9079                             try {
   9080                                 // We could also do this lazily before calling dexopt in
   9081                                 // PackageDexOptimizer to prevent this happening on first boot. The
   9082                                 // issue is that we don't have a good way to say "do this only
   9083                                 // once".
   9084                                 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
   9085                                         pkg.applicationInfo.uid, pkg.packageName,
   9086                                         ArtManager.getProfileName(null))) {
   9087                                     Log.e(TAG, "Failed to copy system profile for stub package!");
   9088                                 } else {
   9089                                     useProfileForDexopt = true;
   9090                                 }
   9091                             } catch (Exception e) {
   9092                                 Log.e(TAG, "Failed to copy profile " +
   9093                                         profileFile.getAbsolutePath() + " ", e);
   9094                             }
   9095                         }
   9096                     }
   9097                 }
   9098             }
   9099 
   9100             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
   9101                 if (DEBUG_DEXOPT) {
   9102                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
   9103                 }
   9104                 numberOfPackagesSkipped++;
   9105                 continue;
   9106             }
   9107 
   9108             if (DEBUG_DEXOPT) {
   9109                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
   9110                         numberOfPackagesToDexopt + ": " + pkg.packageName);
   9111             }
   9112 
   9113             if (showDialog) {
   9114                 try {
   9115                     ActivityManager.getService().showBootMessage(
   9116                             mContext.getResources().getString(R.string.android_upgrading_apk,
   9117                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
   9118                 } catch (RemoteException e) {
   9119                 }
   9120                 synchronized (mPackages) {
   9121                     mDexOptDialogShown = true;
   9122                 }
   9123             }
   9124 
   9125             int pkgCompilationReason = compilationReason;
   9126             if (useProfileForDexopt) {
   9127                 // Use background dexopt mode to try and use the profile. Note that this does not
   9128                 // guarantee usage of the profile.
   9129                 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
   9130             }
   9131 
   9132             // checkProfiles is false to avoid merging profiles during boot which
   9133             // might interfere with background compilation (b/28612421).
   9134             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
   9135             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
   9136             // trade-off worth doing to save boot time work.
   9137             int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
   9138             if (compilationReason == REASON_FIRST_BOOT) {
   9139                 // TODO: This doesn't cover the upgrade case, we should check for this too.
   9140                 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
   9141             }
   9142             int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
   9143                     pkg.packageName,
   9144                     pkgCompilationReason,
   9145                     dexoptFlags));
   9146 
   9147             switch (primaryDexOptStaus) {
   9148                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
   9149                     numberOfPackagesOptimized++;
   9150                     break;
   9151                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
   9152                     numberOfPackagesSkipped++;
   9153                     break;
   9154                 case PackageDexOptimizer.DEX_OPT_FAILED:
   9155                     numberOfPackagesFailed++;
   9156                     break;
   9157                 default:
   9158                     Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
   9159                     break;
   9160             }
   9161         }
   9162 
   9163         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
   9164                 numberOfPackagesFailed };
   9165     }
   9166 
   9167     @Override
   9168     public void notifyPackageUse(String packageName, int reason) {
   9169         synchronized (mPackages) {
   9170             final int callingUid = Binder.getCallingUid();
   9171             final int callingUserId = UserHandle.getUserId(callingUid);
   9172             if (getInstantAppPackageName(callingUid) != null) {
   9173                 if (!isCallerSameApp(packageName, callingUid)) {
   9174                     return;
   9175                 }
   9176             } else {
   9177                 if (isInstantApp(packageName, callingUserId)) {
   9178                     return;
   9179                 }
   9180             }
   9181             notifyPackageUseLocked(packageName, reason);
   9182         }
   9183     }
   9184 
   9185     @GuardedBy("mPackages")
   9186     private void notifyPackageUseLocked(String packageName, int reason) {
   9187         final PackageParser.Package p = mPackages.get(packageName);
   9188         if (p == null) {
   9189             return;
   9190         }
   9191         p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
   9192     }
   9193 
   9194     @Override
   9195     public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
   9196             List<String> classPaths, String loaderIsa) {
   9197         int userId = UserHandle.getCallingUserId();
   9198         ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
   9199         if (ai == null) {
   9200             Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
   9201                 + loadingPackageName + ", user=" + userId);
   9202             return;
   9203         }
   9204         mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
   9205     }
   9206 
   9207     @Override
   9208     public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
   9209             IDexModuleRegisterCallback callback) {
   9210         int userId = UserHandle.getCallingUserId();
   9211         ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
   9212         DexManager.RegisterDexModuleResult result;
   9213         if (ai == null) {
   9214             Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
   9215                      " calling user. package=" + packageName + ", user=" + userId);
   9216             result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
   9217         } else {
   9218             result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
   9219         }
   9220 
   9221         if (callback != null) {
   9222             mHandler.post(() -> {
   9223                 try {
   9224                     callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
   9225                 } catch (RemoteException e) {
   9226                     Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
   9227                 }
   9228             });
   9229         }
   9230     }
   9231 
   9232     /**
   9233      * Ask the package manager to perform a dex-opt with the given compiler filter.
   9234      *
   9235      * Note: exposed only for the shell command to allow moving packages explicitly to a
   9236      *       definite state.
   9237      */
   9238     @Override
   9239     public boolean performDexOptMode(String packageName,
   9240             boolean checkProfiles, String targetCompilerFilter, boolean force,
   9241             boolean bootComplete, String splitName) {
   9242         int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
   9243                 (force ? DexoptOptions.DEXOPT_FORCE : 0) |
   9244                 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
   9245         return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
   9246                 targetCompilerFilter, splitName, flags));
   9247     }
   9248 
   9249     /**
   9250      * Ask the package manager to perform a dex-opt with the given compiler filter on the
   9251      * secondary dex files belonging to the given package.
   9252      *
   9253      * Note: exposed only for the shell command to allow moving packages explicitly to a
   9254      *       definite state.
   9255      */
   9256     @Override
   9257     public boolean performDexOptSecondary(String packageName, String compilerFilter,
   9258             boolean force) {
   9259         int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
   9260                 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
   9261                 DexoptOptions.DEXOPT_BOOT_COMPLETE |
   9262                 (force ? DexoptOptions.DEXOPT_FORCE : 0);
   9263         return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
   9264     }
   9265 
   9266     /*package*/ boolean performDexOpt(DexoptOptions options) {
   9267         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   9268             return false;
   9269         } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
   9270             return false;
   9271         }
   9272 
   9273         if (options.isDexoptOnlySecondaryDex()) {
   9274             return mDexManager.dexoptSecondaryDex(options);
   9275         } else {
   9276             int dexoptStatus = performDexOptWithStatus(options);
   9277             return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
   9278         }
   9279     }
   9280 
   9281     /**
   9282      * Perform dexopt on the given package and return one of following result:
   9283      *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
   9284      *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
   9285      *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
   9286      */
   9287     /* package */ int performDexOptWithStatus(DexoptOptions options) {
   9288         return performDexOptTraced(options);
   9289     }
   9290 
   9291     private int performDexOptTraced(DexoptOptions options) {
   9292         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
   9293         try {
   9294             return performDexOptInternal(options);
   9295         } finally {
   9296             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9297         }
   9298     }
   9299 
   9300     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
   9301     // if the package can now be considered up to date for the given filter.
   9302     private int performDexOptInternal(DexoptOptions options) {
   9303         PackageParser.Package p;
   9304         synchronized (mPackages) {
   9305             p = mPackages.get(options.getPackageName());
   9306             if (p == null) {
   9307                 // Package could not be found. Report failure.
   9308                 return PackageDexOptimizer.DEX_OPT_FAILED;
   9309             }
   9310             mPackageUsage.maybeWriteAsync(mPackages);
   9311             mCompilerStats.maybeWriteAsync();
   9312         }
   9313         long callingId = Binder.clearCallingIdentity();
   9314         try {
   9315             synchronized (mInstallLock) {
   9316                 return performDexOptInternalWithDependenciesLI(p, options);
   9317             }
   9318         } finally {
   9319             Binder.restoreCallingIdentity(callingId);
   9320         }
   9321     }
   9322 
   9323     public ArraySet<String> getOptimizablePackages() {
   9324         ArraySet<String> pkgs = new ArraySet<String>();
   9325         synchronized (mPackages) {
   9326             for (PackageParser.Package p : mPackages.values()) {
   9327                 if (PackageDexOptimizer.canOptimizePackage(p)) {
   9328                     pkgs.add(p.packageName);
   9329                 }
   9330             }
   9331         }
   9332         return pkgs;
   9333     }
   9334 
   9335     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
   9336             DexoptOptions options) {
   9337         // Select the dex optimizer based on the force parameter.
   9338         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
   9339         //       allocate an object here.
   9340         PackageDexOptimizer pdo = options.isForce()
   9341                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
   9342                 : mPackageDexOptimizer;
   9343 
   9344         // Dexopt all dependencies first. Note: we ignore the return value and march on
   9345         // on errors.
   9346         // Note that we are going to call performDexOpt on those libraries as many times as
   9347         // they are referenced in packages. When we do a batch of performDexOpt (for example
   9348         // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
   9349         // and the first package that uses the library will dexopt it. The
   9350         // others will see that the compiled code for the library is up to date.
   9351         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
   9352         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
   9353         if (!deps.isEmpty()) {
   9354             DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
   9355                     options.getCompilationReason(), options.getCompilerFilter(),
   9356                     options.getSplitName(),
   9357                     options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
   9358             for (PackageParser.Package depPackage : deps) {
   9359                 // TODO: Analyze and investigate if we (should) profile libraries.
   9360                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
   9361                         getOrCreateCompilerPackageStats(depPackage),
   9362                     mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
   9363             }
   9364         }
   9365         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
   9366                 getOrCreateCompilerPackageStats(p),
   9367                 mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
   9368     }
   9369 
   9370     /**
   9371      * Reconcile the information we have about the secondary dex files belonging to
   9372      * {@code packagName} and the actual dex files. For all dex files that were
   9373      * deleted, update the internal records and delete the generated oat files.
   9374      */
   9375     @Override
   9376     public void reconcileSecondaryDexFiles(String packageName) {
   9377         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   9378             return;
   9379         } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
   9380             return;
   9381         }
   9382         mDexManager.reconcileSecondaryDexFiles(packageName);
   9383     }
   9384 
   9385     // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
   9386     // a reference there.
   9387     /*package*/ DexManager getDexManager() {
   9388         return mDexManager;
   9389     }
   9390 
   9391     /**
   9392      * Execute the background dexopt job immediately.
   9393      */
   9394     @Override
   9395     public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
   9396         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   9397             return false;
   9398         }
   9399         return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
   9400     }
   9401 
   9402     List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
   9403         if (p.usesLibraries != null || p.usesOptionalLibraries != null
   9404                 || p.usesStaticLibraries != null) {
   9405             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
   9406             Set<String> collectedNames = new HashSet<>();
   9407             findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
   9408 
   9409             retValue.remove(p);
   9410 
   9411             return retValue;
   9412         } else {
   9413             return Collections.emptyList();
   9414         }
   9415     }
   9416 
   9417     private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
   9418             ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
   9419         if (!collectedNames.contains(p.packageName)) {
   9420             collectedNames.add(p.packageName);
   9421             collected.add(p);
   9422 
   9423             if (p.usesLibraries != null) {
   9424                 findSharedNonSystemLibrariesRecursive(p.usesLibraries,
   9425                         null, collected, collectedNames);
   9426             }
   9427             if (p.usesOptionalLibraries != null) {
   9428                 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
   9429                         null, collected, collectedNames);
   9430             }
   9431             if (p.usesStaticLibraries != null) {
   9432                 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
   9433                         p.usesStaticLibrariesVersions, collected, collectedNames);
   9434             }
   9435         }
   9436     }
   9437 
   9438     private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
   9439             ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
   9440         final int libNameCount = libs.size();
   9441         for (int i = 0; i < libNameCount; i++) {
   9442             String libName = libs.get(i);
   9443             long version = (versions != null && versions.length == libNameCount)
   9444                     ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
   9445             PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
   9446             if (libPkg != null) {
   9447                 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
   9448             }
   9449         }
   9450     }
   9451 
   9452     private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
   9453         synchronized (mPackages) {
   9454             SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
   9455             if (libEntry != null) {
   9456                 return mPackages.get(libEntry.apk);
   9457             }
   9458             return null;
   9459         }
   9460     }
   9461 
   9462     private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
   9463         LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
   9464         if (versionedLib == null) {
   9465             return null;
   9466         }
   9467         return versionedLib.get(version);
   9468     }
   9469 
   9470     private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
   9471         LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
   9472                 pkg.staticSharedLibName);
   9473         if (versionedLib == null) {
   9474             return null;
   9475         }
   9476         long previousLibVersion = -1;
   9477         final int versionCount = versionedLib.size();
   9478         for (int i = 0; i < versionCount; i++) {
   9479             final long libVersion = versionedLib.keyAt(i);
   9480             if (libVersion < pkg.staticSharedLibVersion) {
   9481                 previousLibVersion = Math.max(previousLibVersion, libVersion);
   9482             }
   9483         }
   9484         if (previousLibVersion >= 0) {
   9485             return versionedLib.get(previousLibVersion);
   9486         }
   9487         return null;
   9488     }
   9489 
   9490     public void shutdown() {
   9491         mPackageUsage.writeNow(mPackages);
   9492         mCompilerStats.writeNow();
   9493         mDexManager.writePackageDexUsageNow();
   9494 
   9495         // This is the last chance to write out pending restriction settings
   9496         synchronized (mPackages) {
   9497             if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
   9498                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   9499                 for (int userId : mDirtyUsers) {
   9500                     mSettings.writePackageRestrictionsLPr(userId);
   9501                 }
   9502                 mDirtyUsers.clear();
   9503             }
   9504         }
   9505     }
   9506 
   9507     @Override
   9508     public void dumpProfiles(String packageName) {
   9509         PackageParser.Package pkg;
   9510         synchronized (mPackages) {
   9511             pkg = mPackages.get(packageName);
   9512             if (pkg == null) {
   9513                 throw new IllegalArgumentException("Unknown package: " + packageName);
   9514             }
   9515         }
   9516         /* Only the shell, root, or the app user should be able to dump profiles. */
   9517         int callingUid = Binder.getCallingUid();
   9518         if (callingUid != Process.SHELL_UID &&
   9519             callingUid != Process.ROOT_UID &&
   9520             callingUid != pkg.applicationInfo.uid) {
   9521             throw new SecurityException("dumpProfiles");
   9522         }
   9523 
   9524         synchronized (mInstallLock) {
   9525             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
   9526             mArtManagerService.dumpProfiles(pkg);
   9527             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9528         }
   9529     }
   9530 
   9531     @Override
   9532     public void forceDexOpt(String packageName) {
   9533         enforceSystemOrRoot("forceDexOpt");
   9534 
   9535         PackageParser.Package pkg;
   9536         synchronized (mPackages) {
   9537             pkg = mPackages.get(packageName);
   9538             if (pkg == null) {
   9539                 throw new IllegalArgumentException("Unknown package: " + packageName);
   9540             }
   9541         }
   9542 
   9543         synchronized (mInstallLock) {
   9544             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
   9545 
   9546             // Whoever is calling forceDexOpt wants a compiled package.
   9547             // Don't use profiles since that may cause compilation to be skipped.
   9548             final int res = performDexOptInternalWithDependenciesLI(
   9549                     pkg,
   9550                     new DexoptOptions(packageName,
   9551                             getDefaultCompilerFilter(),
   9552                             DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
   9553 
   9554             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9555             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
   9556                 throw new IllegalStateException("Failed to dexopt: " + res);
   9557             }
   9558         }
   9559     }
   9560 
   9561     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
   9562         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
   9563             Slog.w(TAG, "Unable to update from " + oldPkg.name
   9564                     + " to " + newPkg.packageName
   9565                     + ": old package not in system partition");
   9566             return false;
   9567         } else if (mPackages.get(oldPkg.name) != null) {
   9568             Slog.w(TAG, "Unable to update from " + oldPkg.name
   9569                     + " to " + newPkg.packageName
   9570                     + ": old package still exists");
   9571             return false;
   9572         }
   9573         return true;
   9574     }
   9575 
   9576     void removeCodePathLI(File codePath) {
   9577         if (codePath.isDirectory()) {
   9578             try {
   9579                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
   9580             } catch (InstallerException e) {
   9581                 Slog.w(TAG, "Failed to remove code path", e);
   9582             }
   9583         } else {
   9584             codePath.delete();
   9585         }
   9586     }
   9587 
   9588     private int[] resolveUserIds(int userId) {
   9589         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
   9590     }
   9591 
   9592     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
   9593         if (pkg == null) {
   9594             Slog.wtf(TAG, "Package was null!", new Throwable());
   9595             return;
   9596         }
   9597         clearAppDataLeafLIF(pkg, userId, flags);
   9598         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9599         for (int i = 0; i < childCount; i++) {
   9600             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
   9601         }
   9602 
   9603         clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
   9604     }
   9605 
   9606     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
   9607         final PackageSetting ps;
   9608         synchronized (mPackages) {
   9609             ps = mSettings.mPackages.get(pkg.packageName);
   9610         }
   9611         for (int realUserId : resolveUserIds(userId)) {
   9612             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
   9613             try {
   9614                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
   9615                         ceDataInode);
   9616             } catch (InstallerException e) {
   9617                 Slog.w(TAG, String.valueOf(e));
   9618             }
   9619         }
   9620     }
   9621 
   9622     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
   9623         if (pkg == null) {
   9624             Slog.wtf(TAG, "Package was null!", new Throwable());
   9625             return;
   9626         }
   9627         destroyAppDataLeafLIF(pkg, userId, flags);
   9628         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9629         for (int i = 0; i < childCount; i++) {
   9630             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
   9631         }
   9632     }
   9633 
   9634     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
   9635         final PackageSetting ps;
   9636         synchronized (mPackages) {
   9637             ps = mSettings.mPackages.get(pkg.packageName);
   9638         }
   9639         for (int realUserId : resolveUserIds(userId)) {
   9640             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
   9641             try {
   9642                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
   9643                         ceDataInode);
   9644             } catch (InstallerException e) {
   9645                 Slog.w(TAG, String.valueOf(e));
   9646             }
   9647             mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
   9648         }
   9649     }
   9650 
   9651     private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
   9652         if (pkg == null) {
   9653             Slog.wtf(TAG, "Package was null!", new Throwable());
   9654             return;
   9655         }
   9656         destroyAppProfilesLeafLIF(pkg);
   9657         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9658         for (int i = 0; i < childCount; i++) {
   9659             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
   9660         }
   9661     }
   9662 
   9663     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
   9664         try {
   9665             mInstaller.destroyAppProfiles(pkg.packageName);
   9666         } catch (InstallerException e) {
   9667             Slog.w(TAG, String.valueOf(e));
   9668         }
   9669     }
   9670 
   9671     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
   9672         if (pkg == null) {
   9673             Slog.wtf(TAG, "Package was null!", new Throwable());
   9674             return;
   9675         }
   9676         mArtManagerService.clearAppProfiles(pkg);
   9677         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9678         for (int i = 0; i < childCount; i++) {
   9679             mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
   9680         }
   9681     }
   9682 
   9683     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
   9684             long lastUpdateTime) {
   9685         // Set parent install/update time
   9686         PackageSetting ps = (PackageSetting) pkg.mExtras;
   9687         if (ps != null) {
   9688             ps.firstInstallTime = firstInstallTime;
   9689             ps.lastUpdateTime = lastUpdateTime;
   9690         }
   9691         // Set children install/update time
   9692         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9693         for (int i = 0; i < childCount; i++) {
   9694             PackageParser.Package childPkg = pkg.childPackages.get(i);
   9695             ps = (PackageSetting) childPkg.mExtras;
   9696             if (ps != null) {
   9697                 ps.firstInstallTime = firstInstallTime;
   9698                 ps.lastUpdateTime = lastUpdateTime;
   9699             }
   9700         }
   9701     }
   9702 
   9703     private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
   9704             SharedLibraryEntry file,
   9705             PackageParser.Package changingLib) {
   9706         if (file.path != null) {
   9707             usesLibraryFiles.add(file.path);
   9708             return;
   9709         }
   9710         PackageParser.Package p = mPackages.get(file.apk);
   9711         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
   9712             // If we are doing this while in the middle of updating a library apk,
   9713             // then we need to make sure to use that new apk for determining the
   9714             // dependencies here.  (We haven't yet finished committing the new apk
   9715             // to the package manager state.)
   9716             if (p == null || p.packageName.equals(changingLib.packageName)) {
   9717                 p = changingLib;
   9718             }
   9719         }
   9720         if (p != null) {
   9721             usesLibraryFiles.addAll(p.getAllCodePaths());
   9722             if (p.usesLibraryFiles != null) {
   9723                 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
   9724             }
   9725         }
   9726     }
   9727 
   9728     private void updateSharedLibrariesLPr(PackageParser.Package pkg,
   9729             PackageParser.Package changingLib) throws PackageManagerException {
   9730         if (pkg == null) {
   9731             return;
   9732         }
   9733         // The collection used here must maintain the order of addition (so
   9734         // that libraries are searched in the correct order) and must have no
   9735         // duplicates.
   9736         Set<String> usesLibraryFiles = null;
   9737         if (pkg.usesLibraries != null) {
   9738             usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
   9739                     null, null, pkg.packageName, changingLib, true,
   9740                     pkg.applicationInfo.targetSdkVersion, null);
   9741         }
   9742         if (pkg.usesStaticLibraries != null) {
   9743             usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
   9744                     pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
   9745                     pkg.packageName, changingLib, true,
   9746                     pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
   9747         }
   9748         if (pkg.usesOptionalLibraries != null) {
   9749             usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
   9750                     null, null, pkg.packageName, changingLib, false,
   9751                     pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
   9752         }
   9753         if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
   9754             pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
   9755         } else {
   9756             pkg.usesLibraryFiles = null;
   9757         }
   9758     }
   9759 
   9760     private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
   9761             @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
   9762             @NonNull String packageName, @Nullable PackageParser.Package changingLib,
   9763             boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
   9764             throws PackageManagerException {
   9765         final int libCount = requestedLibraries.size();
   9766         for (int i = 0; i < libCount; i++) {
   9767             final String libName = requestedLibraries.get(i);
   9768             final long libVersion = requiredVersions != null ? requiredVersions[i]
   9769                     : SharedLibraryInfo.VERSION_UNDEFINED;
   9770             final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
   9771             if (libEntry == null) {
   9772                 if (required) {
   9773                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   9774                             "Package " + packageName + " requires unavailable shared library "
   9775                                     + libName + "; failing!");
   9776                 } else if (DEBUG_SHARED_LIBRARIES) {
   9777                     Slog.i(TAG, "Package " + packageName
   9778                             + " desires unavailable shared library "
   9779                             + libName + "; ignoring!");
   9780                 }
   9781             } else {
   9782                 if (requiredVersions != null && requiredCertDigests != null) {
   9783                     if (libEntry.info.getLongVersion() != requiredVersions[i]) {
   9784                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   9785                             "Package " + packageName + " requires unavailable static shared"
   9786                                     + " library " + libName + " version "
   9787                                     + libEntry.info.getLongVersion() + "; failing!");
   9788                     }
   9789 
   9790                     PackageParser.Package libPkg = mPackages.get(libEntry.apk);
   9791                     if (libPkg == null) {
   9792                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   9793                                 "Package " + packageName + " requires unavailable static shared"
   9794                                         + " library; failing!");
   9795                     }
   9796 
   9797                     final String[] expectedCertDigests = requiredCertDigests[i];
   9798 
   9799 
   9800                     if (expectedCertDigests.length > 1) {
   9801 
   9802                         // For apps targeting O MR1 we require explicit enumeration of all certs.
   9803                         final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
   9804                                 ? PackageUtils.computeSignaturesSha256Digests(
   9805                                 libPkg.mSigningDetails.signatures)
   9806                                 : PackageUtils.computeSignaturesSha256Digests(
   9807                                         new Signature[]{libPkg.mSigningDetails.signatures[0]});
   9808 
   9809                         // Take a shortcut if sizes don't match. Note that if an app doesn't
   9810                         // target O we don't parse the "additional-certificate" tags similarly
   9811                         // how we only consider all certs only for apps targeting O (see above).
   9812                         // Therefore, the size check is safe to make.
   9813                         if (expectedCertDigests.length != libCertDigests.length) {
   9814                             throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   9815                                     "Package " + packageName + " requires differently signed" +
   9816                                             " static shared library; failing!");
   9817                         }
   9818 
   9819                         // Use a predictable order as signature order may vary
   9820                         Arrays.sort(libCertDigests);
   9821                         Arrays.sort(expectedCertDigests);
   9822 
   9823                         final int certCount = libCertDigests.length;
   9824                         for (int j = 0; j < certCount; j++) {
   9825                             if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
   9826                                 throw new PackageManagerException(
   9827                                         INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   9828                                         "Package " + packageName + " requires differently signed" +
   9829                                                 " static shared library; failing!");
   9830                             }
   9831                         }
   9832                     } else {
   9833 
   9834                         // lib signing cert could have rotated beyond the one expected, check to see
   9835                         // if the new one has been blessed by the old
   9836                         if (!libPkg.mSigningDetails.hasSha256Certificate(
   9837                                 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
   9838                             throw new PackageManagerException(
   9839                                     INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   9840                                     "Package " + packageName + " requires differently signed" +
   9841                                             " static shared library; failing!");
   9842                         }
   9843                     }
   9844                 }
   9845 
   9846                 if (outUsedLibraries == null) {
   9847                     // Use LinkedHashSet to preserve the order of files added to
   9848                     // usesLibraryFiles while eliminating duplicates.
   9849                     outUsedLibraries = new LinkedHashSet<>();
   9850                 }
   9851                 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
   9852             }
   9853         }
   9854         return outUsedLibraries;
   9855     }
   9856 
   9857     private static boolean hasString(List<String> list, List<String> which) {
   9858         if (list == null) {
   9859             return false;
   9860         }
   9861         for (int i=list.size()-1; i>=0; i--) {
   9862             for (int j=which.size()-1; j>=0; j--) {
   9863                 if (which.get(j).equals(list.get(i))) {
   9864                     return true;
   9865                 }
   9866             }
   9867         }
   9868         return false;
   9869     }
   9870 
   9871     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
   9872             PackageParser.Package changingPkg) {
   9873         ArrayList<PackageParser.Package> res = null;
   9874         for (PackageParser.Package pkg : mPackages.values()) {
   9875             if (changingPkg != null
   9876                     && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
   9877                     && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
   9878                     && !ArrayUtils.contains(pkg.usesStaticLibraries,
   9879                             changingPkg.staticSharedLibName)) {
   9880                 return null;
   9881             }
   9882             if (res == null) {
   9883                 res = new ArrayList<>();
   9884             }
   9885             res.add(pkg);
   9886             try {
   9887                 updateSharedLibrariesLPr(pkg, changingPkg);
   9888             } catch (PackageManagerException e) {
   9889                 // If a system app update or an app and a required lib missing we
   9890                 // delete the package and for updated system apps keep the data as
   9891                 // it is better for the user to reinstall than to be in an limbo
   9892                 // state. Also libs disappearing under an app should never happen
   9893                 // - just in case.
   9894                 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
   9895                     final int flags = pkg.isUpdatedSystemApp()
   9896                             ? PackageManager.DELETE_KEEP_DATA : 0;
   9897                     deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
   9898                             flags , null, true, null);
   9899                 }
   9900                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
   9901             }
   9902         }
   9903         return res;
   9904     }
   9905 
   9906     private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
   9907             final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
   9908             @Nullable UserHandle user) throws PackageManagerException {
   9909         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
   9910         // If the package has children and this is the first dive in the function
   9911         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
   9912         // whether all packages (parent and children) would be successfully scanned
   9913         // before the actual scan since scanning mutates internal state and we want
   9914         // to atomically install the package and its children.
   9915         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
   9916             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
   9917                 scanFlags |= SCAN_CHECK_ONLY;
   9918             }
   9919         } else {
   9920             scanFlags &= ~SCAN_CHECK_ONLY;
   9921         }
   9922 
   9923         final PackageParser.Package scannedPkg;
   9924         try {
   9925             // Scan the parent
   9926             scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
   9927             // Scan the children
   9928             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   9929             for (int i = 0; i < childCount; i++) {
   9930                 PackageParser.Package childPkg = pkg.childPackages.get(i);
   9931                 scanPackageNewLI(childPkg, parseFlags,
   9932                         scanFlags, currentTime, user);
   9933             }
   9934         } finally {
   9935             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   9936         }
   9937 
   9938         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
   9939             return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
   9940         }
   9941 
   9942         return scannedPkg;
   9943     }
   9944 
   9945     /** The result of a package scan. */
   9946     private static class ScanResult {
   9947         /** Whether or not the package scan was successful */
   9948         public final boolean success;
   9949         /**
   9950          * The final package settings. This may be the same object passed in
   9951          * the {@link ScanRequest}, but, with modified values.
   9952          */
   9953         @Nullable public final PackageSetting pkgSetting;
   9954         /** ABI code paths that have changed in the package scan */
   9955         @Nullable public final List<String> changedAbiCodePath;
   9956         public ScanResult(
   9957                 boolean success,
   9958                 @Nullable PackageSetting pkgSetting,
   9959                 @Nullable List<String> changedAbiCodePath) {
   9960             this.success = success;
   9961             this.pkgSetting = pkgSetting;
   9962             this.changedAbiCodePath = changedAbiCodePath;
   9963         }
   9964     }
   9965 
   9966     /** A package to be scanned */
   9967     private static class ScanRequest {
   9968         /** The parsed package */
   9969         @NonNull public final PackageParser.Package pkg;
   9970         /** The package this package replaces */
   9971         @Nullable public final PackageParser.Package oldPkg;
   9972         /** Shared user settings, if the package has a shared user */
   9973         @Nullable public final SharedUserSetting sharedUserSetting;
   9974         /**
   9975          * Package settings of the currently installed version.
   9976          * <p><em>IMPORTANT:</em> The contents of this object may be modified
   9977          * during scan.
   9978          */
   9979         @Nullable public final PackageSetting pkgSetting;
   9980         /** A copy of the settings for the currently installed version */
   9981         @Nullable public final PackageSetting oldPkgSetting;
   9982         /** Package settings for the disabled version on the /system partition */
   9983         @Nullable public final PackageSetting disabledPkgSetting;
   9984         /** Package settings for the installed version under its original package name */
   9985         @Nullable public final PackageSetting originalPkgSetting;
   9986         /** The real package name of a renamed application */
   9987         @Nullable public final String realPkgName;
   9988         public final @ParseFlags int parseFlags;
   9989         public final @ScanFlags int scanFlags;
   9990         /** The user for which the package is being scanned */
   9991         @Nullable public final UserHandle user;
   9992         /** Whether or not the platform package is being scanned */
   9993         public final boolean isPlatformPackage;
   9994         public ScanRequest(
   9995                 @NonNull PackageParser.Package pkg,
   9996                 @Nullable SharedUserSetting sharedUserSetting,
   9997                 @Nullable PackageParser.Package oldPkg,
   9998                 @Nullable PackageSetting pkgSetting,
   9999                 @Nullable PackageSetting disabledPkgSetting,
   10000                 @Nullable PackageSetting originalPkgSetting,
   10001                 @Nullable String realPkgName,
   10002                 @ParseFlags int parseFlags,
   10003                 @ScanFlags int scanFlags,
   10004                 boolean isPlatformPackage,
   10005                 @Nullable UserHandle user) {
   10006             this.pkg = pkg;
   10007             this.oldPkg = oldPkg;
   10008             this.pkgSetting = pkgSetting;
   10009             this.sharedUserSetting = sharedUserSetting;
   10010             this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
   10011             this.disabledPkgSetting = disabledPkgSetting;
   10012             this.originalPkgSetting = originalPkgSetting;
   10013             this.realPkgName = realPkgName;
   10014             this.parseFlags = parseFlags;
   10015             this.scanFlags = scanFlags;
   10016             this.isPlatformPackage = isPlatformPackage;
   10017             this.user = user;
   10018         }
   10019     }
   10020 
   10021     /**
   10022      * Returns the actual scan flags depending upon the state of the other settings.
   10023      * <p>Updated system applications will not have the following flags set
   10024      * by default and need to be adjusted after the fact:
   10025      * <ul>
   10026      * <li>{@link #SCAN_AS_SYSTEM}</li>
   10027      * <li>{@link #SCAN_AS_PRIVILEGED}</li>
   10028      * <li>{@link #SCAN_AS_OEM}</li>
   10029      * <li>{@link #SCAN_AS_VENDOR}</li>
   10030      * <li>{@link #SCAN_AS_PRODUCT}</li>
   10031      * <li>{@link #SCAN_AS_INSTANT_APP}</li>
   10032      * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
   10033      * </ul>
   10034      */
   10035     private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
   10036             PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
   10037             PackageParser.Package pkg) {
   10038         if (disabledPkgSetting != null) {
   10039             // updated system application, must at least have SCAN_AS_SYSTEM
   10040             scanFlags |= SCAN_AS_SYSTEM;
   10041             if ((disabledPkgSetting.pkgPrivateFlags
   10042                     & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
   10043                 scanFlags |= SCAN_AS_PRIVILEGED;
   10044             }
   10045             if ((disabledPkgSetting.pkgPrivateFlags
   10046                     & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
   10047                 scanFlags |= SCAN_AS_OEM;
   10048             }
   10049             if ((disabledPkgSetting.pkgPrivateFlags
   10050                     & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
   10051                 scanFlags |= SCAN_AS_VENDOR;
   10052             }
   10053             if ((disabledPkgSetting.pkgPrivateFlags
   10054                     & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
   10055                 scanFlags |= SCAN_AS_PRODUCT;
   10056             }
   10057         }
   10058         if (pkgSetting != null) {
   10059             final int userId = ((user == null) ? 0 : user.getIdentifier());
   10060             if (pkgSetting.getInstantApp(userId)) {
   10061                 scanFlags |= SCAN_AS_INSTANT_APP;
   10062             }
   10063             if (pkgSetting.getVirtulalPreload(userId)) {
   10064                 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
   10065             }
   10066         }
   10067 
   10068         // Scan as privileged apps that share a user with a priv-app.
   10069         final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
   10070                 && SystemProperties.getInt("ro.vndk.version", 28) < 28;
   10071         if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
   10072                 && !pkg.isPrivileged()
   10073                 && (pkg.mSharedUserId != null)
   10074                 && !skipVendorPrivilegeScan) {
   10075             SharedUserSetting sharedUserSetting = null;
   10076             try {
   10077                 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
   10078             } catch (PackageManagerException ignore) {}
   10079             if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
   10080                 // Exempt SharedUsers signed with the platform key.
   10081                 // TODO(b/72378145) Fix this exemption. Force signature apps
   10082                 // to whitelist their privileged permissions just like other
   10083                 // priv-apps.
   10084                 synchronized (mPackages) {
   10085                     PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
   10086                     if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
   10087                                 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
   10088                         scanFlags |= SCAN_AS_PRIVILEGED;
   10089                     }
   10090                 }
   10091             }
   10092         }
   10093 
   10094         return scanFlags;
   10095     }
   10096 
   10097     // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
   10098     // the results / removing app data needs to be moved up a level to the callers of this
   10099     // method. Also, we need to solve the problem of potentially creating a new shared user
   10100     // setting. That can probably be done later and patch things up after the fact.
   10101     @GuardedBy("mInstallLock")
   10102     private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
   10103             final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
   10104             @Nullable UserHandle user) throws PackageManagerException {
   10105 
   10106         final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
   10107         final String realPkgName = getRealPackageName(pkg, renamedPkgName);
   10108         if (realPkgName != null) {
   10109             ensurePackageRenamed(pkg, renamedPkgName);
   10110         }
   10111         final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
   10112         final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
   10113         final PackageSetting disabledPkgSetting =
   10114                 mSettings.getDisabledSystemPkgLPr(pkg.packageName);
   10115 
   10116         if (mTransferedPackages.contains(pkg.packageName)) {
   10117             Slog.w(TAG, "Package " + pkg.packageName
   10118                     + " was transferred to another, but its .apk remains");
   10119         }
   10120 
   10121         scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
   10122         synchronized (mPackages) {
   10123             applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
   10124             assertPackageIsValid(pkg, parseFlags, scanFlags);
   10125 
   10126             SharedUserSetting sharedUserSetting = null;
   10127             if (pkg.mSharedUserId != null) {
   10128                 // SIDE EFFECTS; may potentially allocate a new shared user
   10129                 sharedUserSetting = mSettings.getSharedUserLPw(
   10130                         pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
   10131                 if (DEBUG_PACKAGE_SCANNING) {
   10132                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
   10133                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
   10134                                 + " (uid=" + sharedUserSetting.userId + "):"
   10135                                 + " packages=" + sharedUserSetting.packages);
   10136                 }
   10137             }
   10138 
   10139             boolean scanSucceeded = false;
   10140             try {
   10141                 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
   10142                         pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
   10143                         originalPkgSetting, realPkgName, parseFlags, scanFlags,
   10144                         (pkg == mPlatformPackage), user);
   10145                 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
   10146                 if (result.success) {
   10147                     commitScanResultsLocked(request, result);
   10148                 }
   10149                 scanSucceeded = true;
   10150             } finally {
   10151                   if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
   10152                       // DELETE_DATA_ON_FAILURES is only used by frozen paths
   10153                       destroyAppDataLIF(pkg, UserHandle.USER_ALL,
   10154                               StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
   10155                       destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
   10156                   }
   10157             }
   10158         }
   10159         return pkg;
   10160     }
   10161 
   10162     /**
   10163      * Commits the package scan and modifies system state.
   10164      * <p><em>WARNING:</em> The method may throw an excpetion in the middle
   10165      * of committing the package, leaving the system in an inconsistent state.
   10166      * This needs to be fixed so, once we get to this point, no errors are
   10167      * possible and the system is not left in an inconsistent state.
   10168      */
   10169     @GuardedBy("mPackages")
   10170     private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
   10171             throws PackageManagerException {
   10172         final PackageParser.Package pkg = request.pkg;
   10173         final PackageParser.Package oldPkg = request.oldPkg;
   10174         final @ParseFlags int parseFlags = request.parseFlags;
   10175         final @ScanFlags int scanFlags = request.scanFlags;
   10176         final PackageSetting oldPkgSetting = request.oldPkgSetting;
   10177         final PackageSetting originalPkgSetting = request.originalPkgSetting;
   10178         final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
   10179         final UserHandle user = request.user;
   10180         final String realPkgName = request.realPkgName;
   10181         final PackageSetting pkgSetting = result.pkgSetting;
   10182         final List<String> changedAbiCodePath = result.changedAbiCodePath;
   10183         final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
   10184 
   10185         if (newPkgSettingCreated) {
   10186             if (originalPkgSetting != null) {
   10187                 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
   10188             }
   10189             // THROWS: when we can't allocate a user id. add call to check if there's
   10190             // enough space to ensure we won't throw; otherwise, don't modify state
   10191             mSettings.addUserToSettingLPw(pkgSetting);
   10192 
   10193             if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
   10194                 mTransferedPackages.add(originalPkgSetting.name);
   10195             }
   10196         }
   10197         // TODO(toddke): Consider a method specifically for modifying the Package object
   10198         // post scan; or, moving this stuff out of the Package object since it has nothing
   10199         // to do with the package on disk.
   10200         // We need to have this here because addUserToSettingLPw() is sometimes responsible
   10201         // for creating the application ID. If we did this earlier, we would be saving the
   10202         // correct ID.
   10203         pkg.applicationInfo.uid = pkgSetting.appId;
   10204 
   10205         mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
   10206 
   10207         if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
   10208             mTransferedPackages.add(pkg.packageName);
   10209         }
   10210 
   10211         // THROWS: when requested libraries that can't be found. it only changes
   10212         // the state of the passed in pkg object, so, move to the top of the method
   10213         // and allow it to abort
   10214         if ((scanFlags & SCAN_BOOTING) == 0
   10215                 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   10216             // Check all shared libraries and map to their actual file path.
   10217             // We only do this here for apps not on a system dir, because those
   10218             // are the only ones that can fail an install due to this.  We
   10219             // will take care of the system apps by updating all of their
   10220             // library paths after the scan is done. Also during the initial
   10221             // scan don't update any libs as we do this wholesale after all
   10222             // apps are scanned to avoid dependency based scanning.
   10223             updateSharedLibrariesLPr(pkg, null);
   10224         }
   10225 
   10226         // All versions of a static shared library are referenced with the same
   10227         // package name. Internally, we use a synthetic package name to allow
   10228         // multiple versions of the same shared library to be installed. So,
   10229         // we need to generate the synthetic package name of the latest shared
   10230         // library in order to compare signatures.
   10231         PackageSetting signatureCheckPs = pkgSetting;
   10232         if (pkg.applicationInfo.isStaticSharedLibrary()) {
   10233             SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
   10234             if (libraryEntry != null) {
   10235                 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
   10236             }
   10237         }
   10238 
   10239         final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   10240         if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
   10241             if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
   10242                 // We just determined the app is signed correctly, so bring
   10243                 // over the latest parsed certs.
   10244                 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
   10245             } else {
   10246                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   10247                     throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
   10248                             "Package " + pkg.packageName + " upgrade keys do not match the "
   10249                                     + "previously installed version");
   10250                 } else {
   10251                     pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
   10252                     String msg = "System package " + pkg.packageName
   10253                             + " signature changed; retaining data.";
   10254                     reportSettingsProblem(Log.WARN, msg);
   10255                 }
   10256             }
   10257         } else {
   10258             try {
   10259                 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
   10260                 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
   10261                 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
   10262                         pkg.mSigningDetails, compareCompat, compareRecover);
   10263                 // The new KeySets will be re-added later in the scanning process.
   10264                 if (compatMatch) {
   10265                     synchronized (mPackages) {
   10266                         ksms.removeAppKeySetDataLPw(pkg.packageName);
   10267                     }
   10268                 }
   10269                 // We just determined the app is signed correctly, so bring
   10270                 // over the latest parsed certs.
   10271                 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
   10272 
   10273 
   10274                 // if this is is a sharedUser, check to see if the new package is signed by a newer
   10275                 // signing certificate than the existing one, and if so, copy over the new details
   10276                 if (signatureCheckPs.sharedUser != null) {
   10277                     if (pkg.mSigningDetails.hasAncestor(
   10278                                 signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
   10279                         signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
   10280                     }
   10281                     if (signatureCheckPs.sharedUser.signaturesChanged == null) {
   10282                         signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
   10283                     }
   10284                 }
   10285             } catch (PackageManagerException e) {
   10286                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   10287                     throw e;
   10288                 }
   10289                 // The signature has changed, but this package is in the system
   10290                 // image...  let's recover!
   10291                 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
   10292 
   10293                 // If the system app is part of a shared user we allow that shared user to change
   10294                 // signatures as well as part of an OTA. We still need to verify that the signatures
   10295                 // are consistent within the shared user for a given boot, so only allow updating
   10296                 // the signatures on the first package scanned for the shared user (i.e. if the
   10297                 // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
   10298                 if (signatureCheckPs.sharedUser != null) {
   10299                     if (signatureCheckPs.sharedUser.signaturesChanged != null &&
   10300                         compareSignatures(
   10301                             signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
   10302                             pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
   10303                         throw new PackageManagerException(
   10304                                 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
   10305                                 "Signature mismatch for shared user: " + pkgSetting.sharedUser);
   10306                     }
   10307 
   10308                     signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
   10309                     signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
   10310                 }
   10311                 // File a report about this.
   10312                 String msg = "System package " + pkg.packageName
   10313                         + " signature changed; retaining data.";
   10314                 reportSettingsProblem(Log.WARN, msg);
   10315             } catch (IllegalArgumentException e) {
   10316 
   10317                 // should never happen: certs matched when checking, but not when comparing
   10318                 // old to new for sharedUser
   10319                 throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
   10320                         "Signing certificates comparison made on incomparable signing details"
   10321                         + " but somehow passed verifySignatures!");
   10322             }
   10323         }
   10324 
   10325         if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
   10326             // This package wants to adopt ownership of permissions from
   10327             // another package.
   10328             for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
   10329                 final String origName = pkg.mAdoptPermissions.get(i);
   10330                 final PackageSetting orig = mSettings.getPackageLPr(origName);
   10331                 if (orig != null) {
   10332                     if (verifyPackageUpdateLPr(orig, pkg)) {
   10333                         Slog.i(TAG, "Adopting permissions from " + origName + " to "
   10334                                 + pkg.packageName);
   10335                         mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
   10336                     }
   10337                 }
   10338             }
   10339         }
   10340 
   10341         if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
   10342             for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
   10343                 final String codePathString = changedAbiCodePath.get(i);
   10344                 try {
   10345                     mInstaller.rmdex(codePathString,
   10346                             getDexCodeInstructionSet(getPreferredInstructionSet()));
   10347                 } catch (InstallerException ignored) {
   10348                 }
   10349             }
   10350         }
   10351 
   10352         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
   10353             if (oldPkgSetting != null) {
   10354                 synchronized (mPackages) {
   10355                     mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
   10356                 }
   10357             }
   10358         } else {
   10359             final int userId = user == null ? 0 : user.getIdentifier();
   10360             // Modify state for the given package setting
   10361             commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
   10362                     (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
   10363             if (pkgSetting.getInstantApp(userId)) {
   10364                 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
   10365             }
   10366         }
   10367     }
   10368 
   10369     /**
   10370      * Returns the "real" name of the package.
   10371      * <p>This may differ from the package's actual name if the application has already
   10372      * been installed under one of this package's original names.
   10373      */
   10374     private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
   10375             @Nullable String renamedPkgName) {
   10376         if (isPackageRenamed(pkg, renamedPkgName)) {
   10377             return pkg.mRealPackage;
   10378         }
   10379         return null;
   10380     }
   10381 
   10382     /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
   10383     private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
   10384             @Nullable String renamedPkgName) {
   10385         return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
   10386     }
   10387 
   10388     /**
   10389      * Returns the original package setting.
   10390      * <p>A package can migrate its name during an update. In this scenario, a package
   10391      * designates a set of names that it considers as one of its original names.
   10392      * <p>An original package must be signed identically and it must have the same
   10393      * shared user [if any].
   10394      */
   10395     @GuardedBy("mPackages")
   10396     private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
   10397             @Nullable String renamedPkgName) {
   10398         if (!isPackageRenamed(pkg, renamedPkgName)) {
   10399             return null;
   10400         }
   10401         for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
   10402             final PackageSetting originalPs =
   10403                     mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
   10404             if (originalPs != null) {
   10405                 // the package is already installed under its original name...
   10406                 // but, should we use it?
   10407                 if (!verifyPackageUpdateLPr(originalPs, pkg)) {
   10408                     // the new package is incompatible with the original
   10409                     continue;
   10410                 } else if (originalPs.sharedUser != null) {
   10411                     if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
   10412                         // the shared user id is incompatible with the original
   10413                         Slog.w(TAG, "Unable to migrate data from " + originalPs.name
   10414                                 + " to " + pkg.packageName + ": old uid "
   10415                                 + originalPs.sharedUser.name
   10416                                 + " differs from " + pkg.mSharedUserId);
   10417                         continue;
   10418                     }
   10419                     // TODO: Add case when shared user id is added [b/28144775]
   10420                 } else {
   10421                     if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
   10422                             + pkg.packageName + " to old name " + originalPs.name);
   10423                 }
   10424                 return originalPs;
   10425             }
   10426         }
   10427         return null;
   10428     }
   10429 
   10430     /**
   10431      * Renames the package if it was installed under a different name.
   10432      * <p>When we've already installed the package under an original name, update
   10433      * the new package so we can continue to have the old name.
   10434      */
   10435     private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
   10436             @NonNull String renamedPackageName) {
   10437         if (pkg.mOriginalPackages == null
   10438                 || !pkg.mOriginalPackages.contains(renamedPackageName)
   10439                 || pkg.packageName.equals(renamedPackageName)) {
   10440             return;
   10441         }
   10442         pkg.setPackageName(renamedPackageName);
   10443     }
   10444 
   10445     /**
   10446      * Just scans the package without any side effects.
   10447      * <p>Not entirely true at the moment. There is still one side effect -- this
   10448      * method potentially modifies a live {@link PackageSetting} object representing
   10449      * the package being scanned. This will be resolved in the future.
   10450      *
   10451      * @param request Information about the package to be scanned
   10452      * @param isUnderFactoryTest Whether or not the device is under factory test
   10453      * @param currentTime The current time, in millis
   10454      * @return The results of the scan
   10455      */
   10456     @GuardedBy("mInstallLock")
   10457     private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
   10458             boolean isUnderFactoryTest, long currentTime)
   10459                     throws PackageManagerException {
   10460         final PackageParser.Package pkg = request.pkg;
   10461         PackageSetting pkgSetting = request.pkgSetting;
   10462         final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
   10463         final PackageSetting originalPkgSetting = request.originalPkgSetting;
   10464         final @ParseFlags int parseFlags = request.parseFlags;
   10465         final @ScanFlags int scanFlags = request.scanFlags;
   10466         final String realPkgName = request.realPkgName;
   10467         final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
   10468         final UserHandle user = request.user;
   10469         final boolean isPlatformPackage = request.isPlatformPackage;
   10470 
   10471         List<String> changedAbiCodePath = null;
   10472 
   10473         if (DEBUG_PACKAGE_SCANNING) {
   10474             if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
   10475                 Log.d(TAG, "Scanning package " + pkg.packageName);
   10476         }
   10477 
   10478         DexManager.maybeLogUnexpectedPackageDetails(pkg);
   10479 
   10480         // Initialize package source and resource directories
   10481         final File scanFile = new File(pkg.codePath);
   10482         final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
   10483         final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
   10484 
   10485         // We keep references to the derived CPU Abis from settings in oder to reuse
   10486         // them in the case where we're not upgrading or booting for the first time.
   10487         String primaryCpuAbiFromSettings = null;
   10488         String secondaryCpuAbiFromSettings = null;
   10489         boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
   10490 
   10491         if (!needToDeriveAbi) {
   10492             if (pkgSetting != null) {
   10493                 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
   10494                 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
   10495             } else {
   10496                 // Re-scanning a system package after uninstalling updates; need to derive ABI
   10497                 needToDeriveAbi = true;
   10498             }
   10499         }
   10500 
   10501         if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
   10502             PackageManagerService.reportSettingsProblem(Log.WARN,
   10503                     "Package " + pkg.packageName + " shared user changed from "
   10504                             + (pkgSetting.sharedUser != null
   10505                             ? pkgSetting.sharedUser.name : "<nothing>")
   10506                             + " to "
   10507                             + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
   10508                             + "; replacing with new");
   10509             pkgSetting = null;
   10510         }
   10511 
   10512         String[] usesStaticLibraries = null;
   10513         if (pkg.usesStaticLibraries != null) {
   10514             usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
   10515             pkg.usesStaticLibraries.toArray(usesStaticLibraries);
   10516         }
   10517         final boolean createNewPackage = (pkgSetting == null);
   10518         if (createNewPackage) {
   10519             final String parentPackageName = (pkg.parentPackage != null)
   10520                     ? pkg.parentPackage.packageName : null;
   10521             final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
   10522             final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
   10523             // REMOVE SharedUserSetting from method; update in a separate call
   10524             pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
   10525                     disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
   10526                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
   10527                     pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
   10528                     pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
   10529                     user, true /*allowInstall*/, instantApp, virtualPreload,
   10530                     parentPackageName, pkg.getChildPackageNames(),
   10531                     UserManagerService.getInstance(), usesStaticLibraries,
   10532                     pkg.usesStaticLibrariesVersions);
   10533         } else {
   10534             // REMOVE SharedUserSetting from method; update in a separate call.
   10535             //
   10536             // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
   10537             // secondaryCpuAbi are not known at this point so we always update them
   10538             // to null here, only to reset them at a later point.
   10539             Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
   10540                     destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
   10541                     pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
   10542                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
   10543                     pkg.getChildPackageNames(), UserManagerService.getInstance(),
   10544                     usesStaticLibraries, pkg.usesStaticLibrariesVersions);
   10545         }
   10546         if (createNewPackage && originalPkgSetting != null) {
   10547             // This is the initial transition from the original package, so,
   10548             // fix up the new package's name now. We must do this after looking
   10549             // up the package under its new name, so getPackageLP takes care of
   10550             // fiddling things correctly.
   10551             pkg.setPackageName(originalPkgSetting.name);
   10552 
   10553             // File a report about this.
   10554             String msg = "New package " + pkgSetting.realName
   10555                     + " renamed to replace old package " + pkgSetting.name;
   10556             reportSettingsProblem(Log.WARN, msg);
   10557         }
   10558 
   10559         final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
   10560         // for existing packages, change the install state; but, only if it's explicitly specified
   10561         if (!createNewPackage) {
   10562             final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
   10563             final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
   10564             setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
   10565         }
   10566 
   10567         if (disabledPkgSetting != null) {
   10568             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
   10569         }
   10570 
   10571         // Apps which share a sharedUserId must be placed in the same selinux domain. If this
   10572         // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
   10573         // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
   10574         // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
   10575         // least restrictive selinux domain.
   10576         // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
   10577         // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
   10578         // ensures that all packages continue to run in the same selinux domain.
   10579         final int targetSdkVersion =
   10580             ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
   10581             sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
   10582         // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
   10583         // They currently can be if the sharedUser apps are signed with the platform key.
   10584         final boolean isPrivileged = (sharedUserSetting != null) ?
   10585             sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
   10586 
   10587         pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
   10588                 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
   10589         pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
   10590                 userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
   10591 
   10592         pkg.mExtras = pkgSetting;
   10593         pkg.applicationInfo.processName = fixProcessName(
   10594                 pkg.applicationInfo.packageName,
   10595                 pkg.applicationInfo.processName);
   10596 
   10597         if (!isPlatformPackage) {
   10598             // Get all of our default paths setup
   10599             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
   10600         }
   10601 
   10602         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
   10603 
   10604         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
   10605             if (needToDeriveAbi) {
   10606                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
   10607                 final boolean extractNativeLibs = !pkg.isLibrary();
   10608                 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
   10609                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   10610 
   10611                 // Some system apps still use directory structure for native libraries
   10612                 // in which case we might end up not detecting abi solely based on apk
   10613                 // structure. Try to detect abi based on directory structure.
   10614                 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
   10615                         pkg.applicationInfo.primaryCpuAbi == null) {
   10616                     setBundledAppAbisAndRoots(pkg, pkgSetting);
   10617                     setNativeLibraryPaths(pkg, sAppLib32InstallDir);
   10618                 }
   10619             } else {
   10620                 // This is not a first boot or an upgrade, don't bother deriving the
   10621                 // ABI during the scan. Instead, trust the value that was stored in the
   10622                 // package setting.
   10623                 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
   10624                 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
   10625 
   10626                 setNativeLibraryPaths(pkg, sAppLib32InstallDir);
   10627 
   10628                 if (DEBUG_ABI_SELECTION) {
   10629                     Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
   10630                             pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
   10631                             pkg.applicationInfo.secondaryCpuAbi);
   10632                 }
   10633             }
   10634         } else {
   10635             if ((scanFlags & SCAN_MOVE) != 0) {
   10636                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
   10637                 // but we already have this packages package info in the PackageSetting. We just
   10638                 // use that and derive the native library path based on the new codepath.
   10639                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
   10640                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
   10641             }
   10642 
   10643             // Set native library paths again. For moves, the path will be updated based on the
   10644             // ABIs we've determined above. For non-moves, the path will be updated based on the
   10645             // ABIs we determined during compilation, but the path will depend on the final
   10646             // package path (after the rename away from the stage path).
   10647             setNativeLibraryPaths(pkg, sAppLib32InstallDir);
   10648         }
   10649 
   10650         // This is a special case for the "system" package, where the ABI is
   10651         // dictated by the zygote configuration (and init.rc). We should keep track
   10652         // of this ABI so that we can deal with "normal" applications that run under
   10653         // the same UID correctly.
   10654         if (isPlatformPackage) {
   10655             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
   10656                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
   10657         }
   10658 
   10659         // If there's a mismatch between the abi-override in the package setting
   10660         // and the abiOverride specified for the install. Warn about this because we
   10661         // would've already compiled the app without taking the package setting into
   10662         // account.
   10663         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
   10664             if (cpuAbiOverride == null && pkg.packageName != null) {
   10665                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
   10666                         " for package " + pkg.packageName);
   10667             }
   10668         }
   10669 
   10670         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
   10671         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
   10672         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
   10673 
   10674         // Copy the derived override back to the parsed package, so that we can
   10675         // update the package settings accordingly.
   10676         pkg.cpuAbiOverride = cpuAbiOverride;
   10677 
   10678         if (DEBUG_ABI_SELECTION) {
   10679             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
   10680                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
   10681                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
   10682         }
   10683 
   10684         // Push the derived path down into PackageSettings so we know what to
   10685         // clean up at uninstall time.
   10686         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
   10687 
   10688         if (DEBUG_ABI_SELECTION) {
   10689             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
   10690                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
   10691                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
   10692         }
   10693 
   10694         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
   10695             // We don't do this here during boot because we can do it all
   10696             // at once after scanning all existing packages.
   10697             //
   10698             // We also do this *before* we perform dexopt on this package, so that
   10699             // we can avoid redundant dexopts, and also to make sure we've got the
   10700             // code and package path correct.
   10701             changedAbiCodePath =
   10702                     adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
   10703         }
   10704 
   10705         if (isUnderFactoryTest && pkg.requestedPermissions.contains(
   10706                 android.Manifest.permission.FACTORY_TEST)) {
   10707             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
   10708         }
   10709 
   10710         if (isSystemApp(pkg)) {
   10711             pkgSetting.isOrphaned = true;
   10712         }
   10713 
   10714         // Take care of first install / last update times.
   10715         final long scanFileTime = getLastModifiedTime(pkg);
   10716         if (currentTime != 0) {
   10717             if (pkgSetting.firstInstallTime == 0) {
   10718                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
   10719             } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
   10720                 pkgSetting.lastUpdateTime = currentTime;
   10721             }
   10722         } else if (pkgSetting.firstInstallTime == 0) {
   10723             // We need *something*.  Take time time stamp of the file.
   10724             pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
   10725         } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
   10726             if (scanFileTime != pkgSetting.timeStamp) {
   10727                 // A package on the system image has changed; consider this
   10728                 // to be an update.
   10729                 pkgSetting.lastUpdateTime = scanFileTime;
   10730             }
   10731         }
   10732         pkgSetting.setTimeStamp(scanFileTime);
   10733 
   10734         pkgSetting.pkg = pkg;
   10735         pkgSetting.pkgFlags = pkg.applicationInfo.flags;
   10736         if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
   10737             pkgSetting.versionCode = pkg.getLongVersionCode();
   10738         }
   10739         // Update volume if needed
   10740         final String volumeUuid = pkg.applicationInfo.volumeUuid;
   10741         if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
   10742             Slog.i(PackageManagerService.TAG,
   10743                     "Update" + (pkgSetting.isSystem() ? " system" : "")
   10744                     + " package " + pkg.packageName
   10745                     + " volume from " + pkgSetting.volumeUuid
   10746                     + " to " + volumeUuid);
   10747             pkgSetting.volumeUuid = volumeUuid;
   10748         }
   10749 
   10750         return new ScanResult(true, pkgSetting, changedAbiCodePath);
   10751     }
   10752 
   10753     /**
   10754      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
   10755      */
   10756     private static boolean apkHasCode(String fileName) {
   10757         StrictJarFile jarFile = null;
   10758         try {
   10759             jarFile = new StrictJarFile(fileName,
   10760                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
   10761             return jarFile.findEntry("classes.dex") != null;
   10762         } catch (IOException ignore) {
   10763         } finally {
   10764             try {
   10765                 if (jarFile != null) {
   10766                     jarFile.close();
   10767                 }
   10768             } catch (IOException ignore) {}
   10769         }
   10770         return false;
   10771     }
   10772 
   10773     /**
   10774      * Enforces code policy for the package. This ensures that if an APK has
   10775      * declared hasCode="true" in its manifest that the APK actually contains
   10776      * code.
   10777      *
   10778      * @throws PackageManagerException If bytecode could not be found when it should exist
   10779      */
   10780     private static void assertCodePolicy(PackageParser.Package pkg)
   10781             throws PackageManagerException {
   10782         final boolean shouldHaveCode =
   10783                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
   10784         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
   10785             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
   10786                     "Package " + pkg.baseCodePath + " code is missing");
   10787         }
   10788 
   10789         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
   10790             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
   10791                 final boolean splitShouldHaveCode =
   10792                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
   10793                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
   10794                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
   10795                             "Package " + pkg.splitCodePaths[i] + " code is missing");
   10796                 }
   10797             }
   10798         }
   10799     }
   10800 
   10801     /**
   10802      * Applies policy to the parsed package based upon the given policy flags.
   10803      * Ensures the package is in a good state.
   10804      * <p>
   10805      * Implementation detail: This method must NOT have any side effect. It would
   10806      * ideally be static, but, it requires locks to read system state.
   10807      */
   10808     private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
   10809             final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
   10810         if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
   10811             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
   10812             if (pkg.applicationInfo.isDirectBootAware()) {
   10813                 // we're direct boot aware; set for all components
   10814                 for (PackageParser.Service s : pkg.services) {
   10815                     s.info.encryptionAware = s.info.directBootAware = true;
   10816                 }
   10817                 for (PackageParser.Provider p : pkg.providers) {
   10818                     p.info.encryptionAware = p.info.directBootAware = true;
   10819                 }
   10820                 for (PackageParser.Activity a : pkg.activities) {
   10821                     a.info.encryptionAware = a.info.directBootAware = true;
   10822                 }
   10823                 for (PackageParser.Activity r : pkg.receivers) {
   10824                     r.info.encryptionAware = r.info.directBootAware = true;
   10825                 }
   10826             }
   10827             if (compressedFileExists(pkg.codePath)) {
   10828                 pkg.isStub = true;
   10829             }
   10830         } else {
   10831             // non system apps can't be flagged as core
   10832             pkg.coreApp = false;
   10833             // clear flags not applicable to regular apps
   10834             pkg.applicationInfo.flags &=
   10835                     ~ApplicationInfo.FLAG_PERSISTENT;
   10836             pkg.applicationInfo.privateFlags &=
   10837                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
   10838             pkg.applicationInfo.privateFlags &=
   10839                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
   10840             // cap permission priorities
   10841             if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
   10842                 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
   10843                     pkg.permissionGroups.get(i).info.priority = 0;
   10844                 }
   10845             }
   10846         }
   10847         if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
   10848             // clear protected broadcasts
   10849             pkg.protectedBroadcasts = null;
   10850             // ignore export request for single user receivers
   10851             if (pkg.receivers != null) {
   10852                 for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
   10853                     final PackageParser.Activity receiver = pkg.receivers.get(i);
   10854                     if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
   10855                         receiver.info.exported = false;
   10856                     }
   10857                 }
   10858             }
   10859             // ignore export request for single user services
   10860             if (pkg.services != null) {
   10861                 for (int i = pkg.services.size() - 1; i >= 0; --i) {
   10862                     final PackageParser.Service service = pkg.services.get(i);
   10863                     if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
   10864                         service.info.exported = false;
   10865                     }
   10866                 }
   10867             }
   10868             // ignore export request for single user providers
   10869             if (pkg.providers != null) {
   10870                 for (int i = pkg.providers.size() - 1; i >= 0; --i) {
   10871                     final PackageParser.Provider provider = pkg.providers.get(i);
   10872                     if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
   10873                         provider.info.exported = false;
   10874                     }
   10875                 }
   10876             }
   10877         }
   10878 
   10879         if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
   10880             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
   10881         }
   10882 
   10883         if ((scanFlags & SCAN_AS_OEM) != 0) {
   10884             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
   10885         }
   10886 
   10887         if ((scanFlags & SCAN_AS_VENDOR) != 0) {
   10888             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
   10889         }
   10890 
   10891         if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
   10892             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
   10893         }
   10894 
   10895         // Check if the package is signed with the same key as the platform package.
   10896         if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
   10897                 (platformPkg != null && compareSignatures(
   10898                         platformPkg.mSigningDetails.signatures,
   10899                         pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
   10900             pkg.applicationInfo.privateFlags |=
   10901                 ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
   10902         }
   10903 
   10904         if (!isSystemApp(pkg)) {
   10905             // Only system apps can use these features.
   10906             pkg.mOriginalPackages = null;
   10907             pkg.mRealPackage = null;
   10908             pkg.mAdoptPermissions = null;
   10909         }
   10910     }
   10911 
   10912     private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
   10913             throws PackageManagerException {
   10914         if (object == null) {
   10915             throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
   10916         }
   10917         return object;
   10918     }
   10919 
   10920     /**
   10921      * Asserts the parsed package is valid according to the given policy. If the
   10922      * package is invalid, for whatever reason, throws {@link PackageManagerException}.
   10923      * <p>
   10924      * Implementation detail: This method must NOT have any side effects. It would
   10925      * ideally be static, but, it requires locks to read system state.
   10926      *
   10927      * @throws PackageManagerException If the package fails any of the validation checks
   10928      */
   10929     private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
   10930             final @ScanFlags int scanFlags)
   10931                     throws PackageManagerException {
   10932         if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
   10933             assertCodePolicy(pkg);
   10934         }
   10935 
   10936         if (pkg.applicationInfo.getCodePath() == null ||
   10937                 pkg.applicationInfo.getResourcePath() == null) {
   10938             // Bail out. The resource and code paths haven't been set.
   10939             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
   10940                     "Code and resource paths haven't been set correctly");
   10941         }
   10942 
   10943         // Make sure we're not adding any bogus keyset info
   10944         final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   10945         ksms.assertScannedPackageValid(pkg);
   10946 
   10947         synchronized (mPackages) {
   10948             // The special "android" package can only be defined once
   10949             if (pkg.packageName.equals("android")) {
   10950                 if (mAndroidApplication != null) {
   10951                     Slog.w(TAG, "*************************************************");
   10952                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
   10953                     Slog.w(TAG, " codePath=" + pkg.codePath);
   10954                     Slog.w(TAG, "*************************************************");
   10955                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
   10956                             "Core android package being redefined.  Skipping.");
   10957                 }
   10958             }
   10959 
   10960             // A package name must be unique; don't allow duplicates
   10961             if (mPackages.containsKey(pkg.packageName)) {
   10962                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
   10963                         "Application package " + pkg.packageName
   10964                         + " already installed.  Skipping duplicate.");
   10965             }
   10966 
   10967             if (pkg.applicationInfo.isStaticSharedLibrary()) {
   10968                 // Static libs have a synthetic package name containing the version
   10969                 // but we still want the base name to be unique.
   10970                 if (mPackages.containsKey(pkg.manifestPackageName)) {
   10971                     throw new PackageManagerException(
   10972                             "Duplicate static shared lib provider package");
   10973                 }
   10974 
   10975                 // Static shared libraries should have at least O target SDK
   10976                 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
   10977                     throw new PackageManagerException(
   10978                             "Packages declaring static-shared libs must target O SDK or higher");
   10979                 }
   10980 
   10981                 // Package declaring static a shared lib cannot be instant apps
   10982                 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
   10983                     throw new PackageManagerException(
   10984                             "Packages declaring static-shared libs cannot be instant apps");
   10985                 }
   10986 
   10987                 // Package declaring static a shared lib cannot be renamed since the package
   10988                 // name is synthetic and apps can't code around package manager internals.
   10989                 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
   10990                     throw new PackageManagerException(
   10991                             "Packages declaring static-shared libs cannot be renamed");
   10992                 }
   10993 
   10994                 // Package declaring static a shared lib cannot declare child packages
   10995                 if (!ArrayUtils.isEmpty(pkg.childPackages)) {
   10996                     throw new PackageManagerException(
   10997                             "Packages declaring static-shared libs cannot have child packages");
   10998                 }
   10999 
   11000                 // Package declaring static a shared lib cannot declare dynamic libs
   11001                 if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
   11002                     throw new PackageManagerException(
   11003                             "Packages declaring static-shared libs cannot declare dynamic libs");
   11004                 }
   11005 
   11006                 // Package declaring static a shared lib cannot declare shared users
   11007                 if (pkg.mSharedUserId != null) {
   11008                     throw new PackageManagerException(
   11009                             "Packages declaring static-shared libs cannot declare shared users");
   11010                 }
   11011 
   11012                 // Static shared libs cannot declare activities
   11013                 if (!pkg.activities.isEmpty()) {
   11014                     throw new PackageManagerException(
   11015                             "Static shared libs cannot declare activities");
   11016                 }
   11017 
   11018                 // Static shared libs cannot declare services
   11019                 if (!pkg.services.isEmpty()) {
   11020                     throw new PackageManagerException(
   11021                             "Static shared libs cannot declare services");
   11022                 }
   11023 
   11024                 // Static shared libs cannot declare providers
   11025                 if (!pkg.providers.isEmpty()) {
   11026                     throw new PackageManagerException(
   11027                             "Static shared libs cannot declare content providers");
   11028                 }
   11029 
   11030                 // Static shared libs cannot declare receivers
   11031                 if (!pkg.receivers.isEmpty()) {
   11032                     throw new PackageManagerException(
   11033                             "Static shared libs cannot declare broadcast receivers");
   11034                 }
   11035 
   11036                 // Static shared libs cannot declare permission groups
   11037                 if (!pkg.permissionGroups.isEmpty()) {
   11038                     throw new PackageManagerException(
   11039                             "Static shared libs cannot declare permission groups");
   11040                 }
   11041 
   11042                 // Static shared libs cannot declare permissions
   11043                 if (!pkg.permissions.isEmpty()) {
   11044                     throw new PackageManagerException(
   11045                             "Static shared libs cannot declare permissions");
   11046                 }
   11047 
   11048                 // Static shared libs cannot declare protected broadcasts
   11049                 if (pkg.protectedBroadcasts != null) {
   11050                     throw new PackageManagerException(
   11051                             "Static shared libs cannot declare protected broadcasts");
   11052                 }
   11053 
   11054                 // Static shared libs cannot be overlay targets
   11055                 if (pkg.mOverlayTarget != null) {
   11056                     throw new PackageManagerException(
   11057                             "Static shared libs cannot be overlay targets");
   11058                 }
   11059 
   11060                 // The version codes must be ordered as lib versions
   11061                 long minVersionCode = Long.MIN_VALUE;
   11062                 long maxVersionCode = Long.MAX_VALUE;
   11063 
   11064                 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
   11065                         pkg.staticSharedLibName);
   11066                 if (versionedLib != null) {
   11067                     final int versionCount = versionedLib.size();
   11068                     for (int i = 0; i < versionCount; i++) {
   11069                         SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
   11070                         final long libVersionCode = libInfo.getDeclaringPackage()
   11071                                 .getLongVersionCode();
   11072                         if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
   11073                             minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
   11074                         } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
   11075                             maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
   11076                         } else {
   11077                             minVersionCode = maxVersionCode = libVersionCode;
   11078                             break;
   11079                         }
   11080                     }
   11081                 }
   11082                 if (pkg.getLongVersionCode() < minVersionCode
   11083                         || pkg.getLongVersionCode() > maxVersionCode) {
   11084                     throw new PackageManagerException("Static shared"
   11085                             + " lib version codes must be ordered as lib versions");
   11086                 }
   11087             }
   11088 
   11089             // Only privileged apps and updated privileged apps can add child packages.
   11090             if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
   11091                 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
   11092                     throw new PackageManagerException("Only privileged apps can add child "
   11093                             + "packages. Ignoring package " + pkg.packageName);
   11094                 }
   11095                 final int childCount = pkg.childPackages.size();
   11096                 for (int i = 0; i < childCount; i++) {
   11097                     PackageParser.Package childPkg = pkg.childPackages.get(i);
   11098                     if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
   11099                             childPkg.packageName)) {
   11100                         throw new PackageManagerException("Can't override child of "
   11101                                 + "another disabled app. Ignoring package " + pkg.packageName);
   11102                     }
   11103                 }
   11104             }
   11105 
   11106             // If we're only installing presumed-existing packages, require that the
   11107             // scanned APK is both already known and at the path previously established
   11108             // for it.  Previously unknown packages we pick up normally, but if we have an
   11109             // a priori expectation about this package's install presence, enforce it.
   11110             // With a singular exception for new system packages. When an OTA contains
   11111             // a new system package, we allow the codepath to change from a system location
   11112             // to the user-installed location. If we don't allow this change, any newer,
   11113             // user-installed version of the application will be ignored.
   11114             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
   11115                 if (mExpectingBetter.containsKey(pkg.packageName)) {
   11116                     logCriticalInfo(Log.WARN,
   11117                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
   11118                 } else {
   11119                     PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
   11120                     if (known != null) {
   11121                         if (DEBUG_PACKAGE_SCANNING) {
   11122                             Log.d(TAG, "Examining " + pkg.codePath
   11123                                     + " and requiring known paths " + known.codePathString
   11124                                     + " & " + known.resourcePathString);
   11125                         }
   11126                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
   11127                                 || !pkg.applicationInfo.getResourcePath().equals(
   11128                                         known.resourcePathString)) {
   11129                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
   11130                                     "Application package " + pkg.packageName
   11131                                     + " found at " + pkg.applicationInfo.getCodePath()
   11132                                     + " but expected at " + known.codePathString
   11133                                     + "; ignoring.");
   11134                         }
   11135                     } else {
   11136                         throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
   11137                                 "Application package " + pkg.packageName
   11138                                 + " not found; ignoring.");
   11139                     }
   11140                 }
   11141             }
   11142 
   11143             // Verify that this new package doesn't have any content providers
   11144             // that conflict with existing packages.  Only do this if the
   11145             // package isn't already installed, since we don't want to break
   11146             // things that are installed.
   11147             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
   11148                 final int N = pkg.providers.size();
   11149                 int i;
   11150                 for (i=0; i<N; i++) {
   11151                     PackageParser.Provider p = pkg.providers.get(i);
   11152                     if (p.info.authority != null) {
   11153                         String names[] = p.info.authority.split(";");
   11154                         for (int j = 0; j < names.length; j++) {
   11155                             if (mProvidersByAuthority.containsKey(names[j])) {
   11156                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
   11157                                 final String otherPackageName =
   11158                                         ((other != null && other.getComponentName() != null) ?
   11159                                                 other.getComponentName().getPackageName() : "?");
   11160                                 throw new PackageManagerException(
   11161                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
   11162                                         "Can't install because provider name " + names[j]
   11163                                                 + " (in package " + pkg.applicationInfo.packageName
   11164                                                 + ") is already used by " + otherPackageName);
   11165                             }
   11166                         }
   11167                     }
   11168                 }
   11169             }
   11170 
   11171             // Verify that packages sharing a user with a privileged app are marked as privileged.
   11172             if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
   11173                 SharedUserSetting sharedUserSetting = null;
   11174                 try {
   11175                     sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
   11176                 } catch (PackageManagerException ignore) {}
   11177                 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
   11178                     // Exempt SharedUsers signed with the platform key.
   11179                     PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
   11180                     if ((platformPkgSetting.signatures.mSigningDetails
   11181                             != PackageParser.SigningDetails.UNKNOWN)
   11182                             && (compareSignatures(
   11183                                     platformPkgSetting.signatures.mSigningDetails.signatures,
   11184                                     pkg.mSigningDetails.signatures)
   11185                                             != PackageManager.SIGNATURE_MATCH)) {
   11186                         throw new PackageManagerException("Apps that share a user with a " +
   11187                                 "privileged app must themselves be marked as privileged. " +
   11188                                 pkg.packageName + " shares privileged user " +
   11189                                 pkg.mSharedUserId + ".");
   11190                     }
   11191                 }
   11192             }
   11193 
   11194             // Apply policies specific for runtime resource overlays (RROs).
   11195             if (pkg.mOverlayTarget != null) {
   11196                 // System overlays have some restrictions on their use of the 'static' state.
   11197                 if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
   11198                     // We are scanning a system overlay. This can be the first scan of the
   11199                     // system/vendor/oem partition, or an update to the system overlay.
   11200                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   11201                         // This must be an update to a system overlay.
   11202                         final PackageSetting previousPkg = assertNotNull(
   11203                                 mSettings.getPackageLPr(pkg.packageName),
   11204                                 "previous package state not present");
   11205 
   11206                         // previousPkg.pkg may be null: the package will be not be scanned if the
   11207                         // package manager knows there is a newer version on /data.
   11208                         // TODO[b/79435695]: Find a better way to keep track of the "static"
   11209                         // property for RROs instead of having to parse packages on /system
   11210                         PackageParser.Package ppkg = previousPkg.pkg;
   11211                         if (ppkg == null) {
   11212                             try {
   11213                                 final PackageParser pp = new PackageParser();
   11214                                 ppkg = pp.parsePackage(previousPkg.codePath,
   11215                                         parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR);
   11216                             } catch (PackageParserException e) {
   11217                                 Slog.w(TAG, "failed to parse " + previousPkg.codePath, e);
   11218                             }
   11219                         }
   11220 
   11221                         // Static overlays cannot be updated.
   11222                         if (ppkg != null && ppkg.mOverlayIsStatic) {
   11223                             throw new PackageManagerException("Overlay " + pkg.packageName +
   11224                                     " is static and cannot be upgraded.");
   11225                         // Non-static overlays cannot be converted to static overlays.
   11226                         } else if (pkg.mOverlayIsStatic) {
   11227                             throw new PackageManagerException("Overlay " + pkg.packageName +
   11228                                     " cannot be upgraded into a static overlay.");
   11229                         }
   11230                     }
   11231                 } else {
   11232                     // The overlay is a non-system overlay. Non-system overlays cannot be static.
   11233                     if (pkg.mOverlayIsStatic) {
   11234                         throw new PackageManagerException("Overlay " + pkg.packageName +
   11235                                 " is static but not pre-installed.");
   11236                     }
   11237 
   11238                     // The only case where we allow installation of a non-system overlay is when
   11239                     // its signature is signed with the platform certificate.
   11240                     PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
   11241                     if ((platformPkgSetting.signatures.mSigningDetails
   11242                             != PackageParser.SigningDetails.UNKNOWN)
   11243                             && (compareSignatures(
   11244                                     platformPkgSetting.signatures.mSigningDetails.signatures,
   11245                                     pkg.mSigningDetails.signatures)
   11246                                             != PackageManager.SIGNATURE_MATCH)) {
   11247                         throw new PackageManagerException("Overlay " + pkg.packageName +
   11248                                 " must be signed with the platform certificate.");
   11249                     }
   11250                 }
   11251             }
   11252         }
   11253     }
   11254 
   11255     private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
   11256             int type, String declaringPackageName, long declaringVersionCode) {
   11257         LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
   11258         if (versionedLib == null) {
   11259             versionedLib = new LongSparseArray<>();
   11260             mSharedLibraries.put(name, versionedLib);
   11261             if (type == SharedLibraryInfo.TYPE_STATIC) {
   11262                 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
   11263             }
   11264         } else if (versionedLib.indexOfKey(version) >= 0) {
   11265             return false;
   11266         }
   11267         SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
   11268                 version, type, declaringPackageName, declaringVersionCode);
   11269         versionedLib.put(version, libEntry);
   11270         return true;
   11271     }
   11272 
   11273     private boolean removeSharedLibraryLPw(String name, long version) {
   11274         LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
   11275         if (versionedLib == null) {
   11276             return false;
   11277         }
   11278         final int libIdx = versionedLib.indexOfKey(version);
   11279         if (libIdx < 0) {
   11280             return false;
   11281         }
   11282         SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
   11283         versionedLib.remove(version);
   11284         if (versionedLib.size() <= 0) {
   11285             mSharedLibraries.remove(name);
   11286             if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
   11287                 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
   11288                         .getPackageName());
   11289             }
   11290         }
   11291         return true;
   11292     }
   11293 
   11294     /**
   11295      * Adds a scanned package to the system. When this method is finished, the package will
   11296      * be available for query, resolution, etc...
   11297      */
   11298     private void commitPackageSettings(PackageParser.Package pkg,
   11299             @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
   11300             final @ScanFlags int scanFlags, boolean chatty) {
   11301         final String pkgName = pkg.packageName;
   11302         if (mCustomResolverComponentName != null &&
   11303                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
   11304             setUpCustomResolverActivity(pkg);
   11305         }
   11306 
   11307         if (pkg.packageName.equals("android")) {
   11308             synchronized (mPackages) {
   11309                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
   11310                     // Set up information for our fall-back user intent resolution activity.
   11311                     mPlatformPackage = pkg;
   11312                     pkg.mVersionCode = mSdkVersion;
   11313                     pkg.mVersionCodeMajor = 0;
   11314                     mAndroidApplication = pkg.applicationInfo;
   11315                     if (!mResolverReplaced) {
   11316                         mResolveActivity.applicationInfo = mAndroidApplication;
   11317                         mResolveActivity.name = ResolverActivity.class.getName();
   11318                         mResolveActivity.packageName = mAndroidApplication.packageName;
   11319                         mResolveActivity.processName = "system:ui";
   11320                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
   11321                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
   11322                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
   11323                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
   11324                         mResolveActivity.exported = true;
   11325                         mResolveActivity.enabled = true;
   11326                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
   11327                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
   11328                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
   11329                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
   11330                                 | ActivityInfo.CONFIG_ORIENTATION
   11331                                 | ActivityInfo.CONFIG_KEYBOARD
   11332                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
   11333                         mResolveInfo.activityInfo = mResolveActivity;
   11334                         mResolveInfo.priority = 0;
   11335                         mResolveInfo.preferredOrder = 0;
   11336                         mResolveInfo.match = 0;
   11337                         mResolveComponentName = new ComponentName(
   11338                                 mAndroidApplication.packageName, mResolveActivity.name);
   11339                     }
   11340                 }
   11341             }
   11342         }
   11343 
   11344         ArrayList<PackageParser.Package> clientLibPkgs = null;
   11345         // writer
   11346         synchronized (mPackages) {
   11347             boolean hasStaticSharedLibs = false;
   11348 
   11349             // Any app can add new static shared libraries
   11350             if (pkg.staticSharedLibName != null) {
   11351                 // Static shared libs don't allow renaming as they have synthetic package
   11352                 // names to allow install of multiple versions, so use name from manifest.
   11353                 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
   11354                         pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
   11355                         pkg.manifestPackageName, pkg.getLongVersionCode())) {
   11356                     hasStaticSharedLibs = true;
   11357                 } else {
   11358                     Slog.w(TAG, "Package " + pkg.packageName + " library "
   11359                                 + pkg.staticSharedLibName + " already exists; skipping");
   11360                 }
   11361                 // Static shared libs cannot be updated once installed since they
   11362                 // use synthetic package name which includes the version code, so
   11363                 // not need to update other packages's shared lib dependencies.
   11364             }
   11365 
   11366             if (!hasStaticSharedLibs
   11367                     && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   11368                 // Only system apps can add new dynamic shared libraries.
   11369                 if (pkg.libraryNames != null) {
   11370                     for (int i = 0; i < pkg.libraryNames.size(); i++) {
   11371                         String name = pkg.libraryNames.get(i);
   11372                         boolean allowed = false;
   11373                         if (pkg.isUpdatedSystemApp()) {
   11374                             // New library entries can only be added through the
   11375                             // system image.  This is important to get rid of a lot
   11376                             // of nasty edge cases: for example if we allowed a non-
   11377                             // system update of the app to add a library, then uninstalling
   11378                             // the update would make the library go away, and assumptions
   11379                             // we made such as through app install filtering would now
   11380                             // have allowed apps on the device which aren't compatible
   11381                             // with it.  Better to just have the restriction here, be
   11382                             // conservative, and create many fewer cases that can negatively
   11383                             // impact the user experience.
   11384                             final PackageSetting sysPs = mSettings
   11385                                     .getDisabledSystemPkgLPr(pkg.packageName);
   11386                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
   11387                                 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
   11388                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
   11389                                         allowed = true;
   11390                                         break;
   11391                                     }
   11392                                 }
   11393                             }
   11394                         } else {
   11395                             allowed = true;
   11396                         }
   11397                         if (allowed) {
   11398                             if (!addSharedLibraryLPw(null, pkg.packageName, name,
   11399                                     SharedLibraryInfo.VERSION_UNDEFINED,
   11400                                     SharedLibraryInfo.TYPE_DYNAMIC,
   11401                                     pkg.packageName, pkg.getLongVersionCode())) {
   11402                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
   11403                                         + name + " already exists; skipping");
   11404                             }
   11405                         } else {
   11406                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
   11407                                     + name + " that is not declared on system image; skipping");
   11408                         }
   11409                     }
   11410 
   11411                     if ((scanFlags & SCAN_BOOTING) == 0) {
   11412                         // If we are not booting, we need to update any applications
   11413                         // that are clients of our shared library.  If we are booting,
   11414                         // this will all be done once the scan is complete.
   11415                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
   11416                     }
   11417                 }
   11418             }
   11419         }
   11420 
   11421         if ((scanFlags & SCAN_BOOTING) != 0) {
   11422             // No apps can run during boot scan, so they don't need to be frozen
   11423         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
   11424             // Caller asked to not kill app, so it's probably not frozen
   11425         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
   11426             // Caller asked us to ignore frozen check for some reason; they
   11427             // probably didn't know the package name
   11428         } else {
   11429             // We're doing major surgery on this package, so it better be frozen
   11430             // right now to keep it from launching
   11431             checkPackageFrozen(pkgName);
   11432         }
   11433 
   11434         // Also need to kill any apps that are dependent on the library.
   11435         if (clientLibPkgs != null) {
   11436             for (int i=0; i<clientLibPkgs.size(); i++) {
   11437                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
   11438                 killApplication(clientPkg.applicationInfo.packageName,
   11439                         clientPkg.applicationInfo.uid, "update lib");
   11440             }
   11441         }
   11442 
   11443         // writer
   11444         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
   11445 
   11446         synchronized (mPackages) {
   11447             // We don't expect installation to fail beyond this point
   11448 
   11449             // Add the new setting to mSettings
   11450             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
   11451             // Add the new setting to mPackages
   11452             mPackages.put(pkg.applicationInfo.packageName, pkg);
   11453             // Make sure we don't accidentally delete its data.
   11454             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
   11455             while (iter.hasNext()) {
   11456                 PackageCleanItem item = iter.next();
   11457                 if (pkgName.equals(item.packageName)) {
   11458                     iter.remove();
   11459                 }
   11460             }
   11461 
   11462             // Add the package's KeySets to the global KeySetManagerService
   11463             KeySetManagerService ksms = mSettings.mKeySetManagerService;
   11464             ksms.addScannedPackageLPw(pkg);
   11465 
   11466             int N = pkg.providers.size();
   11467             StringBuilder r = null;
   11468             int i;
   11469             for (i=0; i<N; i++) {
   11470                 PackageParser.Provider p = pkg.providers.get(i);
   11471                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
   11472                         p.info.processName);
   11473                 mProviders.addProvider(p);
   11474                 p.syncable = p.info.isSyncable;
   11475                 if (p.info.authority != null) {
   11476                     String names[] = p.info.authority.split(";");
   11477                     p.info.authority = null;
   11478                     for (int j = 0; j < names.length; j++) {
   11479                         if (j == 1 && p.syncable) {
   11480                             // We only want the first authority for a provider to possibly be
   11481                             // syncable, so if we already added this provider using a different
   11482                             // authority clear the syncable flag. We copy the provider before
   11483                             // changing it because the mProviders object contains a reference
   11484                             // to a provider that we don't want to change.
   11485                             // Only do this for the second authority since the resulting provider
   11486                             // object can be the same for all future authorities for this provider.
   11487                             p = new PackageParser.Provider(p);
   11488                             p.syncable = false;
   11489                         }
   11490                         if (!mProvidersByAuthority.containsKey(names[j])) {
   11491                             mProvidersByAuthority.put(names[j], p);
   11492                             if (p.info.authority == null) {
   11493                                 p.info.authority = names[j];
   11494                             } else {
   11495                                 p.info.authority = p.info.authority + ";" + names[j];
   11496                             }
   11497                             if (DEBUG_PACKAGE_SCANNING) {
   11498                                 if (chatty)
   11499                                     Log.d(TAG, "Registered content provider: " + names[j]
   11500                                             + ", className = " + p.info.name + ", isSyncable = "
   11501                                             + p.info.isSyncable);
   11502                             }
   11503                         } else {
   11504                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
   11505                             Slog.w(TAG, "Skipping provider name " + names[j] +
   11506                                     " (in package " + pkg.applicationInfo.packageName +
   11507                                     "): name already used by "
   11508                                     + ((other != null && other.getComponentName() != null)
   11509                                             ? other.getComponentName().getPackageName() : "?"));
   11510                         }
   11511                     }
   11512                 }
   11513                 if (chatty) {
   11514                     if (r == null) {
   11515                         r = new StringBuilder(256);
   11516                     } else {
   11517                         r.append(' ');
   11518                     }
   11519                     r.append(p.info.name);
   11520                 }
   11521             }
   11522             if (r != null) {
   11523                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
   11524             }
   11525 
   11526             N = pkg.services.size();
   11527             r = null;
   11528             for (i=0; i<N; i++) {
   11529                 PackageParser.Service s = pkg.services.get(i);
   11530                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
   11531                         s.info.processName);
   11532                 mServices.addService(s);
   11533                 if (chatty) {
   11534                     if (r == null) {
   11535                         r = new StringBuilder(256);
   11536                     } else {
   11537                         r.append(' ');
   11538                     }
   11539                     r.append(s.info.name);
   11540                 }
   11541             }
   11542             if (r != null) {
   11543                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
   11544             }
   11545 
   11546             N = pkg.receivers.size();
   11547             r = null;
   11548             for (i=0; i<N; i++) {
   11549                 PackageParser.Activity a = pkg.receivers.get(i);
   11550                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
   11551                         a.info.processName);
   11552                 mReceivers.addActivity(a, "receiver");
   11553                 if (chatty) {
   11554                     if (r == null) {
   11555                         r = new StringBuilder(256);
   11556                     } else {
   11557                         r.append(' ');
   11558                     }
   11559                     r.append(a.info.name);
   11560                 }
   11561             }
   11562             if (r != null) {
   11563                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
   11564             }
   11565 
   11566             N = pkg.activities.size();
   11567             r = null;
   11568             for (i=0; i<N; i++) {
   11569                 PackageParser.Activity a = pkg.activities.get(i);
   11570                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
   11571                         a.info.processName);
   11572                 mActivities.addActivity(a, "activity");
   11573                 if (chatty) {
   11574                     if (r == null) {
   11575                         r = new StringBuilder(256);
   11576                     } else {
   11577                         r.append(' ');
   11578                     }
   11579                     r.append(a.info.name);
   11580                 }
   11581             }
   11582             if (r != null) {
   11583                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
   11584             }
   11585 
   11586             // Don't allow ephemeral applications to define new permissions groups.
   11587             if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
   11588                 Slog.w(TAG, "Permission groups from package " + pkg.packageName
   11589                         + " ignored: instant apps cannot define new permission groups.");
   11590             } else {
   11591                 mPermissionManager.addAllPermissionGroups(pkg, chatty);
   11592             }
   11593 
   11594             // Don't allow ephemeral applications to define new permissions.
   11595             if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
   11596                 Slog.w(TAG, "Permissions from package " + pkg.packageName
   11597                         + " ignored: instant apps cannot define new permissions.");
   11598             } else {
   11599                 mPermissionManager.addAllPermissions(pkg, chatty);
   11600             }
   11601 
   11602             N = pkg.instrumentation.size();
   11603             r = null;
   11604             for (i=0; i<N; i++) {
   11605                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
   11606                 a.info.packageName = pkg.applicationInfo.packageName;
   11607                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
   11608                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
   11609                 a.info.splitNames = pkg.splitNames;
   11610                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
   11611                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
   11612                 a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
   11613                 a.info.dataDir = pkg.applicationInfo.dataDir;
   11614                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
   11615                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
   11616                 a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
   11617                 a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
   11618                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
   11619                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
   11620                 mInstrumentation.put(a.getComponentName(), a);
   11621                 if (chatty) {
   11622                     if (r == null) {
   11623                         r = new StringBuilder(256);
   11624                     } else {
   11625                         r.append(' ');
   11626                     }
   11627                     r.append(a.info.name);
   11628                 }
   11629             }
   11630             if (r != null) {
   11631                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
   11632             }
   11633 
   11634             if (pkg.protectedBroadcasts != null) {
   11635                 N = pkg.protectedBroadcasts.size();
   11636                 synchronized (mProtectedBroadcasts) {
   11637                     for (i = 0; i < N; i++) {
   11638                         mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
   11639                     }
   11640                 }
   11641             }
   11642 
   11643             if (oldPkg != null) {
   11644                 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
   11645                 // revoke callbacks from this method might need to kill apps which need the
   11646                 // mPackages lock on a different thread. This would dead lock.
   11647                 //
   11648                 // Hence create a copy of all package names and pass it into
   11649                 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
   11650                 // revoked. If a new package is added before the async code runs the permission
   11651                 // won't be granted yet, hence new packages are no problem.
   11652                 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
   11653 
   11654                 AsyncTask.execute(() ->
   11655                         mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
   11656                                 allPackageNames, mPermissionCallback));
   11657             }
   11658         }
   11659 
   11660         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   11661     }
   11662 
   11663     /**
   11664      * Derive the ABI of a non-system package located at {@code scanFile}. This information
   11665      * is derived purely on the basis of the contents of {@code scanFile} and
   11666      * {@code cpuAbiOverride}.
   11667      *
   11668      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
   11669      */
   11670     private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
   11671             boolean extractLibs)
   11672                     throws PackageManagerException {
   11673         // Give ourselves some initial paths; we'll come back for another
   11674         // pass once we've determined ABI below.
   11675         setNativeLibraryPaths(pkg, sAppLib32InstallDir);
   11676 
   11677         // We would never need to extract libs for forward-locked and external packages,
   11678         // since the container service will do it for us. We shouldn't attempt to
   11679         // extract libs from system app when it was not updated.
   11680         if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
   11681                 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
   11682             extractLibs = false;
   11683         }
   11684 
   11685         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
   11686         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
   11687 
   11688         NativeLibraryHelper.Handle handle = null;
   11689         try {
   11690             handle = NativeLibraryHelper.Handle.create(pkg);
   11691             // TODO(multiArch): This can be null for apps that didn't go through the
   11692             // usual installation process. We can calculate it again, like we
   11693             // do during install time.
   11694             //
   11695             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
   11696             // unnecessary.
   11697             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
   11698 
   11699             // Null out the abis so that they can be recalculated.
   11700             pkg.applicationInfo.primaryCpuAbi = null;
   11701             pkg.applicationInfo.secondaryCpuAbi = null;
   11702             if (isMultiArch(pkg.applicationInfo)) {
   11703                 // Warn if we've set an abiOverride for multi-lib packages..
   11704                 // By definition, we need to copy both 32 and 64 bit libraries for
   11705                 // such packages.
   11706                 if (pkg.cpuAbiOverride != null
   11707                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
   11708                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
   11709                 }
   11710 
   11711                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
   11712                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
   11713                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
   11714                     if (extractLibs) {
   11715                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
   11716                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
   11717                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
   11718                                 useIsaSpecificSubdirs);
   11719                     } else {
   11720                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
   11721                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
   11722                     }
   11723                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   11724                 }
   11725 
   11726                 // Shared library native code should be in the APK zip aligned
   11727                 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
   11728                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
   11729                             "Shared library native lib extraction not supported");
   11730                 }
   11731 
   11732                 maybeThrowExceptionForMultiArchCopy(
   11733                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
   11734 
   11735                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
   11736                     if (extractLibs) {
   11737                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
   11738                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
   11739                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
   11740                                 useIsaSpecificSubdirs);
   11741                     } else {
   11742                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
   11743                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
   11744                     }
   11745                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   11746                 }
   11747 
   11748                 maybeThrowExceptionForMultiArchCopy(
   11749                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
   11750 
   11751                 if (abi64 >= 0) {
   11752                     // Shared library native libs should be in the APK zip aligned
   11753                     if (extractLibs && pkg.isLibrary()) {
   11754                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
   11755                                 "Shared library native lib extraction not supported");
   11756                     }
   11757                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
   11758                 }
   11759 
   11760                 if (abi32 >= 0) {
   11761                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
   11762                     if (abi64 >= 0) {
   11763                         if (pkg.use32bitAbi) {
   11764                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
   11765                             pkg.applicationInfo.primaryCpuAbi = abi;
   11766                         } else {
   11767                             pkg.applicationInfo.secondaryCpuAbi = abi;
   11768                         }
   11769                     } else {
   11770                         pkg.applicationInfo.primaryCpuAbi = abi;
   11771                     }
   11772                 }
   11773             } else {
   11774                 String[] abiList = (cpuAbiOverride != null) ?
   11775                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
   11776 
   11777                 // Enable gross and lame hacks for apps that are built with old
   11778                 // SDK tools. We must scan their APKs for renderscript bitcode and
   11779                 // not launch them if it's present. Don't bother checking on devices
   11780                 // that don't have 64 bit support.
   11781                 boolean needsRenderScriptOverride = false;
   11782                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
   11783                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
   11784                     abiList = Build.SUPPORTED_32_BIT_ABIS;
   11785                     needsRenderScriptOverride = true;
   11786                 }
   11787 
   11788                 final int copyRet;
   11789                 if (extractLibs) {
   11790                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
   11791                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
   11792                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
   11793                 } else {
   11794                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
   11795                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
   11796                 }
   11797                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   11798 
   11799                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
   11800                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
   11801                             "Error unpackaging native libs for app, errorCode=" + copyRet);
   11802                 }
   11803 
   11804                 if (copyRet >= 0) {
   11805                     // Shared libraries that have native libs must be multi-architecture
   11806                     if (pkg.isLibrary()) {
   11807                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
   11808                                 "Shared library with native libs must be multiarch");
   11809                     }
   11810                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
   11811                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
   11812                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
   11813                 } else if (needsRenderScriptOverride) {
   11814                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
   11815                 }
   11816             }
   11817         } catch (IOException ioe) {
   11818             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
   11819         } finally {
   11820             IoUtils.closeQuietly(handle);
   11821         }
   11822 
   11823         // Now that we've calculated the ABIs and determined if it's an internal app,
   11824         // we will go ahead and populate the nativeLibraryPath.
   11825         setNativeLibraryPaths(pkg, sAppLib32InstallDir);
   11826     }
   11827 
   11828     /**
   11829      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
   11830      * i.e, so that all packages can be run inside a single process if required.
   11831      *
   11832      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
   11833      * this function will either try and make the ABI for all packages in {@code packagesForUser}
   11834      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
   11835      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
   11836      * updating a package that belongs to a shared user.
   11837      *
   11838      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
   11839      * adds unnecessary complexity.
   11840      */
   11841     private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
   11842             Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
   11843         List<String> changedAbiCodePath = null;
   11844         String requiredInstructionSet = null;
   11845         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
   11846             requiredInstructionSet = VMRuntime.getInstructionSet(
   11847                      scannedPackage.applicationInfo.primaryCpuAbi);
   11848         }
   11849 
   11850         PackageSetting requirer = null;
   11851         for (PackageSetting ps : packagesForUser) {
   11852             // If packagesForUser contains scannedPackage, we skip it. This will happen
   11853             // when scannedPackage is an update of an existing package. Without this check,
   11854             // we will never be able to change the ABI of any package belonging to a shared
   11855             // user, even if it's compatible with other packages.
   11856             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
   11857                 if (ps.primaryCpuAbiString == null) {
   11858                     continue;
   11859                 }
   11860 
   11861                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
   11862                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
   11863                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
   11864                     // this but there's not much we can do.
   11865                     String errorMessage = "Instruction set mismatch, "
   11866                             + ((requirer == null) ? "[caller]" : requirer)
   11867                             + " requires " + requiredInstructionSet + " whereas " + ps
   11868                             + " requires " + instructionSet;
   11869                     Slog.w(TAG, errorMessage);
   11870                 }
   11871 
   11872                 if (requiredInstructionSet == null) {
   11873                     requiredInstructionSet = instructionSet;
   11874                     requirer = ps;
   11875                 }
   11876             }
   11877         }
   11878 
   11879         if (requiredInstructionSet != null) {
   11880             String adjustedAbi;
   11881             if (requirer != null) {
   11882                 // requirer != null implies that either scannedPackage was null or that scannedPackage
   11883                 // did not require an ABI, in which case we have to adjust scannedPackage to match
   11884                 // the ABI of the set (which is the same as requirer's ABI)
   11885                 adjustedAbi = requirer.primaryCpuAbiString;
   11886                 if (scannedPackage != null) {
   11887                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
   11888                 }
   11889             } else {
   11890                 // requirer == null implies that we're updating all ABIs in the set to
   11891                 // match scannedPackage.
   11892                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
   11893             }
   11894 
   11895             for (PackageSetting ps : packagesForUser) {
   11896                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
   11897                     if (ps.primaryCpuAbiString != null) {
   11898                         continue;
   11899                     }
   11900 
   11901                     ps.primaryCpuAbiString = adjustedAbi;
   11902                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
   11903                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
   11904                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
   11905                         if (DEBUG_ABI_SELECTION) {
   11906                             Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
   11907                                     + " (requirer="
   11908                                     + (requirer != null ? requirer.pkg : "null")
   11909                                     + ", scannedPackage="
   11910                                     + (scannedPackage != null ? scannedPackage : "null")
   11911                                     + ")");
   11912                         }
   11913                         if (changedAbiCodePath == null) {
   11914                             changedAbiCodePath = new ArrayList<>();
   11915                         }
   11916                         changedAbiCodePath.add(ps.codePathString);
   11917                     }
   11918                 }
   11919             }
   11920         }
   11921         return changedAbiCodePath;
   11922     }
   11923 
   11924     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
   11925         synchronized (mPackages) {
   11926             mResolverReplaced = true;
   11927             // Set up information for custom user intent resolution activity.
   11928             mResolveActivity.applicationInfo = pkg.applicationInfo;
   11929             mResolveActivity.name = mCustomResolverComponentName.getClassName();
   11930             mResolveActivity.packageName = pkg.applicationInfo.packageName;
   11931             mResolveActivity.processName = pkg.applicationInfo.packageName;
   11932             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
   11933             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
   11934                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
   11935             mResolveActivity.theme = 0;
   11936             mResolveActivity.exported = true;
   11937             mResolveActivity.enabled = true;
   11938             mResolveInfo.activityInfo = mResolveActivity;
   11939             mResolveInfo.priority = 0;
   11940             mResolveInfo.preferredOrder = 0;
   11941             mResolveInfo.match = 0;
   11942             mResolveComponentName = mCustomResolverComponentName;
   11943             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
   11944                     mResolveComponentName);
   11945         }
   11946     }
   11947 
   11948     private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
   11949         if (installerActivity == null) {
   11950             if (DEBUG_INSTANT) {
   11951                 Slog.d(TAG, "Clear ephemeral installer activity");
   11952             }
   11953             mInstantAppInstallerActivity = null;
   11954             return;
   11955         }
   11956 
   11957         if (DEBUG_INSTANT) {
   11958             Slog.d(TAG, "Set ephemeral installer activity: "
   11959                     + installerActivity.getComponentName());
   11960         }
   11961         // Set up information for ephemeral installer activity
   11962         mInstantAppInstallerActivity = installerActivity;
   11963         mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
   11964                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
   11965         mInstantAppInstallerActivity.exported = true;
   11966         mInstantAppInstallerActivity.enabled = true;
   11967         mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
   11968         mInstantAppInstallerInfo.priority = 1;
   11969         mInstantAppInstallerInfo.preferredOrder = 1;
   11970         mInstantAppInstallerInfo.isDefault = true;
   11971         mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
   11972                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
   11973     }
   11974 
   11975     private static String calculateBundledApkRoot(final String codePathString) {
   11976         final File codePath = new File(codePathString);
   11977         final File codeRoot;
   11978         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
   11979             codeRoot = Environment.getRootDirectory();
   11980         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
   11981             codeRoot = Environment.getOemDirectory();
   11982         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
   11983             codeRoot = Environment.getVendorDirectory();
   11984         } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
   11985             codeRoot = Environment.getOdmDirectory();
   11986         } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
   11987             codeRoot = Environment.getProductDirectory();
   11988         } else {
   11989             // Unrecognized code path; take its top real segment as the apk root:
   11990             // e.g. /something/app/blah.apk => /something
   11991             try {
   11992                 File f = codePath.getCanonicalFile();
   11993                 File parent = f.getParentFile();    // non-null because codePath is a file
   11994                 File tmp;
   11995                 while ((tmp = parent.getParentFile()) != null) {
   11996                     f = parent;
   11997                     parent = tmp;
   11998                 }
   11999                 codeRoot = f;
   12000                 Slog.w(TAG, "Unrecognized code path "
   12001                         + codePath + " - using " + codeRoot);
   12002             } catch (IOException e) {
   12003                 // Can't canonicalize the code path -- shenanigans?
   12004                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
   12005                 return Environment.getRootDirectory().getPath();
   12006             }
   12007         }
   12008         return codeRoot.getPath();
   12009     }
   12010 
   12011     /**
   12012      * Derive and set the location of native libraries for the given package,
   12013      * which varies depending on where and how the package was installed.
   12014      */
   12015     private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
   12016         final ApplicationInfo info = pkg.applicationInfo;
   12017         final String codePath = pkg.codePath;
   12018         final File codeFile = new File(codePath);
   12019         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
   12020         final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
   12021 
   12022         info.nativeLibraryRootDir = null;
   12023         info.nativeLibraryRootRequiresIsa = false;
   12024         info.nativeLibraryDir = null;
   12025         info.secondaryNativeLibraryDir = null;
   12026 
   12027         if (isApkFile(codeFile)) {
   12028             // Monolithic install
   12029             if (bundledApp) {
   12030                 // If "/system/lib64/apkname" exists, assume that is the per-package
   12031                 // native library directory to use; otherwise use "/system/lib/apkname".
   12032                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
   12033                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
   12034                         getPrimaryInstructionSet(info));
   12035 
   12036                 // This is a bundled system app so choose the path based on the ABI.
   12037                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
   12038                 // is just the default path.
   12039                 final String apkName = deriveCodePathName(codePath);
   12040                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
   12041                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
   12042                         apkName).getAbsolutePath();
   12043 
   12044                 if (info.secondaryCpuAbi != null) {
   12045                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
   12046                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
   12047                             secondaryLibDir, apkName).getAbsolutePath();
   12048                 }
   12049             } else if (asecApp) {
   12050                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
   12051                         .getAbsolutePath();
   12052             } else {
   12053                 final String apkName = deriveCodePathName(codePath);
   12054                 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
   12055                         .getAbsolutePath();
   12056             }
   12057 
   12058             info.nativeLibraryRootRequiresIsa = false;
   12059             info.nativeLibraryDir = info.nativeLibraryRootDir;
   12060         } else {
   12061             // Cluster install
   12062             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
   12063             info.nativeLibraryRootRequiresIsa = true;
   12064 
   12065             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
   12066                     getPrimaryInstructionSet(info)).getAbsolutePath();
   12067 
   12068             if (info.secondaryCpuAbi != null) {
   12069                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
   12070                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
   12071             }
   12072         }
   12073     }
   12074 
   12075     /**
   12076      * Calculate the abis and roots for a bundled app. These can uniquely
   12077      * be determined from the contents of the system partition, i.e whether
   12078      * it contains 64 or 32 bit shared libraries etc. We do not validate any
   12079      * of this information, and instead assume that the system was built
   12080      * sensibly.
   12081      */
   12082     private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
   12083                                            PackageSetting pkgSetting) {
   12084         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
   12085 
   12086         // If "/system/lib64/apkname" exists, assume that is the per-package
   12087         // native library directory to use; otherwise use "/system/lib/apkname".
   12088         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
   12089         setBundledAppAbi(pkg, apkRoot, apkName);
   12090         // pkgSetting might be null during rescan following uninstall of updates
   12091         // to a bundled app, so accommodate that possibility.  The settings in
   12092         // that case will be established later from the parsed package.
   12093         //
   12094         // If the settings aren't null, sync them up with what we've just derived.
   12095         // note that apkRoot isn't stored in the package settings.
   12096         if (pkgSetting != null) {
   12097             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
   12098             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
   12099         }
   12100     }
   12101 
   12102     /**
   12103      * Deduces the ABI of a bundled app and sets the relevant fields on the
   12104      * parsed pkg object.
   12105      *
   12106      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
   12107      *        under which system libraries are installed.
   12108      * @param apkName the name of the installed package.
   12109      */
   12110     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
   12111         final File codeFile = new File(pkg.codePath);
   12112 
   12113         final boolean has64BitLibs;
   12114         final boolean has32BitLibs;
   12115         if (isApkFile(codeFile)) {
   12116             // Monolithic install
   12117             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
   12118             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
   12119         } else {
   12120             // Cluster install
   12121             final File rootDir = new File(codeFile, LIB_DIR_NAME);
   12122             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
   12123                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
   12124                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
   12125                 has64BitLibs = (new File(rootDir, isa)).exists();
   12126             } else {
   12127                 has64BitLibs = false;
   12128             }
   12129             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
   12130                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
   12131                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
   12132                 has32BitLibs = (new File(rootDir, isa)).exists();
   12133             } else {
   12134                 has32BitLibs = false;
   12135             }
   12136         }
   12137 
   12138         if (has64BitLibs && !has32BitLibs) {
   12139             // The package has 64 bit libs, but not 32 bit libs. Its primary
   12140             // ABI should be 64 bit. We can safely assume here that the bundled
   12141             // native libraries correspond to the most preferred ABI in the list.
   12142 
   12143             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
   12144             pkg.applicationInfo.secondaryCpuAbi = null;
   12145         } else if (has32BitLibs && !has64BitLibs) {
   12146             // The package has 32 bit libs but not 64 bit libs. Its primary
   12147             // ABI should be 32 bit.
   12148 
   12149             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   12150             pkg.applicationInfo.secondaryCpuAbi = null;
   12151         } else if (has32BitLibs && has64BitLibs) {
   12152             // The application has both 64 and 32 bit bundled libraries. We check
   12153             // here that the app declares multiArch support, and warn if it doesn't.
   12154             //
   12155             // We will be lenient here and record both ABIs. The primary will be the
   12156             // ABI that's higher on the list, i.e, a device that's configured to prefer
   12157             // 64 bit apps will see a 64 bit primary ABI,
   12158 
   12159             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
   12160                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
   12161             }
   12162 
   12163             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
   12164                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
   12165                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   12166             } else {
   12167                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   12168                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
   12169             }
   12170         } else {
   12171             pkg.applicationInfo.primaryCpuAbi = null;
   12172             pkg.applicationInfo.secondaryCpuAbi = null;
   12173         }
   12174     }
   12175 
   12176     private void killApplication(String pkgName, int appId, String reason) {
   12177         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
   12178     }
   12179 
   12180     private void killApplication(String pkgName, int appId, int userId, String reason) {
   12181         // Request the ActivityManager to kill the process(only for existing packages)
   12182         // so that we do not end up in a confused state while the user is still using the older
   12183         // version of the application while the new one gets installed.
   12184         final long token = Binder.clearCallingIdentity();
   12185         try {
   12186             IActivityManager am = ActivityManager.getService();
   12187             if (am != null) {
   12188                 try {
   12189                     am.killApplication(pkgName, appId, userId, reason);
   12190                 } catch (RemoteException e) {
   12191                 }
   12192             }
   12193         } finally {
   12194             Binder.restoreCallingIdentity(token);
   12195         }
   12196     }
   12197 
   12198     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
   12199         // Remove the parent package setting
   12200         PackageSetting ps = (PackageSetting) pkg.mExtras;
   12201         if (ps != null) {
   12202             removePackageLI(ps, chatty);
   12203         }
   12204         // Remove the child package setting
   12205         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   12206         for (int i = 0; i < childCount; i++) {
   12207             PackageParser.Package childPkg = pkg.childPackages.get(i);
   12208             ps = (PackageSetting) childPkg.mExtras;
   12209             if (ps != null) {
   12210                 removePackageLI(ps, chatty);
   12211             }
   12212         }
   12213     }
   12214 
   12215     void removePackageLI(PackageSetting ps, boolean chatty) {
   12216         if (DEBUG_INSTALL) {
   12217             if (chatty)
   12218                 Log.d(TAG, "Removing package " + ps.name);
   12219         }
   12220 
   12221         // writer
   12222         synchronized (mPackages) {
   12223             mPackages.remove(ps.name);
   12224             final PackageParser.Package pkg = ps.pkg;
   12225             if (pkg != null) {
   12226                 cleanPackageDataStructuresLILPw(pkg, chatty);
   12227             }
   12228         }
   12229     }
   12230 
   12231     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
   12232         if (DEBUG_INSTALL) {
   12233             if (chatty)
   12234                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
   12235         }
   12236 
   12237         // writer
   12238         synchronized (mPackages) {
   12239             // Remove the parent package
   12240             mPackages.remove(pkg.applicationInfo.packageName);
   12241             cleanPackageDataStructuresLILPw(pkg, chatty);
   12242 
   12243             // Remove the child packages
   12244             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   12245             for (int i = 0; i < childCount; i++) {
   12246                 PackageParser.Package childPkg = pkg.childPackages.get(i);
   12247                 mPackages.remove(childPkg.applicationInfo.packageName);
   12248                 cleanPackageDataStructuresLILPw(childPkg, chatty);
   12249             }
   12250         }
   12251     }
   12252 
   12253     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
   12254         int N = pkg.providers.size();
   12255         StringBuilder r = null;
   12256         int i;
   12257         for (i=0; i<N; i++) {
   12258             PackageParser.Provider p = pkg.providers.get(i);
   12259             mProviders.removeProvider(p);
   12260             if (p.info.authority == null) {
   12261 
   12262                 /* There was another ContentProvider with this authority when
   12263                  * this app was installed so this authority is null,
   12264                  * Ignore it as we don't have to unregister the provider.
   12265                  */
   12266                 continue;
   12267             }
   12268             String names[] = p.info.authority.split(";");
   12269             for (int j = 0; j < names.length; j++) {
   12270                 if (mProvidersByAuthority.get(names[j]) == p) {
   12271                     mProvidersByAuthority.remove(names[j]);
   12272                     if (DEBUG_REMOVE) {
   12273                         if (chatty)
   12274                             Log.d(TAG, "Unregistered content provider: " + names[j]
   12275                                     + ", className = " + p.info.name + ", isSyncable = "
   12276                                     + p.info.isSyncable);
   12277                     }
   12278                 }
   12279             }
   12280             if (DEBUG_REMOVE && chatty) {
   12281                 if (r == null) {
   12282                     r = new StringBuilder(256);
   12283                 } else {
   12284                     r.append(' ');
   12285                 }
   12286                 r.append(p.info.name);
   12287             }
   12288         }
   12289         if (r != null) {
   12290             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
   12291         }
   12292 
   12293         N = pkg.services.size();
   12294         r = null;
   12295         for (i=0; i<N; i++) {
   12296             PackageParser.Service s = pkg.services.get(i);
   12297             mServices.removeService(s);
   12298             if (chatty) {
   12299                 if (r == null) {
   12300                     r = new StringBuilder(256);
   12301                 } else {
   12302                     r.append(' ');
   12303                 }
   12304                 r.append(s.info.name);
   12305             }
   12306         }
   12307         if (r != null) {
   12308             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
   12309         }
   12310 
   12311         N = pkg.receivers.size();
   12312         r = null;
   12313         for (i=0; i<N; i++) {
   12314             PackageParser.Activity a = pkg.receivers.get(i);
   12315             mReceivers.removeActivity(a, "receiver");
   12316             if (DEBUG_REMOVE && chatty) {
   12317                 if (r == null) {
   12318                     r = new StringBuilder(256);
   12319                 } else {
   12320                     r.append(' ');
   12321                 }
   12322                 r.append(a.info.name);
   12323             }
   12324         }
   12325         if (r != null) {
   12326             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
   12327         }
   12328 
   12329         N = pkg.activities.size();
   12330         r = null;
   12331         for (i=0; i<N; i++) {
   12332             PackageParser.Activity a = pkg.activities.get(i);
   12333             mActivities.removeActivity(a, "activity");
   12334             if (DEBUG_REMOVE && chatty) {
   12335                 if (r == null) {
   12336                     r = new StringBuilder(256);
   12337                 } else {
   12338                     r.append(' ');
   12339                 }
   12340                 r.append(a.info.name);
   12341             }
   12342         }
   12343         if (r != null) {
   12344             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
   12345         }
   12346 
   12347         mPermissionManager.removeAllPermissions(pkg, chatty);
   12348 
   12349         N = pkg.instrumentation.size();
   12350         r = null;
   12351         for (i=0; i<N; i++) {
   12352             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
   12353             mInstrumentation.remove(a.getComponentName());
   12354             if (DEBUG_REMOVE && chatty) {
   12355                 if (r == null) {
   12356                     r = new StringBuilder(256);
   12357                 } else {
   12358                     r.append(' ');
   12359                 }
   12360                 r.append(a.info.name);
   12361             }
   12362         }
   12363         if (r != null) {
   12364             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
   12365         }
   12366 
   12367         r = null;
   12368         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
   12369             // Only system apps can hold shared libraries.
   12370             if (pkg.libraryNames != null) {
   12371                 for (i = 0; i < pkg.libraryNames.size(); i++) {
   12372                     String name = pkg.libraryNames.get(i);
   12373                     if (removeSharedLibraryLPw(name, 0)) {
   12374                         if (DEBUG_REMOVE && chatty) {
   12375                             if (r == null) {
   12376                                 r = new StringBuilder(256);
   12377                             } else {
   12378                                 r.append(' ');
   12379                             }
   12380                             r.append(name);
   12381                         }
   12382                     }
   12383                 }
   12384             }
   12385         }
   12386 
   12387         r = null;
   12388 
   12389         // Any package can hold static shared libraries.
   12390         if (pkg.staticSharedLibName != null) {
   12391             if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
   12392                 if (DEBUG_REMOVE && chatty) {
   12393                     if (r == null) {
   12394                         r = new StringBuilder(256);
   12395                     } else {
   12396                         r.append(' ');
   12397                     }
   12398                     r.append(pkg.staticSharedLibName);
   12399                 }
   12400             }
   12401         }
   12402 
   12403         if (r != null) {
   12404             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
   12405         }
   12406     }
   12407 
   12408 
   12409     final class ActivityIntentResolver
   12410             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
   12411         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
   12412                 boolean defaultOnly, int userId) {
   12413             if (!sUserManager.exists(userId)) return null;
   12414             mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
   12415             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
   12416         }
   12417 
   12418         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
   12419                 int userId) {
   12420             if (!sUserManager.exists(userId)) return null;
   12421             mFlags = flags;
   12422             return super.queryIntent(intent, resolvedType,
   12423                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   12424                     userId);
   12425         }
   12426 
   12427         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
   12428                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
   12429             if (!sUserManager.exists(userId)) return null;
   12430             if (packageActivities == null) {
   12431                 return null;
   12432             }
   12433             mFlags = flags;
   12434             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
   12435             final int N = packageActivities.size();
   12436             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
   12437                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
   12438 
   12439             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
   12440             for (int i = 0; i < N; ++i) {
   12441                 intentFilters = packageActivities.get(i).intents;
   12442                 if (intentFilters != null && intentFilters.size() > 0) {
   12443                     PackageParser.ActivityIntentInfo[] array =
   12444                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
   12445                     intentFilters.toArray(array);
   12446                     listCut.add(array);
   12447                 }
   12448             }
   12449             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
   12450         }
   12451 
   12452         /**
   12453          * Finds a privileged activity that matches the specified activity names.
   12454          */
   12455         private PackageParser.Activity findMatchingActivity(
   12456                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
   12457             for (PackageParser.Activity sysActivity : activityList) {
   12458                 if (sysActivity.info.name.equals(activityInfo.name)) {
   12459                     return sysActivity;
   12460                 }
   12461                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
   12462                     return sysActivity;
   12463                 }
   12464                 if (sysActivity.info.targetActivity != null) {
   12465                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
   12466                         return sysActivity;
   12467                     }
   12468                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
   12469                         return sysActivity;
   12470                     }
   12471                 }
   12472             }
   12473             return null;
   12474         }
   12475 
   12476         public class IterGenerator<E> {
   12477             public Iterator<E> generate(ActivityIntentInfo info) {
   12478                 return null;
   12479             }
   12480         }
   12481 
   12482         public class ActionIterGenerator extends IterGenerator<String> {
   12483             @Override
   12484             public Iterator<String> generate(ActivityIntentInfo info) {
   12485                 return info.actionsIterator();
   12486             }
   12487         }
   12488 
   12489         public class CategoriesIterGenerator extends IterGenerator<String> {
   12490             @Override
   12491             public Iterator<String> generate(ActivityIntentInfo info) {
   12492                 return info.categoriesIterator();
   12493             }
   12494         }
   12495 
   12496         public class SchemesIterGenerator extends IterGenerator<String> {
   12497             @Override
   12498             public Iterator<String> generate(ActivityIntentInfo info) {
   12499                 return info.schemesIterator();
   12500             }
   12501         }
   12502 
   12503         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
   12504             @Override
   12505             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
   12506                 return info.authoritiesIterator();
   12507             }
   12508         }
   12509 
   12510         /**
   12511          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
   12512          * MODIFIED. Do not pass in a list that should not be changed.
   12513          */
   12514         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
   12515                 IterGenerator<T> generator, Iterator<T> searchIterator) {
   12516             // loop through the set of actions; every one must be found in the intent filter
   12517             while (searchIterator.hasNext()) {
   12518                 // we must have at least one filter in the list to consider a match
   12519                 if (intentList.size() == 0) {
   12520                     break;
   12521                 }
   12522 
   12523                 final T searchAction = searchIterator.next();
   12524 
   12525                 // loop through the set of intent filters
   12526                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
   12527                 while (intentIter.hasNext()) {
   12528                     final ActivityIntentInfo intentInfo = intentIter.next();
   12529                     boolean selectionFound = false;
   12530 
   12531                     // loop through the intent filter's selection criteria; at least one
   12532                     // of them must match the searched criteria
   12533                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
   12534                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
   12535                         final T intentSelection = intentSelectionIter.next();
   12536                         if (intentSelection != null && intentSelection.equals(searchAction)) {
   12537                             selectionFound = true;
   12538                             break;
   12539                         }
   12540                     }
   12541 
   12542                     // the selection criteria wasn't found in this filter's set; this filter
   12543                     // is not a potential match
   12544                     if (!selectionFound) {
   12545                         intentIter.remove();
   12546                     }
   12547                 }
   12548             }
   12549         }
   12550 
   12551         private boolean isProtectedAction(ActivityIntentInfo filter) {
   12552             final Iterator<String> actionsIter = filter.actionsIterator();
   12553             while (actionsIter != null && actionsIter.hasNext()) {
   12554                 final String filterAction = actionsIter.next();
   12555                 if (PROTECTED_ACTIONS.contains(filterAction)) {
   12556                     return true;
   12557                 }
   12558             }
   12559             return false;
   12560         }
   12561 
   12562         /**
   12563          * Adjusts the priority of the given intent filter according to policy.
   12564          * <p>
   12565          * <ul>
   12566          * <li>The priority for non privileged applications is capped to '0'</li>
   12567          * <li>The priority for protected actions on privileged applications is capped to '0'</li>
   12568          * <li>The priority for unbundled updates to privileged applications is capped to the
   12569          *      priority defined on the system partition</li>
   12570          * </ul>
   12571          * <p>
   12572          * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
   12573          * allowed to obtain any priority on any action.
   12574          */
   12575         private void adjustPriority(
   12576                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
   12577             // nothing to do; priority is fine as-is
   12578             if (intent.getPriority() <= 0) {
   12579                 return;
   12580             }
   12581 
   12582             final ActivityInfo activityInfo = intent.activity.info;
   12583             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
   12584 
   12585             final boolean privilegedApp =
   12586                     ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
   12587             if (!privilegedApp) {
   12588                 // non-privileged applications can never define a priority >0
   12589                 if (DEBUG_FILTERS) {
   12590                     Slog.i(TAG, "Non-privileged app; cap priority to 0;"
   12591                             + " package: " + applicationInfo.packageName
   12592                             + " activity: " + intent.activity.className
   12593                             + " origPrio: " + intent.getPriority());
   12594                 }
   12595                 intent.setPriority(0);
   12596                 return;
   12597             }
   12598 
   12599             if (systemActivities == null) {
   12600                 // the system package is not disabled; we're parsing the system partition
   12601                 if (isProtectedAction(intent)) {
   12602                     if (mDeferProtectedFilters) {
   12603                         // We can't deal with these just yet. No component should ever obtain a
   12604                         // >0 priority for a protected actions, with ONE exception -- the setup
   12605                         // wizard. The setup wizard, however, cannot be known until we're able to
   12606                         // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
   12607                         // until all intent filters have been processed. Chicken, meet egg.
   12608                         // Let the filter temporarily have a high priority and rectify the
   12609                         // priorities after all system packages have been scanned.
   12610                         mProtectedFilters.add(intent);
   12611                         if (DEBUG_FILTERS) {
   12612                             Slog.i(TAG, "Protected action; save for later;"
   12613                                     + " package: " + applicationInfo.packageName
   12614                                     + " activity: " + intent.activity.className
   12615                                     + " origPrio: " + intent.getPriority());
   12616                         }
   12617                         return;
   12618                     } else {
   12619                         if (DEBUG_FILTERS && mSetupWizardPackage == null) {
   12620                             Slog.i(TAG, "No setup wizard;"
   12621                                 + " All protected intents capped to priority 0");
   12622                         }
   12623                         if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
   12624                             if (DEBUG_FILTERS) {
   12625                                 Slog.i(TAG, "Found setup wizard;"
   12626                                     + " allow priority " + intent.getPriority() + ";"
   12627                                     + " package: " + intent.activity.info.packageName
   12628                                     + " activity: " + intent.activity.className
   12629                                     + " priority: " + intent.getPriority());
   12630                             }
   12631                             // setup wizard gets whatever it wants
   12632                             return;
   12633                         }
   12634                         if (DEBUG_FILTERS) {
   12635                             Slog.i(TAG, "Protected action; cap priority to 0;"
   12636                                     + " package: " + intent.activity.info.packageName
   12637                                     + " activity: " + intent.activity.className
   12638                                     + " origPrio: " + intent.getPriority());
   12639                         }
   12640                         intent.setPriority(0);
   12641                         return;
   12642                     }
   12643                 }
   12644                 // privileged apps on the system image get whatever priority they request
   12645                 return;
   12646             }
   12647 
   12648             // privileged app unbundled update ... try to find the same activity
   12649             final PackageParser.Activity foundActivity =
   12650                     findMatchingActivity(systemActivities, activityInfo);
   12651             if (foundActivity == null) {
   12652                 // this is a new activity; it cannot obtain >0 priority
   12653                 if (DEBUG_FILTERS) {
   12654                     Slog.i(TAG, "New activity; cap priority to 0;"
   12655                             + " package: " + applicationInfo.packageName
   12656                             + " activity: " + intent.activity.className
   12657                             + " origPrio: " + intent.getPriority());
   12658                 }
   12659                 intent.setPriority(0);
   12660                 return;
   12661             }
   12662 
   12663             // found activity, now check for filter equivalence
   12664 
   12665             // a shallow copy is enough; we modify the list, not its contents
   12666             final List<ActivityIntentInfo> intentListCopy =
   12667                     new ArrayList<>(foundActivity.intents);
   12668             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
   12669 
   12670             // find matching action subsets
   12671             final Iterator<String> actionsIterator = intent.actionsIterator();
   12672             if (actionsIterator != null) {
   12673                 getIntentListSubset(
   12674                         intentListCopy, new ActionIterGenerator(), actionsIterator);
   12675                 if (intentListCopy.size() == 0) {
   12676                     // no more intents to match; we're not equivalent
   12677                     if (DEBUG_FILTERS) {
   12678                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
   12679                                 + " package: " + applicationInfo.packageName
   12680                                 + " activity: " + intent.activity.className
   12681                                 + " origPrio: " + intent.getPriority());
   12682                     }
   12683                     intent.setPriority(0);
   12684                     return;
   12685                 }
   12686             }
   12687 
   12688             // find matching category subsets
   12689             final Iterator<String> categoriesIterator = intent.categoriesIterator();
   12690             if (categoriesIterator != null) {
   12691                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
   12692                         categoriesIterator);
   12693                 if (intentListCopy.size() == 0) {
   12694                     // no more intents to match; we're not equivalent
   12695                     if (DEBUG_FILTERS) {
   12696                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
   12697                                 + " package: " + applicationInfo.packageName
   12698                                 + " activity: " + intent.activity.className
   12699                                 + " origPrio: " + intent.getPriority());
   12700                     }
   12701                     intent.setPriority(0);
   12702                     return;
   12703                 }
   12704             }
   12705 
   12706             // find matching schemes subsets
   12707             final Iterator<String> schemesIterator = intent.schemesIterator();
   12708             if (schemesIterator != null) {
   12709                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
   12710                         schemesIterator);
   12711                 if (intentListCopy.size() == 0) {
   12712                     // no more intents to match; we're not equivalent
   12713                     if (DEBUG_FILTERS) {
   12714                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
   12715                                 + " package: " + applicationInfo.packageName
   12716                                 + " activity: " + intent.activity.className
   12717                                 + " origPrio: " + intent.getPriority());
   12718                     }
   12719                     intent.setPriority(0);
   12720                     return;
   12721                 }
   12722             }
   12723 
   12724             // find matching authorities subsets
   12725             final Iterator<IntentFilter.AuthorityEntry>
   12726                     authoritiesIterator = intent.authoritiesIterator();
   12727             if (authoritiesIterator != null) {
   12728                 getIntentListSubset(intentListCopy,
   12729                         new AuthoritiesIterGenerator(),
   12730                         authoritiesIterator);
   12731                 if (intentListCopy.size() == 0) {
   12732                     // no more intents to match; we're not equivalent
   12733                     if (DEBUG_FILTERS) {
   12734                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
   12735                                 + " package: " + applicationInfo.packageName
   12736                                 + " activity: " + intent.activity.className
   12737                                 + " origPrio: " + intent.getPriority());
   12738                     }
   12739                     intent.setPriority(0);
   12740                     return;
   12741                 }
   12742             }
   12743 
   12744             // we found matching filter(s); app gets the max priority of all intents
   12745             int cappedPriority = 0;
   12746             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
   12747                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
   12748             }
   12749             if (intent.getPriority() > cappedPriority) {
   12750                 if (DEBUG_FILTERS) {
   12751                     Slog.i(TAG, "Found matching filter(s);"
   12752                             + " cap priority to " + cappedPriority + ";"
   12753                             + " package: " + applicationInfo.packageName
   12754                             + " activity: " + intent.activity.className
   12755                             + " origPrio: " + intent.getPriority());
   12756                 }
   12757                 intent.setPriority(cappedPriority);
   12758                 return;
   12759             }
   12760             // all this for nothing; the requested priority was <= what was on the system
   12761         }
   12762 
   12763         public final void addActivity(PackageParser.Activity a, String type) {
   12764             mActivities.put(a.getComponentName(), a);
   12765             if (DEBUG_SHOW_INFO)
   12766                 Log.v(
   12767                 TAG, "  " + type + " " +
   12768                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
   12769             if (DEBUG_SHOW_INFO)
   12770                 Log.v(TAG, "    Class=" + a.info.name);
   12771             final int NI = a.intents.size();
   12772             for (int j=0; j<NI; j++) {
   12773                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
   12774                 if ("activity".equals(type)) {
   12775                     final PackageSetting ps =
   12776                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
   12777                     final List<PackageParser.Activity> systemActivities =
   12778                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
   12779                     adjustPriority(systemActivities, intent);
   12780                 }
   12781                 if (DEBUG_SHOW_INFO) {
   12782                     Log.v(TAG, "    IntentFilter:");
   12783                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   12784                 }
   12785                 if (!intent.debugCheck()) {
   12786                     Log.w(TAG, "==> For Activity " + a.info.name);
   12787                 }
   12788                 addFilter(intent);
   12789             }
   12790         }
   12791 
   12792         public final void removeActivity(PackageParser.Activity a, String type) {
   12793             mActivities.remove(a.getComponentName());
   12794             if (DEBUG_SHOW_INFO) {
   12795                 Log.v(TAG, "  " + type + " "
   12796                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
   12797                                 : a.info.name) + ":");
   12798                 Log.v(TAG, "    Class=" + a.info.name);
   12799             }
   12800             final int NI = a.intents.size();
   12801             for (int j=0; j<NI; j++) {
   12802                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
   12803                 if (DEBUG_SHOW_INFO) {
   12804                     Log.v(TAG, "    IntentFilter:");
   12805                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   12806                 }
   12807                 removeFilter(intent);
   12808             }
   12809         }
   12810 
   12811         @Override
   12812         protected boolean allowFilterResult(
   12813                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
   12814             ActivityInfo filterAi = filter.activity.info;
   12815             for (int i=dest.size()-1; i>=0; i--) {
   12816                 ActivityInfo destAi = dest.get(i).activityInfo;
   12817                 if (destAi.name == filterAi.name
   12818                         && destAi.packageName == filterAi.packageName) {
   12819                     return false;
   12820                 }
   12821             }
   12822             return true;
   12823         }
   12824 
   12825         @Override
   12826         protected ActivityIntentInfo[] newArray(int size) {
   12827             return new ActivityIntentInfo[size];
   12828         }
   12829 
   12830         @Override
   12831         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
   12832             if (!sUserManager.exists(userId)) return true;
   12833             PackageParser.Package p = filter.activity.owner;
   12834             if (p != null) {
   12835                 PackageSetting ps = (PackageSetting)p.mExtras;
   12836                 if (ps != null) {
   12837                     // System apps are never considered stopped for purposes of
   12838                     // filtering, because there may be no way for the user to
   12839                     // actually re-launch them.
   12840                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
   12841                             && ps.getStopped(userId);
   12842                 }
   12843             }
   12844             return false;
   12845         }
   12846 
   12847         @Override
   12848         protected boolean isPackageForFilter(String packageName,
   12849                 PackageParser.ActivityIntentInfo info) {
   12850             return packageName.equals(info.activity.owner.packageName);
   12851         }
   12852 
   12853         @Override
   12854         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
   12855                 int match, int userId) {
   12856             if (!sUserManager.exists(userId)) return null;
   12857             if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
   12858                 return null;
   12859             }
   12860             final PackageParser.Activity activity = info.activity;
   12861             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
   12862             if (ps == null) {
   12863                 return null;
   12864             }
   12865             final PackageUserState userState = ps.readUserState(userId);
   12866             ActivityInfo ai =
   12867                     PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
   12868             if (ai == null) {
   12869                 return null;
   12870             }
   12871             final boolean matchExplicitlyVisibleOnly =
   12872                     (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
   12873             final boolean matchVisibleToInstantApp =
   12874                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   12875             final boolean componentVisible =
   12876                     matchVisibleToInstantApp
   12877                     && info.isVisibleToInstantApp()
   12878                     && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
   12879             final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
   12880             // throw out filters that aren't visible to ephemeral apps
   12881             if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
   12882                 return null;
   12883             }
   12884             // throw out instant app filters if we're not explicitly requesting them
   12885             if (!matchInstantApp && userState.instantApp) {
   12886                 return null;
   12887             }
   12888             // throw out instant app filters if updates are available; will trigger
   12889             // instant app resolution
   12890             if (userState.instantApp && ps.isUpdateAvailable()) {
   12891                 return null;
   12892             }
   12893             final ResolveInfo res = new ResolveInfo();
   12894             res.activityInfo = ai;
   12895             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
   12896                 res.filter = info;
   12897             }
   12898             if (info != null) {
   12899                 res.handleAllWebDataURI = info.handleAllWebDataURI();
   12900             }
   12901             res.priority = info.getPriority();
   12902             res.preferredOrder = activity.owner.mPreferredOrder;
   12903             //System.out.println("Result: " + res.activityInfo.className +
   12904             //                   " = " + res.priority);
   12905             res.match = match;
   12906             res.isDefault = info.hasDefault;
   12907             res.labelRes = info.labelRes;
   12908             res.nonLocalizedLabel = info.nonLocalizedLabel;
   12909             if (userNeedsBadging(userId)) {
   12910                 res.noResourceId = true;
   12911             } else {
   12912                 res.icon = info.icon;
   12913             }
   12914             res.iconResourceId = info.icon;
   12915             res.system = res.activityInfo.applicationInfo.isSystemApp();
   12916             res.isInstantAppAvailable = userState.instantApp;
   12917             return res;
   12918         }
   12919 
   12920         @Override
   12921         protected void sortResults(List<ResolveInfo> results) {
   12922             Collections.sort(results, mResolvePrioritySorter);
   12923         }
   12924 
   12925         @Override
   12926         protected void dumpFilter(PrintWriter out, String prefix,
   12927                 PackageParser.ActivityIntentInfo filter) {
   12928             out.print(prefix); out.print(
   12929                     Integer.toHexString(System.identityHashCode(filter.activity)));
   12930                     out.print(' ');
   12931                     filter.activity.printComponentShortName(out);
   12932                     out.print(" filter ");
   12933                     out.println(Integer.toHexString(System.identityHashCode(filter)));
   12934         }
   12935 
   12936         @Override
   12937         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
   12938             return filter.activity;
   12939         }
   12940 
   12941         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
   12942             PackageParser.Activity activity = (PackageParser.Activity)label;
   12943             out.print(prefix); out.print(
   12944                     Integer.toHexString(System.identityHashCode(activity)));
   12945                     out.print(' ');
   12946                     activity.printComponentShortName(out);
   12947             if (count > 1) {
   12948                 out.print(" ("); out.print(count); out.print(" filters)");
   12949             }
   12950             out.println();
   12951         }
   12952 
   12953         // Keys are String (activity class name), values are Activity.
   12954         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
   12955                 = new ArrayMap<ComponentName, PackageParser.Activity>();
   12956         private int mFlags;
   12957     }
   12958 
   12959     private final class ServiceIntentResolver
   12960             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
   12961         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
   12962                 boolean defaultOnly, int userId) {
   12963             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
   12964             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
   12965         }
   12966 
   12967         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
   12968                 int userId) {
   12969             if (!sUserManager.exists(userId)) return null;
   12970             mFlags = flags;
   12971             return super.queryIntent(intent, resolvedType,
   12972                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   12973                     userId);
   12974         }
   12975 
   12976         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
   12977                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
   12978             if (!sUserManager.exists(userId)) return null;
   12979             if (packageServices == null) {
   12980                 return null;
   12981             }
   12982             mFlags = flags;
   12983             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
   12984             final int N = packageServices.size();
   12985             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
   12986                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
   12987 
   12988             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
   12989             for (int i = 0; i < N; ++i) {
   12990                 intentFilters = packageServices.get(i).intents;
   12991                 if (intentFilters != null && intentFilters.size() > 0) {
   12992                     PackageParser.ServiceIntentInfo[] array =
   12993                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
   12994                     intentFilters.toArray(array);
   12995                     listCut.add(array);
   12996                 }
   12997             }
   12998             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
   12999         }
   13000 
   13001         public final void addService(PackageParser.Service s) {
   13002             mServices.put(s.getComponentName(), s);
   13003             if (DEBUG_SHOW_INFO) {
   13004                 Log.v(TAG, "  "
   13005                         + (s.info.nonLocalizedLabel != null
   13006                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
   13007                 Log.v(TAG, "    Class=" + s.info.name);
   13008             }
   13009             final int NI = s.intents.size();
   13010             int j;
   13011             for (j=0; j<NI; j++) {
   13012                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
   13013                 if (DEBUG_SHOW_INFO) {
   13014                     Log.v(TAG, "    IntentFilter:");
   13015                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   13016                 }
   13017                 if (!intent.debugCheck()) {
   13018                     Log.w(TAG, "==> For Service " + s.info.name);
   13019                 }
   13020                 addFilter(intent);
   13021             }
   13022         }
   13023 
   13024         public final void removeService(PackageParser.Service s) {
   13025             mServices.remove(s.getComponentName());
   13026             if (DEBUG_SHOW_INFO) {
   13027                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
   13028                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
   13029                 Log.v(TAG, "    Class=" + s.info.name);
   13030             }
   13031             final int NI = s.intents.size();
   13032             int j;
   13033             for (j=0; j<NI; j++) {
   13034                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
   13035                 if (DEBUG_SHOW_INFO) {
   13036                     Log.v(TAG, "    IntentFilter:");
   13037                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   13038                 }
   13039                 removeFilter(intent);
   13040             }
   13041         }
   13042 
   13043         @Override
   13044         protected boolean allowFilterResult(
   13045                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
   13046             ServiceInfo filterSi = filter.service.info;
   13047             for (int i=dest.size()-1; i>=0; i--) {
   13048                 ServiceInfo destAi = dest.get(i).serviceInfo;
   13049                 if (destAi.name == filterSi.name
   13050                         && destAi.packageName == filterSi.packageName) {
   13051                     return false;
   13052                 }
   13053             }
   13054             return true;
   13055         }
   13056 
   13057         @Override
   13058         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
   13059             return new PackageParser.ServiceIntentInfo[size];
   13060         }
   13061 
   13062         @Override
   13063         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
   13064             if (!sUserManager.exists(userId)) return true;
   13065             PackageParser.Package p = filter.service.owner;
   13066             if (p != null) {
   13067                 PackageSetting ps = (PackageSetting)p.mExtras;
   13068                 if (ps != null) {
   13069                     // System apps are never considered stopped for purposes of
   13070                     // filtering, because there may be no way for the user to
   13071                     // actually re-launch them.
   13072                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
   13073                             && ps.getStopped(userId);
   13074                 }
   13075             }
   13076             return false;
   13077         }
   13078 
   13079         @Override
   13080         protected boolean isPackageForFilter(String packageName,
   13081                 PackageParser.ServiceIntentInfo info) {
   13082             return packageName.equals(info.service.owner.packageName);
   13083         }
   13084 
   13085         @Override
   13086         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
   13087                 int match, int userId) {
   13088             if (!sUserManager.exists(userId)) return null;
   13089             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
   13090             if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
   13091                 return null;
   13092             }
   13093             final PackageParser.Service service = info.service;
   13094             PackageSetting ps = (PackageSetting) service.owner.mExtras;
   13095             if (ps == null) {
   13096                 return null;
   13097             }
   13098             final PackageUserState userState = ps.readUserState(userId);
   13099             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
   13100                     userState, userId);
   13101             if (si == null) {
   13102                 return null;
   13103             }
   13104             final boolean matchVisibleToInstantApp =
   13105                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   13106             final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
   13107             // throw out filters that aren't visible to ephemeral apps
   13108             if (matchVisibleToInstantApp
   13109                     && !(info.isVisibleToInstantApp() || userState.instantApp)) {
   13110                 return null;
   13111             }
   13112             // throw out ephemeral filters if we're not explicitly requesting them
   13113             if (!isInstantApp && userState.instantApp) {
   13114                 return null;
   13115             }
   13116             // throw out instant app filters if updates are available; will trigger
   13117             // instant app resolution
   13118             if (userState.instantApp && ps.isUpdateAvailable()) {
   13119                 return null;
   13120             }
   13121             final ResolveInfo res = new ResolveInfo();
   13122             res.serviceInfo = si;
   13123             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
   13124                 res.filter = filter;
   13125             }
   13126             res.priority = info.getPriority();
   13127             res.preferredOrder = service.owner.mPreferredOrder;
   13128             res.match = match;
   13129             res.isDefault = info.hasDefault;
   13130             res.labelRes = info.labelRes;
   13131             res.nonLocalizedLabel = info.nonLocalizedLabel;
   13132             res.icon = info.icon;
   13133             res.system = res.serviceInfo.applicationInfo.isSystemApp();
   13134             return res;
   13135         }
   13136 
   13137         @Override
   13138         protected void sortResults(List<ResolveInfo> results) {
   13139             Collections.sort(results, mResolvePrioritySorter);
   13140         }
   13141 
   13142         @Override
   13143         protected void dumpFilter(PrintWriter out, String prefix,
   13144                 PackageParser.ServiceIntentInfo filter) {
   13145             out.print(prefix); out.print(
   13146                     Integer.toHexString(System.identityHashCode(filter.service)));
   13147                     out.print(' ');
   13148                     filter.service.printComponentShortName(out);
   13149                     out.print(" filter ");
   13150                     out.print(Integer.toHexString(System.identityHashCode(filter)));
   13151                     if (filter.service.info.permission != null) {
   13152                         out.print(" permission "); out.println(filter.service.info.permission);
   13153                     } else {
   13154                         out.println();
   13155                     }
   13156         }
   13157 
   13158         @Override
   13159         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
   13160             return filter.service;
   13161         }
   13162 
   13163         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
   13164             PackageParser.Service service = (PackageParser.Service)label;
   13165             out.print(prefix); out.print(
   13166                     Integer.toHexString(System.identityHashCode(service)));
   13167                     out.print(' ');
   13168                     service.printComponentShortName(out);
   13169             if (count > 1) {
   13170                 out.print(" ("); out.print(count); out.print(" filters)");
   13171             }
   13172             out.println();
   13173         }
   13174 
   13175 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
   13176 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
   13177 //            final List<ResolveInfo> retList = Lists.newArrayList();
   13178 //            while (i.hasNext()) {
   13179 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
   13180 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
   13181 //                    retList.add(resolveInfo);
   13182 //                }
   13183 //            }
   13184 //            return retList;
   13185 //        }
   13186 
   13187         // Keys are String (activity class name), values are Activity.
   13188         private final ArrayMap<ComponentName, PackageParser.Service> mServices
   13189                 = new ArrayMap<ComponentName, PackageParser.Service>();
   13190         private int mFlags;
   13191     }
   13192 
   13193     private final class ProviderIntentResolver
   13194             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
   13195         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
   13196                 boolean defaultOnly, int userId) {
   13197             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
   13198             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
   13199         }
   13200 
   13201         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
   13202                 int userId) {
   13203             if (!sUserManager.exists(userId))
   13204                 return null;
   13205             mFlags = flags;
   13206             return super.queryIntent(intent, resolvedType,
   13207                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
   13208                     userId);
   13209         }
   13210 
   13211         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
   13212                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
   13213             if (!sUserManager.exists(userId))
   13214                 return null;
   13215             if (packageProviders == null) {
   13216                 return null;
   13217             }
   13218             mFlags = flags;
   13219             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
   13220             final int N = packageProviders.size();
   13221             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
   13222                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
   13223 
   13224             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
   13225             for (int i = 0; i < N; ++i) {
   13226                 intentFilters = packageProviders.get(i).intents;
   13227                 if (intentFilters != null && intentFilters.size() > 0) {
   13228                     PackageParser.ProviderIntentInfo[] array =
   13229                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
   13230                     intentFilters.toArray(array);
   13231                     listCut.add(array);
   13232                 }
   13233             }
   13234             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
   13235         }
   13236 
   13237         public final void addProvider(PackageParser.Provider p) {
   13238             if (mProviders.containsKey(p.getComponentName())) {
   13239                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
   13240                 return;
   13241             }
   13242 
   13243             mProviders.put(p.getComponentName(), p);
   13244             if (DEBUG_SHOW_INFO) {
   13245                 Log.v(TAG, "  "
   13246                         + (p.info.nonLocalizedLabel != null
   13247                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
   13248                 Log.v(TAG, "    Class=" + p.info.name);
   13249             }
   13250             final int NI = p.intents.size();
   13251             int j;
   13252             for (j = 0; j < NI; j++) {
   13253                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
   13254                 if (DEBUG_SHOW_INFO) {
   13255                     Log.v(TAG, "    IntentFilter:");
   13256                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   13257                 }
   13258                 if (!intent.debugCheck()) {
   13259                     Log.w(TAG, "==> For Provider " + p.info.name);
   13260                 }
   13261                 addFilter(intent);
   13262             }
   13263         }
   13264 
   13265         public final void removeProvider(PackageParser.Provider p) {
   13266             mProviders.remove(p.getComponentName());
   13267             if (DEBUG_SHOW_INFO) {
   13268                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
   13269                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
   13270                 Log.v(TAG, "    Class=" + p.info.name);
   13271             }
   13272             final int NI = p.intents.size();
   13273             int j;
   13274             for (j = 0; j < NI; j++) {
   13275                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
   13276                 if (DEBUG_SHOW_INFO) {
   13277                     Log.v(TAG, "    IntentFilter:");
   13278                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   13279                 }
   13280                 removeFilter(intent);
   13281             }
   13282         }
   13283 
   13284         @Override
   13285         protected boolean allowFilterResult(
   13286                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
   13287             ProviderInfo filterPi = filter.provider.info;
   13288             for (int i = dest.size() - 1; i >= 0; i--) {
   13289                 ProviderInfo destPi = dest.get(i).providerInfo;
   13290                 if (destPi.name == filterPi.name
   13291                         && destPi.packageName == filterPi.packageName) {
   13292                     return false;
   13293                 }
   13294             }
   13295             return true;
   13296         }
   13297 
   13298         @Override
   13299         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
   13300             return new PackageParser.ProviderIntentInfo[size];
   13301         }
   13302 
   13303         @Override
   13304         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
   13305             if (!sUserManager.exists(userId))
   13306                 return true;
   13307             PackageParser.Package p = filter.provider.owner;
   13308             if (p != null) {
   13309                 PackageSetting ps = (PackageSetting) p.mExtras;
   13310                 if (ps != null) {
   13311                     // System apps are never considered stopped for purposes of
   13312                     // filtering, because there may be no way for the user to
   13313                     // actually re-launch them.
   13314                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
   13315                             && ps.getStopped(userId);
   13316                 }
   13317             }
   13318             return false;
   13319         }
   13320 
   13321         @Override
   13322         protected boolean isPackageForFilter(String packageName,
   13323                 PackageParser.ProviderIntentInfo info) {
   13324             return packageName.equals(info.provider.owner.packageName);
   13325         }
   13326 
   13327         @Override
   13328         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
   13329                 int match, int userId) {
   13330             if (!sUserManager.exists(userId))
   13331                 return null;
   13332             final PackageParser.ProviderIntentInfo info = filter;
   13333             if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
   13334                 return null;
   13335             }
   13336             final PackageParser.Provider provider = info.provider;
   13337             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
   13338             if (ps == null) {
   13339                 return null;
   13340             }
   13341             final PackageUserState userState = ps.readUserState(userId);
   13342             final boolean matchVisibleToInstantApp =
   13343                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
   13344             final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
   13345             // throw out filters that aren't visible to instant applications
   13346             if (matchVisibleToInstantApp
   13347                     && !(info.isVisibleToInstantApp() || userState.instantApp)) {
   13348                 return null;
   13349             }
   13350             // throw out instant application filters if we're not explicitly requesting them
   13351             if (!isInstantApp && userState.instantApp) {
   13352                 return null;
   13353             }
   13354             // throw out instant application filters if updates are available; will trigger
   13355             // instant application resolution
   13356             if (userState.instantApp && ps.isUpdateAvailable()) {
   13357                 return null;
   13358             }
   13359             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
   13360                     userState, userId);
   13361             if (pi == null) {
   13362                 return null;
   13363             }
   13364             final ResolveInfo res = new ResolveInfo();
   13365             res.providerInfo = pi;
   13366             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
   13367                 res.filter = filter;
   13368             }
   13369             res.priority = info.getPriority();
   13370             res.preferredOrder = provider.owner.mPreferredOrder;
   13371             res.match = match;
   13372             res.isDefault = info.hasDefault;
   13373             res.labelRes = info.labelRes;
   13374             res.nonLocalizedLabel = info.nonLocalizedLabel;
   13375             res.icon = info.icon;
   13376             res.system = res.providerInfo.applicationInfo.isSystemApp();
   13377             return res;
   13378         }
   13379 
   13380         @Override
   13381         protected void sortResults(List<ResolveInfo> results) {
   13382             Collections.sort(results, mResolvePrioritySorter);
   13383         }
   13384 
   13385         @Override
   13386         protected void dumpFilter(PrintWriter out, String prefix,
   13387                 PackageParser.ProviderIntentInfo filter) {
   13388             out.print(prefix);
   13389             out.print(
   13390                     Integer.toHexString(System.identityHashCode(filter.provider)));
   13391             out.print(' ');
   13392             filter.provider.printComponentShortName(out);
   13393             out.print(" filter ");
   13394             out.println(Integer.toHexString(System.identityHashCode(filter)));
   13395         }
   13396 
   13397         @Override
   13398         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
   13399             return filter.provider;
   13400         }
   13401 
   13402         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
   13403             PackageParser.Provider provider = (PackageParser.Provider)label;
   13404             out.print(prefix); out.print(
   13405                     Integer.toHexString(System.identityHashCode(provider)));
   13406                     out.print(' ');
   13407                     provider.printComponentShortName(out);
   13408             if (count > 1) {
   13409                 out.print(" ("); out.print(count); out.print(" filters)");
   13410             }
   13411             out.println();
   13412         }
   13413 
   13414         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
   13415                 = new ArrayMap<ComponentName, PackageParser.Provider>();
   13416         private int mFlags;
   13417     }
   13418 
   13419     static final class InstantAppIntentResolver
   13420             extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
   13421             AuxiliaryResolveInfo.AuxiliaryFilter> {
   13422         /**
   13423          * The result that has the highest defined order. Ordering applies on a
   13424          * per-package basis. Mapping is from package name to Pair of order and
   13425          * EphemeralResolveInfo.
   13426          * <p>
   13427          * NOTE: This is implemented as a field variable for convenience and efficiency.
   13428          * By having a field variable, we're able to track filter ordering as soon as
   13429          * a non-zero order is defined. Otherwise, multiple loops across the result set
   13430          * would be needed to apply ordering. If the intent resolver becomes re-entrant,
   13431          * this needs to be contained entirely within {@link #filterResults}.
   13432          */
   13433         final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
   13434 
   13435         @Override
   13436         protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
   13437             return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
   13438         }
   13439 
   13440         @Override
   13441         protected boolean isPackageForFilter(String packageName,
   13442                 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
   13443             return true;
   13444         }
   13445 
   13446         @Override
   13447         protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
   13448                 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
   13449             if (!sUserManager.exists(userId)) {
   13450                 return null;
   13451             }
   13452             final String packageName = responseObj.resolveInfo.getPackageName();
   13453             final Integer order = responseObj.getOrder();
   13454             final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
   13455                     mOrderResult.get(packageName);
   13456             // ordering is enabled and this item's order isn't high enough
   13457             if (lastOrderResult != null && lastOrderResult.first >= order) {
   13458                 return null;
   13459             }
   13460             final InstantAppResolveInfo res = responseObj.resolveInfo;
   13461             if (order > 0) {
   13462                 // non-zero order, enable ordering
   13463                 mOrderResult.put(packageName, new Pair<>(order, res));
   13464             }
   13465             return responseObj;
   13466         }
   13467 
   13468         @Override
   13469         protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
   13470             // only do work if ordering is enabled [most of the time it won't be]
   13471             if (mOrderResult.size() == 0) {
   13472                 return;
   13473             }
   13474             int resultSize = results.size();
   13475             for (int i = 0; i < resultSize; i++) {
   13476                 final InstantAppResolveInfo info = results.get(i).resolveInfo;
   13477                 final String packageName = info.getPackageName();
   13478                 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
   13479                 if (savedInfo == null) {
   13480                     // package doesn't having ordering
   13481                     continue;
   13482                 }
   13483                 if (savedInfo.second == info) {
   13484                     // circled back to the highest ordered item; remove from order list
   13485                     mOrderResult.remove(packageName);
   13486                     if (mOrderResult.size() == 0) {
   13487                         // no more ordered items
   13488                         break;
   13489                     }
   13490                     continue;
   13491                 }
   13492                 // item has a worse order, remove it from the result list
   13493                 results.remove(i);
   13494                 resultSize--;
   13495                 i--;
   13496             }
   13497         }
   13498     }
   13499 
   13500     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
   13501             new Comparator<ResolveInfo>() {
   13502         public int compare(ResolveInfo r1, ResolveInfo r2) {
   13503             int v1 = r1.priority;
   13504             int v2 = r2.priority;
   13505             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
   13506             if (v1 != v2) {
   13507                 return (v1 > v2) ? -1 : 1;
   13508             }
   13509             v1 = r1.preferredOrder;
   13510             v2 = r2.preferredOrder;
   13511             if (v1 != v2) {
   13512                 return (v1 > v2) ? -1 : 1;
   13513             }
   13514             if (r1.isDefault != r2.isDefault) {
   13515                 return r1.isDefault ? -1 : 1;
   13516             }
   13517             v1 = r1.match;
   13518             v2 = r2.match;
   13519             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
   13520             if (v1 != v2) {
   13521                 return (v1 > v2) ? -1 : 1;
   13522             }
   13523             if (r1.system != r2.system) {
   13524                 return r1.system ? -1 : 1;
   13525             }
   13526             if (r1.activityInfo != null) {
   13527                 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
   13528             }
   13529             if (r1.serviceInfo != null) {
   13530                 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
   13531             }
   13532             if (r1.providerInfo != null) {
   13533                 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
   13534             }
   13535             return 0;
   13536         }
   13537     };
   13538 
   13539     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
   13540             new Comparator<ProviderInfo>() {
   13541         public int compare(ProviderInfo p1, ProviderInfo p2) {
   13542             final int v1 = p1.initOrder;
   13543             final int v2 = p2.initOrder;
   13544             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
   13545         }
   13546     };
   13547 
   13548     @Override
   13549     public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
   13550             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
   13551             final int[] userIds, int[] instantUserIds) {
   13552         mHandler.post(new Runnable() {
   13553             @Override
   13554             public void run() {
   13555                 try {
   13556                     final IActivityManager am = ActivityManager.getService();
   13557                     if (am == null) return;
   13558                     final int[] resolvedUserIds;
   13559                     if (userIds == null) {
   13560                         resolvedUserIds = am.getRunningUserIds();
   13561                     } else {
   13562                         resolvedUserIds = userIds;
   13563                     }
   13564                     doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
   13565                             resolvedUserIds, false);
   13566                     if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
   13567                         doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
   13568                                 instantUserIds, true);
   13569                     }
   13570                 } catch (RemoteException ex) {
   13571                 }
   13572             }
   13573         });
   13574     }
   13575 
   13576     @Override
   13577     public void notifyPackageAdded(String packageName) {
   13578         final PackageListObserver[] observers;
   13579         synchronized (mPackages) {
   13580             if (mPackageListObservers.size() == 0) {
   13581                 return;
   13582             }
   13583             observers = (PackageListObserver[]) mPackageListObservers.toArray();
   13584         }
   13585         for (int i = observers.length - 1; i >= 0; --i) {
   13586             observers[i].onPackageAdded(packageName);
   13587         }
   13588     }
   13589 
   13590     @Override
   13591     public void notifyPackageRemoved(String packageName) {
   13592         final PackageListObserver[] observers;
   13593         synchronized (mPackages) {
   13594             if (mPackageListObservers.size() == 0) {
   13595                 return;
   13596             }
   13597             observers = (PackageListObserver[]) mPackageListObservers.toArray();
   13598         }
   13599         for (int i = observers.length - 1; i >= 0; --i) {
   13600             observers[i].onPackageRemoved(packageName);
   13601         }
   13602     }
   13603 
   13604     /**
   13605      * Sends a broadcast for the given action.
   13606      * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
   13607      * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
   13608      * the system and applications allowed to see instant applications to receive package
   13609      * lifecycle events for instant applications.
   13610      */
   13611     private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
   13612             int flags, String targetPkg, IIntentReceiver finishedReceiver,
   13613             int[] userIds, boolean isInstantApp)
   13614                     throws RemoteException {
   13615         for (int id : userIds) {
   13616             final Intent intent = new Intent(action,
   13617                     pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
   13618             final String[] requiredPermissions =
   13619                     isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
   13620             if (extras != null) {
   13621                 intent.putExtras(extras);
   13622             }
   13623             if (targetPkg != null) {
   13624                 intent.setPackage(targetPkg);
   13625             }
   13626             // Modify the UID when posting to other users
   13627             int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
   13628             if (uid > 0 && UserHandle.getUserId(uid) != id) {
   13629                 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
   13630                 intent.putExtra(Intent.EXTRA_UID, uid);
   13631             }
   13632             intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
   13633             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
   13634             if (DEBUG_BROADCASTS) {
   13635                 RuntimeException here = new RuntimeException("here");
   13636                 here.fillInStackTrace();
   13637                 Slog.d(TAG, "Sending to user " + id + ": "
   13638                         + intent.toShortString(false, true, false, false)
   13639                         + " " + intent.getExtras(), here);
   13640             }
   13641             am.broadcastIntent(null, intent, null, finishedReceiver,
   13642                     0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
   13643                     null, finishedReceiver != null, false, id);
   13644         }
   13645     }
   13646 
   13647     /**
   13648      * Check if the external storage media is available. This is true if there
   13649      * is a mounted external storage medium or if the external storage is
   13650      * emulated.
   13651      */
   13652     private boolean isExternalMediaAvailable() {
   13653         return mMediaMounted || Environment.isExternalStorageEmulated();
   13654     }
   13655 
   13656     @Override
   13657     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
   13658         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   13659             return null;
   13660         }
   13661         if (!isExternalMediaAvailable()) {
   13662                 // If the external storage is no longer mounted at this point,
   13663                 // the caller may not have been able to delete all of this
   13664                 // packages files and can not delete any more.  Bail.
   13665             return null;
   13666         }
   13667         synchronized (mPackages) {
   13668             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
   13669             if (lastPackage != null) {
   13670                 pkgs.remove(lastPackage);
   13671             }
   13672             if (pkgs.size() > 0) {
   13673                 return pkgs.get(0);
   13674             }
   13675         }
   13676         return null;
   13677     }
   13678 
   13679     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
   13680         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
   13681                 userId, andCode ? 1 : 0, packageName);
   13682         if (mSystemReady) {
   13683             msg.sendToTarget();
   13684         } else {
   13685             if (mPostSystemReadyMessages == null) {
   13686                 mPostSystemReadyMessages = new ArrayList<>();
   13687             }
   13688             mPostSystemReadyMessages.add(msg);
   13689         }
   13690     }
   13691 
   13692     void startCleaningPackages() {
   13693         // reader
   13694         if (!isExternalMediaAvailable()) {
   13695             return;
   13696         }
   13697         synchronized (mPackages) {
   13698             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
   13699                 return;
   13700             }
   13701         }
   13702         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
   13703         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
   13704         IActivityManager am = ActivityManager.getService();
   13705         if (am != null) {
   13706             int dcsUid = -1;
   13707             synchronized (mPackages) {
   13708                 if (!mDefaultContainerWhitelisted) {
   13709                     mDefaultContainerWhitelisted = true;
   13710                     PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
   13711                     dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
   13712                 }
   13713             }
   13714             try {
   13715                 if (dcsUid > 0) {
   13716                     am.backgroundWhitelistUid(dcsUid);
   13717                 }
   13718                 am.startService(null, intent, null, false, mContext.getOpPackageName(),
   13719                         UserHandle.USER_SYSTEM);
   13720             } catch (RemoteException e) {
   13721             }
   13722         }
   13723     }
   13724 
   13725     /**
   13726      * Ensure that the install reason matches what we know about the package installer (e.g. whether
   13727      * it is acting on behalf on an enterprise or the user).
   13728      *
   13729      * Note that the ordering of the conditionals in this method is important. The checks we perform
   13730      * are as follows, in this order:
   13731      *
   13732      * 1) If the install is being performed by a system app, we can trust the app to have set the
   13733      *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
   13734      *    what it is.
   13735      * 2) If the install is being performed by a device or profile owner app, the install reason
   13736      *    should be enterprise policy. However, we cannot be sure that the device or profile owner
   13737      *    set the install reason correctly. If the app targets an older SDK version where install
   13738      *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
   13739      *    unset or wrong. Thus, we force the install reason to be enterprise policy.
   13740      * 3) In all other cases, the install is being performed by a regular app that is neither part
   13741      *    of the system nor a device or profile owner. We have no reason to believe that this app is
   13742      *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
   13743      *    set to enterprise policy and if so, change it to unknown instead.
   13744      */
   13745     private int fixUpInstallReason(String installerPackageName, int installerUid,
   13746             int installReason) {
   13747         if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
   13748                 == PERMISSION_GRANTED) {
   13749             // If the install is being performed by a system app, we trust that app to have set the
   13750             // install reason correctly.
   13751             return installReason;
   13752         }
   13753         final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
   13754                 UserHandle.getUserId(installerUid));
   13755         if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
   13756             // If the install is being performed by a device or profile owner, the install
   13757             // reason should be enterprise policy.
   13758             return PackageManager.INSTALL_REASON_POLICY;
   13759         }
   13760 
   13761 
   13762         if (installReason == PackageManager.INSTALL_REASON_POLICY) {
   13763             // If the install is being performed by a regular app (i.e. neither system app nor
   13764             // device or profile owner), we have no reason to believe that the app is acting on
   13765             // behalf of an enterprise. If the app set the install reason to enterprise policy,
   13766             // change it to unknown instead.
   13767             return PackageManager.INSTALL_REASON_UNKNOWN;
   13768         }
   13769 
   13770         // If the install is being performed by a regular app and the install reason was set to any
   13771         // value but enterprise policy, leave the install reason unchanged.
   13772         return installReason;
   13773     }
   13774 
   13775     /**
   13776      * Attempts to bind to the default container service explicitly instead of doing so lazily on
   13777      * install commit.
   13778      */
   13779     void earlyBindToDefContainer() {
   13780         mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
   13781     }
   13782 
   13783     void installStage(String packageName, File stagedDir,
   13784             IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
   13785             String installerPackageName, int installerUid, UserHandle user,
   13786             PackageParser.SigningDetails signingDetails) {
   13787         if (DEBUG_INSTANT) {
   13788             if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
   13789                 Slog.d(TAG, "Ephemeral install of " + packageName);
   13790             }
   13791         }
   13792         final VerificationInfo verificationInfo = new VerificationInfo(
   13793                 sessionParams.originatingUri, sessionParams.referrerUri,
   13794                 sessionParams.originatingUid, installerUid);
   13795 
   13796         final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
   13797 
   13798         final Message msg = mHandler.obtainMessage(INIT_COPY);
   13799         final int installReason = fixUpInstallReason(installerPackageName, installerUid,
   13800                 sessionParams.installReason);
   13801         final InstallParams params = new InstallParams(origin, null, observer,
   13802                 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
   13803                 verificationInfo, user, sessionParams.abiOverride,
   13804                 sessionParams.grantedRuntimePermissions, signingDetails, installReason);
   13805         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
   13806         msg.obj = params;
   13807 
   13808         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
   13809                 System.identityHashCode(msg.obj));
   13810         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   13811                 System.identityHashCode(msg.obj));
   13812 
   13813         mHandler.sendMessage(msg);
   13814     }
   13815 
   13816     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
   13817             int userId) {
   13818         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
   13819         final boolean isInstantApp = pkgSetting.getInstantApp(userId);
   13820         final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
   13821         final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
   13822         sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
   13823                 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
   13824 
   13825         // Send a session commit broadcast
   13826         final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
   13827         info.installReason = pkgSetting.getInstallReason(userId);
   13828         info.appPackageName = packageName;
   13829         sendSessionCommitBroadcast(info, userId);
   13830     }
   13831 
   13832     @Override
   13833     public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
   13834             boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
   13835         if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
   13836             return;
   13837         }
   13838         Bundle extras = new Bundle(1);
   13839         // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
   13840         final int uid = UserHandle.getUid(
   13841                 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
   13842         extras.putInt(Intent.EXTRA_UID, uid);
   13843 
   13844         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
   13845                 packageName, extras, 0, null, null, userIds, instantUserIds);
   13846         if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
   13847             mHandler.post(() -> {
   13848                         for (int userId : userIds) {
   13849                             sendBootCompletedBroadcastToSystemApp(
   13850                                     packageName, includeStopped, userId);
   13851                         }
   13852                     }
   13853             );
   13854         }
   13855     }
   13856 
   13857     /**
   13858      * The just-installed/enabled app is bundled on the system, so presumed to be able to run
   13859      * automatically without needing an explicit launch.
   13860      * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
   13861      */
   13862     private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
   13863             int userId) {
   13864         // If user is not running, the app didn't miss any broadcast
   13865         if (!mUserManagerInternal.isUserRunning(userId)) {
   13866             return;
   13867         }
   13868         final IActivityManager am = ActivityManager.getService();
   13869         try {
   13870             // Deliver LOCKED_BOOT_COMPLETED first
   13871             Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
   13872                     .setPackage(packageName);
   13873             if (includeStopped) {
   13874                 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
   13875             }
   13876             final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
   13877             am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
   13878                     android.app.AppOpsManager.OP_NONE, null, false, false, userId);
   13879 
   13880             // Deliver BOOT_COMPLETED only if user is unlocked
   13881             if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
   13882                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
   13883                 if (includeStopped) {
   13884                     bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
   13885                 }
   13886                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
   13887                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
   13888             }
   13889         } catch (RemoteException e) {
   13890             throw e.rethrowFromSystemServer();
   13891         }
   13892     }
   13893 
   13894     @Override
   13895     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
   13896             int userId) {
   13897         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   13898         PackageSetting pkgSetting;
   13899         final int callingUid = Binder.getCallingUid();
   13900         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   13901                 true /* requireFullPermission */, true /* checkShell */,
   13902                 "setApplicationHiddenSetting for user " + userId);
   13903 
   13904         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
   13905             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
   13906             return false;
   13907         }
   13908 
   13909         long callingId = Binder.clearCallingIdentity();
   13910         try {
   13911             boolean sendAdded = false;
   13912             boolean sendRemoved = false;
   13913             // writer
   13914             synchronized (mPackages) {
   13915                 pkgSetting = mSettings.mPackages.get(packageName);
   13916                 if (pkgSetting == null) {
   13917                     return false;
   13918                 }
   13919                 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
   13920                     return false;
   13921                 }
   13922                 // Do not allow "android" is being disabled
   13923                 if ("android".equals(packageName)) {
   13924                     Slog.w(TAG, "Cannot hide package: android");
   13925                     return false;
   13926                 }
   13927                 // Cannot hide static shared libs as they are considered
   13928                 // a part of the using app (emulating static linking). Also
   13929                 // static libs are installed always on internal storage.
   13930                 PackageParser.Package pkg = mPackages.get(packageName);
   13931                 if (pkg != null && pkg.staticSharedLibName != null) {
   13932                     Slog.w(TAG, "Cannot hide package: " + packageName
   13933                             + " providing static shared library: "
   13934                             + pkg.staticSharedLibName);
   13935                     return false;
   13936                 }
   13937                 // Only allow protected packages to hide themselves.
   13938                 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
   13939                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
   13940                     Slog.w(TAG, "Not hiding protected package: " + packageName);
   13941                     return false;
   13942                 }
   13943 
   13944                 if (pkgSetting.getHidden(userId) != hidden) {
   13945                     pkgSetting.setHidden(hidden, userId);
   13946                     mSettings.writePackageRestrictionsLPr(userId);
   13947                     if (hidden) {
   13948                         sendRemoved = true;
   13949                     } else {
   13950                         sendAdded = true;
   13951                     }
   13952                 }
   13953             }
   13954             if (sendAdded) {
   13955                 sendPackageAddedForUser(packageName, pkgSetting, userId);
   13956                 return true;
   13957             }
   13958             if (sendRemoved) {
   13959                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
   13960                         "hiding pkg");
   13961                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
   13962                 return true;
   13963             }
   13964         } finally {
   13965             Binder.restoreCallingIdentity(callingId);
   13966         }
   13967         return false;
   13968     }
   13969 
   13970     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
   13971             int userId) {
   13972         final PackageRemovedInfo info = new PackageRemovedInfo(this);
   13973         info.removedPackage = packageName;
   13974         info.installerPackageName = pkgSetting.installerPackageName;
   13975         info.removedUsers = new int[] {userId};
   13976         info.broadcastUsers = new int[] {userId};
   13977         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
   13978         info.sendPackageRemovedBroadcasts(true /*killApp*/);
   13979     }
   13980 
   13981     private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
   13982             PersistableBundle launcherExtras) {
   13983         if (pkgList.length > 0) {
   13984             Bundle extras = new Bundle(1);
   13985             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
   13986             if (launcherExtras != null) {
   13987                 extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
   13988                         new Bundle(launcherExtras.deepCopy()));
   13989             }
   13990             sendPackageBroadcast(
   13991                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
   13992                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
   13993                     null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
   13994                     new int[] {userId}, null);
   13995         }
   13996     }
   13997 
   13998     /**
   13999      * Returns true if application is not found or there was an error. Otherwise it returns
   14000      * the hidden state of the package for the given user.
   14001      */
   14002     @Override
   14003     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
   14004         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   14005         final int callingUid = Binder.getCallingUid();
   14006         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   14007                 true /* requireFullPermission */, false /* checkShell */,
   14008                 "getApplicationHidden for user " + userId);
   14009         PackageSetting ps;
   14010         long callingId = Binder.clearCallingIdentity();
   14011         try {
   14012             // writer
   14013             synchronized (mPackages) {
   14014                 ps = mSettings.mPackages.get(packageName);
   14015                 if (ps == null) {
   14016                     return true;
   14017                 }
   14018                 if (filterAppAccessLPr(ps, callingUid, userId)) {
   14019                     return true;
   14020                 }
   14021                 return ps.getHidden(userId);
   14022             }
   14023         } finally {
   14024             Binder.restoreCallingIdentity(callingId);
   14025         }
   14026     }
   14027 
   14028     /**
   14029      * @hide
   14030      */
   14031     @Override
   14032     public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
   14033             int installReason) {
   14034         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
   14035                 null);
   14036         PackageSetting pkgSetting;
   14037         final int callingUid = Binder.getCallingUid();
   14038         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   14039                 true /* requireFullPermission */, true /* checkShell */,
   14040                 "installExistingPackage for user " + userId);
   14041         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
   14042             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
   14043         }
   14044 
   14045         long callingId = Binder.clearCallingIdentity();
   14046         try {
   14047             boolean installed = false;
   14048             final boolean instantApp =
   14049                     (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
   14050             final boolean fullApp =
   14051                     (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
   14052 
   14053             // writer
   14054             synchronized (mPackages) {
   14055                 pkgSetting = mSettings.mPackages.get(packageName);
   14056                 if (pkgSetting == null) {
   14057                     return PackageManager.INSTALL_FAILED_INVALID_URI;
   14058                 }
   14059                 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
   14060                     // only allow the existing package to be used if it's installed as a full
   14061                     // application for at least one user
   14062                     boolean installAllowed = false;
   14063                     for (int checkUserId : sUserManager.getUserIds()) {
   14064                         installAllowed = !pkgSetting.getInstantApp(checkUserId);
   14065                         if (installAllowed) {
   14066                             break;
   14067                         }
   14068                     }
   14069                     if (!installAllowed) {
   14070                         return PackageManager.INSTALL_FAILED_INVALID_URI;
   14071                     }
   14072                 }
   14073                 if (!pkgSetting.getInstalled(userId)) {
   14074                     pkgSetting.setInstalled(true, userId);
   14075                     pkgSetting.setHidden(false, userId);
   14076                     pkgSetting.setInstallReason(installReason, userId);
   14077                     mSettings.writePackageRestrictionsLPr(userId);
   14078                     mSettings.writeKernelMappingLPr(pkgSetting);
   14079                     installed = true;
   14080                 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
   14081                     // upgrade app from instant to full; we don't allow app downgrade
   14082                     installed = true;
   14083                 }
   14084                 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
   14085             }
   14086 
   14087             if (installed) {
   14088                 if (pkgSetting.pkg != null) {
   14089                     synchronized (mInstallLock) {
   14090                         // We don't need to freeze for a brand new install
   14091                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
   14092                     }
   14093                 }
   14094                 sendPackageAddedForUser(packageName, pkgSetting, userId);
   14095                 synchronized (mPackages) {
   14096                     updateSequenceNumberLP(pkgSetting, new int[]{ userId });
   14097                 }
   14098             }
   14099         } finally {
   14100             Binder.restoreCallingIdentity(callingId);
   14101         }
   14102 
   14103         return PackageManager.INSTALL_SUCCEEDED;
   14104     }
   14105 
   14106     static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
   14107             boolean instantApp, boolean fullApp) {
   14108         // no state specified; do nothing
   14109         if (!instantApp && !fullApp) {
   14110             return;
   14111         }
   14112         if (userId != UserHandle.USER_ALL) {
   14113             if (instantApp && !pkgSetting.getInstantApp(userId)) {
   14114                 pkgSetting.setInstantApp(true /*instantApp*/, userId);
   14115             } else if (fullApp && pkgSetting.getInstantApp(userId)) {
   14116                 pkgSetting.setInstantApp(false /*instantApp*/, userId);
   14117             }
   14118         } else {
   14119             for (int currentUserId : sUserManager.getUserIds()) {
   14120                 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
   14121                     pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
   14122                 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
   14123                     pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
   14124                 }
   14125             }
   14126         }
   14127     }
   14128 
   14129     boolean isUserRestricted(int userId, String restrictionKey) {
   14130         Bundle restrictions = sUserManager.getUserRestrictions(userId);
   14131         if (restrictions.getBoolean(restrictionKey, false)) {
   14132             Log.w(TAG, "User is restricted: " + restrictionKey);
   14133             return true;
   14134         }
   14135         return false;
   14136     }
   14137 
   14138     @Override
   14139     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
   14140             PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
   14141             String callingPackage, int userId) {
   14142         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
   14143                 "setPackagesSuspendedAsUser");
   14144 
   14145         final int callingUid = Binder.getCallingUid();
   14146         if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
   14147                 && getPackageUid(callingPackage, 0, userId) != callingUid) {
   14148             throw new SecurityException("Calling package " + callingPackage + " in user "
   14149                     + userId + " does not belong to calling uid " + callingUid);
   14150         }
   14151         if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
   14152                 && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
   14153             throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
   14154                     + userId + " has an active DO or PO");
   14155         }
   14156         if (ArrayUtils.isEmpty(packageNames)) {
   14157             return packageNames;
   14158         }
   14159 
   14160         final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
   14161         final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
   14162         final long callingId = Binder.clearCallingIdentity();
   14163         try {
   14164             synchronized (mPackages) {
   14165                 for (int i = 0; i < packageNames.length; i++) {
   14166                     final String packageName = packageNames[i];
   14167                     if (callingPackage.equals(packageName)) {
   14168                         Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
   14169                                 + (suspended ? "" : "un") + "suspend itself. Ignoring");
   14170                         unactionedPackages.add(packageName);
   14171                         continue;
   14172                     }
   14173                     final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
   14174                     if (pkgSetting == null
   14175                             || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
   14176                         Slog.w(TAG, "Could not find package setting for package: " + packageName
   14177                                 + ". Skipping suspending/un-suspending.");
   14178                         unactionedPackages.add(packageName);
   14179                         continue;
   14180                     }
   14181                     if (suspended && !canSuspendPackageForUserLocked(packageName, userId)) {
   14182                         unactionedPackages.add(packageName);
   14183                         continue;
   14184                     }
   14185                     pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
   14186                             launcherExtras, userId);
   14187                     changedPackagesList.add(packageName);
   14188                 }
   14189             }
   14190         } finally {
   14191             Binder.restoreCallingIdentity(callingId);
   14192         }
   14193         if (!changedPackagesList.isEmpty()) {
   14194             final String[] changedPackages = changedPackagesList.toArray(
   14195                     new String[changedPackagesList.size()]);
   14196             sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
   14197             sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
   14198             synchronized (mPackages) {
   14199                 scheduleWritePackageRestrictionsLocked(userId);
   14200             }
   14201         }
   14202         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
   14203     }
   14204 
   14205     @Override
   14206     public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
   14207         final int callingUid = Binder.getCallingUid();
   14208         if (getPackageUid(packageName, 0, userId) != callingUid) {
   14209             throw new SecurityException("Calling package " + packageName
   14210                     + " does not belong to calling uid " + callingUid);
   14211         }
   14212         synchronized (mPackages) {
   14213             final PackageSetting ps = mSettings.mPackages.get(packageName);
   14214             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
   14215                 throw new IllegalArgumentException("Unknown target package: " + packageName);
   14216             }
   14217             final PackageUserState packageUserState = ps.readUserState(userId);
   14218             if (packageUserState.suspended) {
   14219                 return packageUserState.suspendedAppExtras;
   14220             }
   14221             return null;
   14222         }
   14223     }
   14224 
   14225     private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
   14226             PersistableBundle appExtras, int userId) {
   14227         final String action;
   14228         final Bundle intentExtras = new Bundle();
   14229         if (suspended) {
   14230             action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
   14231             if (appExtras != null) {
   14232                 final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
   14233                 intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
   14234             }
   14235         } else {
   14236             action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
   14237         }
   14238         mHandler.post(new Runnable() {
   14239             @Override
   14240             public void run() {
   14241                 try {
   14242                     final IActivityManager am = ActivityManager.getService();
   14243                     if (am == null) {
   14244                         Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
   14245                                 + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
   14246                         return;
   14247                     }
   14248                     final int[] targetUserIds = new int[] {userId};
   14249                     for (String packageName : affectedPackages) {
   14250                         doSendBroadcast(am, action, null, intentExtras,
   14251                                 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
   14252                                 targetUserIds, false);
   14253                     }
   14254                 } catch (RemoteException ex) {
   14255                     // Shouldn't happen as AMS is in the same process.
   14256                 }
   14257             }
   14258         });
   14259     }
   14260 
   14261     @Override
   14262     public boolean isPackageSuspendedForUser(String packageName, int userId) {
   14263         final int callingUid = Binder.getCallingUid();
   14264         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   14265                 true /* requireFullPermission */, false /* checkShell */,
   14266                 "isPackageSuspendedForUser for user " + userId);
   14267         synchronized (mPackages) {
   14268             final PackageSetting ps = mSettings.mPackages.get(packageName);
   14269             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
   14270                 throw new IllegalArgumentException("Unknown target package: " + packageName);
   14271             }
   14272             return ps.getSuspended(userId);
   14273         }
   14274     }
   14275 
   14276     /**
   14277      * Immediately unsuspends any packages suspended by the given package. To be called
   14278      * when such a package's data is cleared or it is removed from the device.
   14279      *
   14280      * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
   14281      * synchronously
   14282      *
   14283      * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
   14284      * @param affectedUser The user for which the changes are taking place.
   14285      */
   14286     void unsuspendForSuspendingPackage(final String packageName, int affectedUser) {
   14287         final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
   14288                 : new int[] {affectedUser};
   14289         for (int userId : userIds) {
   14290             unsuspendForSuspendingPackages(packageName::equals, userId);
   14291         }
   14292     }
   14293 
   14294     /**
   14295      * Immediately unsuspends any packages in the given users not suspended by the platform or root.
   14296      * To be called when a profile owner or a device owner is added.
   14297      *
   14298      * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
   14299      * synchronously
   14300      *
   14301      * @param userIds The users for which to unsuspend packages
   14302      */
   14303     void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) {
   14304         final int sz = userIds.size();
   14305         for (int i = 0; i < sz; i++) {
   14306             unsuspendForSuspendingPackages(
   14307                     (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage),
   14308                     userIds.valueAt(i));
   14309         }
   14310     }
   14311 
   14312     private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) {
   14313         final List<String> affectedPackages = new ArrayList<>();
   14314         synchronized (mPackages) {
   14315             for (PackageSetting ps : mSettings.mPackages.values()) {
   14316                 final PackageUserState pus = ps.readUserState(userId);
   14317                 if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) {
   14318                     ps.setSuspended(false, null, null, null, null, userId);
   14319                     affectedPackages.add(ps.name);
   14320                 }
   14321             }
   14322         }
   14323         if (!affectedPackages.isEmpty()) {
   14324             final String[] packageArray = affectedPackages.toArray(
   14325                     new String[affectedPackages.size()]);
   14326             sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
   14327             sendPackagesSuspendedForUser(packageArray, userId, false, null);
   14328             // Write package restrictions immediately to avoid an inconsistent state.
   14329             mSettings.writePackageRestrictionsLPr(userId);
   14330         }
   14331     }
   14332 
   14333     @GuardedBy("mPackages")
   14334     private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
   14335         if (isPackageDeviceAdmin(packageName, userId)) {
   14336             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14337                     + "\": has an active device admin");
   14338             return false;
   14339         }
   14340 
   14341         String activeLauncherPackageName = getActiveLauncherPackageName(userId);
   14342         if (packageName.equals(activeLauncherPackageName)) {
   14343             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14344                     + "\": contains the active launcher");
   14345             return false;
   14346         }
   14347 
   14348         if (packageName.equals(mRequiredInstallerPackage)) {
   14349             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14350                     + "\": required for package installation");
   14351             return false;
   14352         }
   14353 
   14354         if (packageName.equals(mRequiredUninstallerPackage)) {
   14355             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14356                     + "\": required for package uninstallation");
   14357             return false;
   14358         }
   14359 
   14360         if (packageName.equals(mRequiredVerifierPackage)) {
   14361             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14362                     + "\": required for package verification");
   14363             return false;
   14364         }
   14365 
   14366         if (packageName.equals(getDefaultDialerPackageName(userId))) {
   14367             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14368                     + "\": is the default dialer");
   14369             return false;
   14370         }
   14371 
   14372         if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
   14373             Slog.w(TAG, "Cannot suspend package \"" + packageName
   14374                     + "\": protected package");
   14375             return false;
   14376         }
   14377 
   14378         // Cannot suspend static shared libs as they are considered
   14379         // a part of the using app (emulating static linking). Also
   14380         // static libs are installed always on internal storage.
   14381         PackageParser.Package pkg = mPackages.get(packageName);
   14382         if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
   14383             Slog.w(TAG, "Cannot suspend package: " + packageName
   14384                     + " providing static shared library: "
   14385                     + pkg.staticSharedLibName);
   14386             return false;
   14387         }
   14388 
   14389         if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
   14390             Slog.w(TAG, "Cannot suspend package: " + packageName);
   14391             return false;
   14392         }
   14393 
   14394         return true;
   14395     }
   14396 
   14397     private String getActiveLauncherPackageName(int userId) {
   14398         Intent intent = new Intent(Intent.ACTION_MAIN);
   14399         intent.addCategory(Intent.CATEGORY_HOME);
   14400         ResolveInfo resolveInfo = resolveIntent(
   14401                 intent,
   14402                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
   14403                 PackageManager.MATCH_DEFAULT_ONLY,
   14404                 userId);
   14405 
   14406         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
   14407     }
   14408 
   14409     private String getDefaultDialerPackageName(int userId) {
   14410         synchronized (mPackages) {
   14411             return mSettings.getDefaultDialerPackageNameLPw(userId);
   14412         }
   14413     }
   14414 
   14415     @Override
   14416     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
   14417         mContext.enforceCallingOrSelfPermission(
   14418                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   14419                 "Only package verification agents can verify applications");
   14420 
   14421         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
   14422         final PackageVerificationResponse response = new PackageVerificationResponse(
   14423                 verificationCode, Binder.getCallingUid());
   14424         msg.arg1 = id;
   14425         msg.obj = response;
   14426         mHandler.sendMessage(msg);
   14427     }
   14428 
   14429     @Override
   14430     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
   14431             long millisecondsToDelay) {
   14432         mContext.enforceCallingOrSelfPermission(
   14433                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   14434                 "Only package verification agents can extend verification timeouts");
   14435 
   14436         final PackageVerificationState state = mPendingVerification.get(id);
   14437         final PackageVerificationResponse response = new PackageVerificationResponse(
   14438                 verificationCodeAtTimeout, Binder.getCallingUid());
   14439 
   14440         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
   14441             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
   14442         }
   14443         if (millisecondsToDelay < 0) {
   14444             millisecondsToDelay = 0;
   14445         }
   14446         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
   14447                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
   14448             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
   14449         }
   14450 
   14451         if ((state != null) && !state.timeoutExtended()) {
   14452             state.extendTimeout();
   14453 
   14454             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
   14455             msg.arg1 = id;
   14456             msg.obj = response;
   14457             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
   14458         }
   14459     }
   14460 
   14461     private void broadcastPackageVerified(int verificationId, Uri packageUri,
   14462             int verificationCode, UserHandle user) {
   14463         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
   14464         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
   14465         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   14466         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
   14467         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
   14468 
   14469         mContext.sendBroadcastAsUser(intent, user,
   14470                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
   14471     }
   14472 
   14473     private ComponentName matchComponentForVerifier(String packageName,
   14474             List<ResolveInfo> receivers) {
   14475         ActivityInfo targetReceiver = null;
   14476 
   14477         final int NR = receivers.size();
   14478         for (int i = 0; i < NR; i++) {
   14479             final ResolveInfo info = receivers.get(i);
   14480             if (info.activityInfo == null) {
   14481                 continue;
   14482             }
   14483 
   14484             if (packageName.equals(info.activityInfo.packageName)) {
   14485                 targetReceiver = info.activityInfo;
   14486                 break;
   14487             }
   14488         }
   14489 
   14490         if (targetReceiver == null) {
   14491             return null;
   14492         }
   14493 
   14494         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
   14495     }
   14496 
   14497     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
   14498             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
   14499         if (pkgInfo.verifiers.length == 0) {
   14500             return null;
   14501         }
   14502 
   14503         final int N = pkgInfo.verifiers.length;
   14504         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
   14505         for (int i = 0; i < N; i++) {
   14506             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
   14507 
   14508             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
   14509                     receivers);
   14510             if (comp == null) {
   14511                 continue;
   14512             }
   14513 
   14514             final int verifierUid = getUidForVerifier(verifierInfo);
   14515             if (verifierUid == -1) {
   14516                 continue;
   14517             }
   14518 
   14519             if (DEBUG_VERIFY) {
   14520                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
   14521                         + " with the correct signature");
   14522             }
   14523             sufficientVerifiers.add(comp);
   14524             verificationState.addSufficientVerifier(verifierUid);
   14525         }
   14526 
   14527         return sufficientVerifiers;
   14528     }
   14529 
   14530     private int getUidForVerifier(VerifierInfo verifierInfo) {
   14531         synchronized (mPackages) {
   14532             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
   14533             if (pkg == null) {
   14534                 return -1;
   14535             } else if (pkg.mSigningDetails.signatures.length != 1) {
   14536                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
   14537                         + " has more than one signature; ignoring");
   14538                 return -1;
   14539             }
   14540 
   14541             /*
   14542              * If the public key of the package's signature does not match
   14543              * our expected public key, then this is a different package and
   14544              * we should skip.
   14545              */
   14546 
   14547             final byte[] expectedPublicKey;
   14548             try {
   14549                 final Signature verifierSig = pkg.mSigningDetails.signatures[0];
   14550                 final PublicKey publicKey = verifierSig.getPublicKey();
   14551                 expectedPublicKey = publicKey.getEncoded();
   14552             } catch (CertificateException e) {
   14553                 return -1;
   14554             }
   14555 
   14556             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
   14557 
   14558             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
   14559                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
   14560                         + " does not have the expected public key; ignoring");
   14561                 return -1;
   14562             }
   14563 
   14564             return pkg.applicationInfo.uid;
   14565         }
   14566     }
   14567 
   14568     @Override
   14569     public void finishPackageInstall(int token, boolean didLaunch) {
   14570         enforceSystemOrRoot("Only the system is allowed to finish installs");
   14571 
   14572         if (DEBUG_INSTALL) {
   14573             Slog.v(TAG, "BM finishing package install for " + token);
   14574         }
   14575         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
   14576 
   14577         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
   14578         mHandler.sendMessage(msg);
   14579     }
   14580 
   14581     /**
   14582      * Get the verification agent timeout.  Used for both the APK verifier and the
   14583      * intent filter verifier.
   14584      *
   14585      * @return verification timeout in milliseconds
   14586      */
   14587     private long getVerificationTimeout() {
   14588         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   14589                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
   14590                 DEFAULT_VERIFICATION_TIMEOUT);
   14591     }
   14592 
   14593     /**
   14594      * Get the default verification agent response code.
   14595      *
   14596      * @return default verification response code
   14597      */
   14598     private int getDefaultVerificationResponse(UserHandle user) {
   14599         if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
   14600             return PackageManager.VERIFICATION_REJECT;
   14601         }
   14602         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   14603                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
   14604                 DEFAULT_VERIFICATION_RESPONSE);
   14605     }
   14606 
   14607     /**
   14608      * Check whether or not package verification has been enabled.
   14609      *
   14610      * @return true if verification should be performed
   14611      */
   14612     private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
   14613         if (!DEFAULT_VERIFY_ENABLE) {
   14614             return false;
   14615         }
   14616 
   14617         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
   14618 
   14619         // Check if installing from ADB
   14620         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
   14621             // Do not run verification in a test harness environment
   14622             if (ActivityManager.isRunningInTestHarness()) {
   14623                 return false;
   14624             }
   14625             if (ensureVerifyAppsEnabled) {
   14626                 return true;
   14627             }
   14628             // Check if the developer does not want package verification for ADB installs
   14629             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   14630                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
   14631                 return false;
   14632             }
   14633         } else {
   14634             // only when not installed from ADB, skip verification for instant apps when
   14635             // the installer and verifier are the same.
   14636             if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
   14637                 if (mInstantAppInstallerActivity != null
   14638                         && mInstantAppInstallerActivity.packageName.equals(
   14639                                 mRequiredVerifierPackage)) {
   14640                     try {
   14641                         mContext.getSystemService(AppOpsManager.class)
   14642                                 .checkPackage(installerUid, mRequiredVerifierPackage);
   14643                         if (DEBUG_VERIFY) {
   14644                             Slog.i(TAG, "disable verification for instant app");
   14645                         }
   14646                         return false;
   14647                     } catch (SecurityException ignore) { }
   14648                 }
   14649             }
   14650         }
   14651 
   14652         if (ensureVerifyAppsEnabled) {
   14653             return true;
   14654         }
   14655 
   14656         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   14657                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
   14658     }
   14659 
   14660     @Override
   14661     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
   14662             throws RemoteException {
   14663         mContext.enforceCallingOrSelfPermission(
   14664                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
   14665                 "Only intentfilter verification agents can verify applications");
   14666 
   14667         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
   14668         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
   14669                 Binder.getCallingUid(), verificationCode, failedDomains);
   14670         msg.arg1 = id;
   14671         msg.obj = response;
   14672         mHandler.sendMessage(msg);
   14673     }
   14674 
   14675     @Override
   14676     public int getIntentVerificationStatus(String packageName, int userId) {
   14677         final int callingUid = Binder.getCallingUid();
   14678         if (UserHandle.getUserId(callingUid) != userId) {
   14679             mContext.enforceCallingOrSelfPermission(
   14680                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   14681                     "getIntentVerificationStatus" + userId);
   14682         }
   14683         if (getInstantAppPackageName(callingUid) != null) {
   14684             return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
   14685         }
   14686         synchronized (mPackages) {
   14687             final PackageSetting ps = mSettings.mPackages.get(packageName);
   14688             if (ps == null
   14689                     || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   14690                 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
   14691             }
   14692             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
   14693         }
   14694     }
   14695 
   14696     @Override
   14697     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
   14698         mContext.enforceCallingOrSelfPermission(
   14699                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   14700 
   14701         boolean result = false;
   14702         synchronized (mPackages) {
   14703             final PackageSetting ps = mSettings.mPackages.get(packageName);
   14704             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
   14705                 return false;
   14706             }
   14707             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
   14708         }
   14709         if (result) {
   14710             scheduleWritePackageRestrictionsLocked(userId);
   14711         }
   14712         return result;
   14713     }
   14714 
   14715     @Override
   14716     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
   14717             String packageName) {
   14718         final int callingUid = Binder.getCallingUid();
   14719         if (getInstantAppPackageName(callingUid) != null) {
   14720             return ParceledListSlice.emptyList();
   14721         }
   14722         synchronized (mPackages) {
   14723             final PackageSetting ps = mSettings.mPackages.get(packageName);
   14724             if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   14725                 return ParceledListSlice.emptyList();
   14726             }
   14727             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
   14728         }
   14729     }
   14730 
   14731     @Override
   14732     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
   14733         if (TextUtils.isEmpty(packageName)) {
   14734             return ParceledListSlice.emptyList();
   14735         }
   14736         final int callingUid = Binder.getCallingUid();
   14737         final int callingUserId = UserHandle.getUserId(callingUid);
   14738         synchronized (mPackages) {
   14739             PackageParser.Package pkg = mPackages.get(packageName);
   14740             if (pkg == null || pkg.activities == null) {
   14741                 return ParceledListSlice.emptyList();
   14742             }
   14743             if (pkg.mExtras == null) {
   14744                 return ParceledListSlice.emptyList();
   14745             }
   14746             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   14747             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   14748                 return ParceledListSlice.emptyList();
   14749             }
   14750             final int count = pkg.activities.size();
   14751             ArrayList<IntentFilter> result = new ArrayList<>();
   14752             for (int n=0; n<count; n++) {
   14753                 PackageParser.Activity activity = pkg.activities.get(n);
   14754                 if (activity.intents != null && activity.intents.size() > 0) {
   14755                     result.addAll(activity.intents);
   14756                 }
   14757             }
   14758             return new ParceledListSlice<>(result);
   14759         }
   14760     }
   14761 
   14762     @Override
   14763     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
   14764         mContext.enforceCallingOrSelfPermission(
   14765                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   14766         if (UserHandle.getCallingUserId() != userId) {
   14767             mContext.enforceCallingOrSelfPermission(
   14768                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   14769         }
   14770 
   14771         synchronized (mPackages) {
   14772             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
   14773             if (packageName != null) {
   14774                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
   14775                         packageName, userId);
   14776             }
   14777             return result;
   14778         }
   14779     }
   14780 
   14781     @Override
   14782     public String getDefaultBrowserPackageName(int userId) {
   14783         if (UserHandle.getCallingUserId() != userId) {
   14784             mContext.enforceCallingOrSelfPermission(
   14785                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   14786         }
   14787         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   14788             return null;
   14789         }
   14790         synchronized (mPackages) {
   14791             return mSettings.getDefaultBrowserPackageNameLPw(userId);
   14792         }
   14793     }
   14794 
   14795     /**
   14796      * Get the "allow unknown sources" setting.
   14797      *
   14798      * @return the current "allow unknown sources" setting
   14799      */
   14800     private int getUnknownSourcesSettings() {
   14801         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
   14802                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
   14803                 -1);
   14804     }
   14805 
   14806     @Override
   14807     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
   14808         final int callingUid = Binder.getCallingUid();
   14809         if (getInstantAppPackageName(callingUid) != null) {
   14810             return;
   14811         }
   14812         // writer
   14813         synchronized (mPackages) {
   14814             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
   14815             if (targetPackageSetting == null
   14816                     || filterAppAccessLPr(
   14817                             targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
   14818                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
   14819             }
   14820 
   14821             PackageSetting installerPackageSetting;
   14822             if (installerPackageName != null) {
   14823                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
   14824                 if (installerPackageSetting == null) {
   14825                     throw new IllegalArgumentException("Unknown installer package: "
   14826                             + installerPackageName);
   14827                 }
   14828             } else {
   14829                 installerPackageSetting = null;
   14830             }
   14831 
   14832             Signature[] callerSignature;
   14833             Object obj = mSettings.getUserIdLPr(callingUid);
   14834             if (obj != null) {
   14835                 if (obj instanceof SharedUserSetting) {
   14836                     callerSignature =
   14837                             ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
   14838                 } else if (obj instanceof PackageSetting) {
   14839                     callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
   14840                 } else {
   14841                     throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
   14842                 }
   14843             } else {
   14844                 throw new SecurityException("Unknown calling UID: " + callingUid);
   14845             }
   14846 
   14847             // Verify: can't set installerPackageName to a package that is
   14848             // not signed with the same cert as the caller.
   14849             if (installerPackageSetting != null) {
   14850                 if (compareSignatures(callerSignature,
   14851                         installerPackageSetting.signatures.mSigningDetails.signatures)
   14852                         != PackageManager.SIGNATURE_MATCH) {
   14853                     throw new SecurityException(
   14854                             "Caller does not have same cert as new installer package "
   14855                             + installerPackageName);
   14856                 }
   14857             }
   14858 
   14859             // Verify: if target already has an installer package, it must
   14860             // be signed with the same cert as the caller.
   14861             if (targetPackageSetting.installerPackageName != null) {
   14862                 PackageSetting setting = mSettings.mPackages.get(
   14863                         targetPackageSetting.installerPackageName);
   14864                 // If the currently set package isn't valid, then it's always
   14865                 // okay to change it.
   14866                 if (setting != null) {
   14867                     if (compareSignatures(callerSignature,
   14868                             setting.signatures.mSigningDetails.signatures)
   14869                             != PackageManager.SIGNATURE_MATCH) {
   14870                         throw new SecurityException(
   14871                                 "Caller does not have same cert as old installer package "
   14872                                 + targetPackageSetting.installerPackageName);
   14873                     }
   14874                 }
   14875             }
   14876 
   14877             // Okay!
   14878             targetPackageSetting.installerPackageName = installerPackageName;
   14879             if (installerPackageName != null) {
   14880                 mSettings.mInstallerPackages.add(installerPackageName);
   14881             }
   14882             scheduleWriteSettingsLocked();
   14883         }
   14884     }
   14885 
   14886     @Override
   14887     public void setApplicationCategoryHint(String packageName, int categoryHint,
   14888             String callerPackageName) {
   14889         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   14890             throw new SecurityException("Instant applications don't have access to this method");
   14891         }
   14892         mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
   14893                 callerPackageName);
   14894         synchronized (mPackages) {
   14895             PackageSetting ps = mSettings.mPackages.get(packageName);
   14896             if (ps == null) {
   14897                 throw new IllegalArgumentException("Unknown target package " + packageName);
   14898             }
   14899             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
   14900                 throw new IllegalArgumentException("Unknown target package " + packageName);
   14901             }
   14902             if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
   14903                 throw new IllegalArgumentException("Calling package " + callerPackageName
   14904                         + " is not installer for " + packageName);
   14905             }
   14906 
   14907             if (ps.categoryHint != categoryHint) {
   14908                 ps.categoryHint = categoryHint;
   14909                 scheduleWriteSettingsLocked();
   14910             }
   14911         }
   14912     }
   14913 
   14914     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
   14915         // Queue up an async operation since the package installation may take a little while.
   14916         mHandler.post(new Runnable() {
   14917             public void run() {
   14918                 mHandler.removeCallbacks(this);
   14919                  // Result object to be returned
   14920                 PackageInstalledInfo res = new PackageInstalledInfo();
   14921                 res.setReturnCode(currentStatus);
   14922                 res.uid = -1;
   14923                 res.pkg = null;
   14924                 res.removedInfo = null;
   14925                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   14926                     args.doPreInstall(res.returnCode);
   14927                     synchronized (mInstallLock) {
   14928                         installPackageTracedLI(args, res);
   14929                     }
   14930                     args.doPostInstall(res.returnCode, res.uid);
   14931                 }
   14932 
   14933                 // A restore should be performed at this point if (a) the install
   14934                 // succeeded, (b) the operation is not an update, and (c) the new
   14935                 // package has not opted out of backup participation.
   14936                 final boolean update = res.removedInfo != null
   14937                         && res.removedInfo.removedPackage != null;
   14938                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
   14939                 boolean doRestore = !update
   14940                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
   14941 
   14942                 // Set up the post-install work request bookkeeping.  This will be used
   14943                 // and cleaned up by the post-install event handling regardless of whether
   14944                 // there's a restore pass performed.  Token values are >= 1.
   14945                 int token;
   14946                 if (mNextInstallToken < 0) mNextInstallToken = 1;
   14947                 token = mNextInstallToken++;
   14948 
   14949                 PostInstallData data = new PostInstallData(args, res);
   14950                 mRunningInstalls.put(token, data);
   14951                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
   14952 
   14953                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
   14954                     // Pass responsibility to the Backup Manager.  It will perform a
   14955                     // restore if appropriate, then pass responsibility back to the
   14956                     // Package Manager to run the post-install observer callbacks
   14957                     // and broadcasts.
   14958                     IBackupManager bm = IBackupManager.Stub.asInterface(
   14959                             ServiceManager.getService(Context.BACKUP_SERVICE));
   14960                     if (bm != null) {
   14961                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
   14962                                 + " to BM for possible restore");
   14963                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
   14964                         try {
   14965                             // TODO: http://b/22388012
   14966                             if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
   14967                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
   14968                             } else {
   14969                                 doRestore = false;
   14970                             }
   14971                         } catch (RemoteException e) {
   14972                             // can't happen; the backup manager is local
   14973                         } catch (Exception e) {
   14974                             Slog.e(TAG, "Exception trying to enqueue restore", e);
   14975                             doRestore = false;
   14976                         }
   14977                     } else {
   14978                         Slog.e(TAG, "Backup Manager not found!");
   14979                         doRestore = false;
   14980                     }
   14981                 }
   14982 
   14983                 if (!doRestore) {
   14984                     // No restore possible, or the Backup Manager was mysteriously not
   14985                     // available -- just fire the post-install work request directly.
   14986                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
   14987 
   14988                     Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
   14989 
   14990                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
   14991                     mHandler.sendMessage(msg);
   14992                 }
   14993             }
   14994         });
   14995     }
   14996 
   14997     /**
   14998      * Callback from PackageSettings whenever an app is first transitioned out of the
   14999      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
   15000      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
   15001      * here whether the app is the target of an ongoing install, and only send the
   15002      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
   15003      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
   15004      * handling.
   15005      */
   15006     void notifyFirstLaunch(final String packageName, final String installerPackage,
   15007             final int userId) {
   15008         // Serialize this with the rest of the install-process message chain.  In the
   15009         // restore-at-install case, this Runnable will necessarily run before the
   15010         // POST_INSTALL message is processed, so the contents of mRunningInstalls
   15011         // are coherent.  In the non-restore case, the app has already completed install
   15012         // and been launched through some other means, so it is not in a problematic
   15013         // state for observers to see the FIRST_LAUNCH signal.
   15014         mHandler.post(new Runnable() {
   15015             @Override
   15016             public void run() {
   15017                 for (int i = 0; i < mRunningInstalls.size(); i++) {
   15018                     final PostInstallData data = mRunningInstalls.valueAt(i);
   15019                     if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
   15020                         continue;
   15021                     }
   15022                     if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
   15023                         // right package; but is it for the right user?
   15024                         for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
   15025                             if (userId == data.res.newUsers[uIndex]) {
   15026                                 if (DEBUG_BACKUP) {
   15027                                     Slog.i(TAG, "Package " + packageName
   15028                                             + " being restored so deferring FIRST_LAUNCH");
   15029                                 }
   15030                                 return;
   15031                             }
   15032                         }
   15033                     }
   15034                 }
   15035                 // didn't find it, so not being restored
   15036                 if (DEBUG_BACKUP) {
   15037                     Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
   15038                 }
   15039                 final boolean isInstantApp = isInstantApp(packageName, userId);
   15040                 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
   15041                 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
   15042                 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
   15043             }
   15044         });
   15045     }
   15046 
   15047     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
   15048             int[] userIds, int[] instantUserIds) {
   15049         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
   15050                 installerPkg, null, userIds, instantUserIds);
   15051     }
   15052 
   15053     private abstract class HandlerParams {
   15054         private static final int MAX_RETRIES = 4;
   15055 
   15056         /**
   15057          * Number of times startCopy() has been attempted and had a non-fatal
   15058          * error.
   15059          */
   15060         private int mRetries = 0;
   15061 
   15062         /** User handle for the user requesting the information or installation. */
   15063         private final UserHandle mUser;
   15064         String traceMethod;
   15065         int traceCookie;
   15066 
   15067         HandlerParams(UserHandle user) {
   15068             mUser = user;
   15069         }
   15070 
   15071         UserHandle getUser() {
   15072             return mUser;
   15073         }
   15074 
   15075         HandlerParams setTraceMethod(String traceMethod) {
   15076             this.traceMethod = traceMethod;
   15077             return this;
   15078         }
   15079 
   15080         HandlerParams setTraceCookie(int traceCookie) {
   15081             this.traceCookie = traceCookie;
   15082             return this;
   15083         }
   15084 
   15085         final boolean startCopy() {
   15086             boolean res;
   15087             try {
   15088                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
   15089 
   15090                 if (++mRetries > MAX_RETRIES) {
   15091                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
   15092                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
   15093                     handleServiceError();
   15094                     return false;
   15095                 } else {
   15096                     handleStartCopy();
   15097                     res = true;
   15098                 }
   15099             } catch (RemoteException e) {
   15100                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
   15101                 mHandler.sendEmptyMessage(MCS_RECONNECT);
   15102                 res = false;
   15103             }
   15104             handleReturnCode();
   15105             return res;
   15106         }
   15107 
   15108         final void serviceError() {
   15109             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
   15110             handleServiceError();
   15111             handleReturnCode();
   15112         }
   15113 
   15114         abstract void handleStartCopy() throws RemoteException;
   15115         abstract void handleServiceError();
   15116         abstract void handleReturnCode();
   15117     }
   15118 
   15119     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
   15120         for (File path : paths) {
   15121             try {
   15122                 mcs.clearDirectory(path.getAbsolutePath());
   15123             } catch (RemoteException e) {
   15124             }
   15125         }
   15126     }
   15127 
   15128     static class OriginInfo {
   15129         /**
   15130          * Location where install is coming from, before it has been
   15131          * copied/renamed into place. This could be a single monolithic APK
   15132          * file, or a cluster directory. This location may be untrusted.
   15133          */
   15134         final File file;
   15135 
   15136         /**
   15137          * Flag indicating that {@link #file} or {@link #cid} has already been
   15138          * staged, meaning downstream users don't need to defensively copy the
   15139          * contents.
   15140          */
   15141         final boolean staged;
   15142 
   15143         /**
   15144          * Flag indicating that {@link #file} or {@link #cid} is an already
   15145          * installed app that is being moved.
   15146          */
   15147         final boolean existing;
   15148 
   15149         final String resolvedPath;
   15150         final File resolvedFile;
   15151 
   15152         static OriginInfo fromNothing() {
   15153             return new OriginInfo(null, false, false);
   15154         }
   15155 
   15156         static OriginInfo fromUntrustedFile(File file) {
   15157             return new OriginInfo(file, false, false);
   15158         }
   15159 
   15160         static OriginInfo fromExistingFile(File file) {
   15161             return new OriginInfo(file, false, true);
   15162         }
   15163 
   15164         static OriginInfo fromStagedFile(File file) {
   15165             return new OriginInfo(file, true, false);
   15166         }
   15167 
   15168         private OriginInfo(File file, boolean staged, boolean existing) {
   15169             this.file = file;
   15170             this.staged = staged;
   15171             this.existing = existing;
   15172 
   15173             if (file != null) {
   15174                 resolvedPath = file.getAbsolutePath();
   15175                 resolvedFile = file;
   15176             } else {
   15177                 resolvedPath = null;
   15178                 resolvedFile = null;
   15179             }
   15180         }
   15181     }
   15182 
   15183     static class MoveInfo {
   15184         final int moveId;
   15185         final String fromUuid;
   15186         final String toUuid;
   15187         final String packageName;
   15188         final String dataAppName;
   15189         final int appId;
   15190         final String seinfo;
   15191         final int targetSdkVersion;
   15192 
   15193         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
   15194                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
   15195             this.moveId = moveId;
   15196             this.fromUuid = fromUuid;
   15197             this.toUuid = toUuid;
   15198             this.packageName = packageName;
   15199             this.dataAppName = dataAppName;
   15200             this.appId = appId;
   15201             this.seinfo = seinfo;
   15202             this.targetSdkVersion = targetSdkVersion;
   15203         }
   15204     }
   15205 
   15206     static class VerificationInfo {
   15207         /** A constant used to indicate that a uid value is not present. */
   15208         public static final int NO_UID = -1;
   15209 
   15210         /** URI referencing where the package was downloaded from. */
   15211         final Uri originatingUri;
   15212 
   15213         /** HTTP referrer URI associated with the originatingURI. */
   15214         final Uri referrer;
   15215 
   15216         /** UID of the application that the install request originated from. */
   15217         final int originatingUid;
   15218 
   15219         /** UID of application requesting the install */
   15220         final int installerUid;
   15221 
   15222         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
   15223             this.originatingUri = originatingUri;
   15224             this.referrer = referrer;
   15225             this.originatingUid = originatingUid;
   15226             this.installerUid = installerUid;
   15227         }
   15228     }
   15229 
   15230     class InstallParams extends HandlerParams {
   15231         final OriginInfo origin;
   15232         final MoveInfo move;
   15233         final IPackageInstallObserver2 observer;
   15234         int installFlags;
   15235         final String installerPackageName;
   15236         final String volumeUuid;
   15237         private InstallArgs mArgs;
   15238         private int mRet;
   15239         final String packageAbiOverride;
   15240         final String[] grantedRuntimePermissions;
   15241         final VerificationInfo verificationInfo;
   15242         final PackageParser.SigningDetails signingDetails;
   15243         final int installReason;
   15244 
   15245         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
   15246                 int installFlags, String installerPackageName, String volumeUuid,
   15247                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
   15248                 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
   15249             super(user);
   15250             this.origin = origin;
   15251             this.move = move;
   15252             this.observer = observer;
   15253             this.installFlags = installFlags;
   15254             this.installerPackageName = installerPackageName;
   15255             this.volumeUuid = volumeUuid;
   15256             this.verificationInfo = verificationInfo;
   15257             this.packageAbiOverride = packageAbiOverride;
   15258             this.grantedRuntimePermissions = grantedPermissions;
   15259             this.signingDetails = signingDetails;
   15260             this.installReason = installReason;
   15261         }
   15262 
   15263         @Override
   15264         public String toString() {
   15265             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
   15266                     + " file=" + origin.file + "}";
   15267         }
   15268 
   15269         private int installLocationPolicy(PackageInfoLite pkgLite) {
   15270             String packageName = pkgLite.packageName;
   15271             int installLocation = pkgLite.installLocation;
   15272             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
   15273             // reader
   15274             synchronized (mPackages) {
   15275                 // Currently installed package which the new package is attempting to replace or
   15276                 // null if no such package is installed.
   15277                 PackageParser.Package installedPkg = mPackages.get(packageName);
   15278                 // Package which currently owns the data which the new package will own if installed.
   15279                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
   15280                 // will be null whereas dataOwnerPkg will contain information about the package
   15281                 // which was uninstalled while keeping its data.
   15282                 PackageParser.Package dataOwnerPkg = installedPkg;
   15283                 if (dataOwnerPkg  == null) {
   15284                     PackageSetting ps = mSettings.mPackages.get(packageName);
   15285                     if (ps != null) {
   15286                         dataOwnerPkg = ps.pkg;
   15287                     }
   15288                 }
   15289 
   15290                 if (dataOwnerPkg != null) {
   15291                     // If installed, the package will get access to data left on the device by its
   15292                     // predecessor. As a security measure, this is permited only if this is not a
   15293                     // version downgrade or if the predecessor package is marked as debuggable and
   15294                     // a downgrade is explicitly requested.
   15295                     //
   15296                     // On debuggable platform builds, downgrades are permitted even for
   15297                     // non-debuggable packages to make testing easier. Debuggable platform builds do
   15298                     // not offer security guarantees and thus it's OK to disable some security
   15299                     // mechanisms to make debugging/testing easier on those builds. However, even on
   15300                     // debuggable builds downgrades of packages are permitted only if requested via
   15301                     // installFlags. This is because we aim to keep the behavior of debuggable
   15302                     // platform builds as close as possible to the behavior of non-debuggable
   15303                     // platform builds.
   15304                     final boolean downgradeRequested =
   15305                             (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
   15306                     final boolean packageDebuggable =
   15307                                 (dataOwnerPkg.applicationInfo.flags
   15308                                         & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
   15309                     final boolean downgradePermitted =
   15310                             (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
   15311                     if (!downgradePermitted) {
   15312                         try {
   15313                             checkDowngrade(dataOwnerPkg, pkgLite);
   15314                         } catch (PackageManagerException e) {
   15315                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
   15316                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
   15317                         }
   15318                     }
   15319                 }
   15320 
   15321                 if (installedPkg != null) {
   15322                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
   15323                         // Check for updated system application.
   15324                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   15325                             if (onSd) {
   15326                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
   15327                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
   15328                             }
   15329                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
   15330                         } else {
   15331                             if (onSd) {
   15332                                 // Install flag overrides everything.
   15333                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
   15334                             }
   15335                             // If current upgrade specifies particular preference
   15336                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
   15337                                 // Application explicitly specified internal.
   15338                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
   15339                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
   15340                                 // App explictly prefers external. Let policy decide
   15341                             } else {
   15342                                 // Prefer previous location
   15343                                 if (isExternal(installedPkg)) {
   15344                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
   15345                                 }
   15346                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
   15347                             }
   15348                         }
   15349                     } else {
   15350                         // Invalid install. Return error code
   15351                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
   15352                     }
   15353                 }
   15354             }
   15355             // All the special cases have been taken care of.
   15356             // Return result based on recommended install location.
   15357             if (onSd) {
   15358                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
   15359             }
   15360             return pkgLite.recommendedInstallLocation;
   15361         }
   15362 
   15363         /*
   15364          * Invoke remote method to get package information and install
   15365          * location values. Override install location based on default
   15366          * policy if needed and then create install arguments based
   15367          * on the install location.
   15368          */
   15369         public void handleStartCopy() throws RemoteException {
   15370             int ret = PackageManager.INSTALL_SUCCEEDED;
   15371 
   15372             // If we're already staged, we've firmly committed to an install location
   15373             if (origin.staged) {
   15374                 if (origin.file != null) {
   15375                     installFlags |= PackageManager.INSTALL_INTERNAL;
   15376                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
   15377                 } else {
   15378                     throw new IllegalStateException("Invalid stage location");
   15379                 }
   15380             }
   15381 
   15382             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
   15383             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
   15384             final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
   15385             PackageInfoLite pkgLite = null;
   15386 
   15387             if (onInt && onSd) {
   15388                 // Check if both bits are set.
   15389                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
   15390                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
   15391             } else if (onSd && ephemeral) {
   15392                 Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
   15393                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
   15394             } else {
   15395                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
   15396                         packageAbiOverride);
   15397 
   15398                 if (DEBUG_INSTANT && ephemeral) {
   15399                     Slog.v(TAG, "pkgLite for install: " + pkgLite);
   15400                 }
   15401 
   15402                 /*
   15403                  * If we have too little free space, try to free cache
   15404                  * before giving up.
   15405                  */
   15406                 if (!origin.staged && pkgLite.recommendedInstallLocation
   15407                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
   15408                     // TODO: focus freeing disk space on the target device
   15409                     final StorageManager storage = StorageManager.from(mContext);
   15410                     final long lowThreshold = storage.getStorageLowBytes(
   15411                             Environment.getDataDirectory());
   15412 
   15413                     final long sizeBytes = mContainerService.calculateInstalledSize(
   15414                             origin.resolvedPath, packageAbiOverride);
   15415 
   15416                     try {
   15417                         mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
   15418                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
   15419                                 installFlags, packageAbiOverride);
   15420                     } catch (InstallerException e) {
   15421                         Slog.w(TAG, "Failed to free cache", e);
   15422                     }
   15423 
   15424                     /*
   15425                      * The cache free must have deleted the file we
   15426                      * downloaded to install.
   15427                      *
   15428                      * TODO: fix the "freeCache" call to not delete
   15429                      *       the file we care about.
   15430                      */
   15431                     if (pkgLite.recommendedInstallLocation
   15432                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
   15433                         pkgLite.recommendedInstallLocation
   15434                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
   15435                     }
   15436                 }
   15437             }
   15438 
   15439             if (ret == PackageManager.INSTALL_SUCCEEDED) {
   15440                 int loc = pkgLite.recommendedInstallLocation;
   15441                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
   15442                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
   15443                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
   15444                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
   15445                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
   15446                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
   15447                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
   15448                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
   15449                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
   15450                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
   15451                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
   15452                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
   15453                 } else {
   15454                     // Override with defaults if needed.
   15455                     loc = installLocationPolicy(pkgLite);
   15456                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
   15457                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
   15458                     } else if (!onSd && !onInt) {
   15459                         // Override install location with flags
   15460                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
   15461                             // Set the flag to install on external media.
   15462                             installFlags |= PackageManager.INSTALL_EXTERNAL;
   15463                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
   15464                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
   15465                             if (DEBUG_INSTANT) {
   15466                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
   15467                             }
   15468                             installFlags |= PackageManager.INSTALL_INSTANT_APP;
   15469                             installFlags &= ~(PackageManager.INSTALL_EXTERNAL
   15470                                     |PackageManager.INSTALL_INTERNAL);
   15471                         } else {
   15472                             // Make sure the flag for installing on external
   15473                             // media is unset
   15474                             installFlags |= PackageManager.INSTALL_INTERNAL;
   15475                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
   15476                         }
   15477                     }
   15478                 }
   15479             }
   15480 
   15481             final InstallArgs args = createInstallArgs(this);
   15482             mArgs = args;
   15483 
   15484             if (ret == PackageManager.INSTALL_SUCCEEDED) {
   15485                 // TODO: http://b/22976637
   15486                 // Apps installed for "all" users use the device owner to verify the app
   15487                 UserHandle verifierUser = getUser();
   15488                 if (verifierUser == UserHandle.ALL) {
   15489                     verifierUser = UserHandle.SYSTEM;
   15490                 }
   15491 
   15492                 /*
   15493                  * Determine if we have any installed package verifiers. If we
   15494                  * do, then we'll defer to them to verify the packages.
   15495                  */
   15496                 final int requiredUid = mRequiredVerifierPackage == null ? -1
   15497                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
   15498                                 verifierUser.getIdentifier());
   15499                 final int installerUid =
   15500                         verificationInfo == null ? -1 : verificationInfo.installerUid;
   15501                 if (!origin.existing && requiredUid != -1
   15502                         && isVerificationEnabled(
   15503                                 verifierUser.getIdentifier(), installFlags, installerUid)) {
   15504                     final Intent verification = new Intent(
   15505                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
   15506                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
   15507                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
   15508                             PACKAGE_MIME_TYPE);
   15509                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   15510 
   15511                     // Query all live verifiers based on current user state
   15512                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
   15513                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
   15514                             false /*allowDynamicSplits*/);
   15515 
   15516                     if (DEBUG_VERIFY) {
   15517                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
   15518                                 + verification.toString() + " with " + pkgLite.verifiers.length
   15519                                 + " optional verifiers");
   15520                     }
   15521 
   15522                     final int verificationId = mPendingVerificationToken++;
   15523 
   15524                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
   15525 
   15526                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
   15527                             installerPackageName);
   15528 
   15529                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
   15530                             installFlags);
   15531 
   15532                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
   15533                             pkgLite.packageName);
   15534 
   15535                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
   15536                             pkgLite.versionCode);
   15537 
   15538                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
   15539                             pkgLite.getLongVersionCode());
   15540 
   15541                     if (verificationInfo != null) {
   15542                         if (verificationInfo.originatingUri != null) {
   15543                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
   15544                                     verificationInfo.originatingUri);
   15545                         }
   15546                         if (verificationInfo.referrer != null) {
   15547                             verification.putExtra(Intent.EXTRA_REFERRER,
   15548                                     verificationInfo.referrer);
   15549                         }
   15550                         if (verificationInfo.originatingUid >= 0) {
   15551                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
   15552                                     verificationInfo.originatingUid);
   15553                         }
   15554                         if (verificationInfo.installerUid >= 0) {
   15555                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
   15556                                     verificationInfo.installerUid);
   15557                         }
   15558                     }
   15559 
   15560                     final PackageVerificationState verificationState = new PackageVerificationState(
   15561                             requiredUid, args);
   15562 
   15563                     mPendingVerification.append(verificationId, verificationState);
   15564 
   15565                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
   15566                             receivers, verificationState);
   15567 
   15568                     DeviceIdleController.LocalService idleController = getDeviceIdleController();
   15569                     final long idleDuration = getVerificationTimeout();
   15570 
   15571                     /*
   15572                      * If any sufficient verifiers were listed in the package
   15573                      * manifest, attempt to ask them.
   15574                      */
   15575                     if (sufficientVerifiers != null) {
   15576                         final int N = sufficientVerifiers.size();
   15577                         if (N == 0) {
   15578                             Slog.i(TAG, "Additional verifiers required, but none installed.");
   15579                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   15580                         } else {
   15581                             for (int i = 0; i < N; i++) {
   15582                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
   15583                                 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
   15584                                         verifierComponent.getPackageName(), idleDuration,
   15585                                         verifierUser.getIdentifier(), false, "package verifier");
   15586 
   15587                                 final Intent sufficientIntent = new Intent(verification);
   15588                                 sufficientIntent.setComponent(verifierComponent);
   15589                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
   15590                             }
   15591                         }
   15592                     }
   15593 
   15594                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
   15595                             mRequiredVerifierPackage, receivers);
   15596                     if (ret == PackageManager.INSTALL_SUCCEEDED
   15597                             && mRequiredVerifierPackage != null) {
   15598                         Trace.asyncTraceBegin(
   15599                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
   15600                         /*
   15601                          * Send the intent to the required verification agent,
   15602                          * but only start the verification timeout after the
   15603                          * target BroadcastReceivers have run.
   15604                          */
   15605                         verification.setComponent(requiredVerifierComponent);
   15606                         idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
   15607                                 mRequiredVerifierPackage, idleDuration,
   15608                                 verifierUser.getIdentifier(), false, "package verifier");
   15609                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
   15610                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   15611                                 new BroadcastReceiver() {
   15612                                     @Override
   15613                                     public void onReceive(Context context, Intent intent) {
   15614                                         final Message msg = mHandler
   15615                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
   15616                                         msg.arg1 = verificationId;
   15617                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
   15618                                     }
   15619                                 }, null, 0, null, null);
   15620 
   15621                         /*
   15622                          * We don't want the copy to proceed until verification
   15623                          * succeeds, so null out this field.
   15624                          */
   15625                         mArgs = null;
   15626                     }
   15627                 } else {
   15628                     /*
   15629                      * No package verification is enabled, so immediately start
   15630                      * the remote call to initiate copy using temporary file.
   15631                      */
   15632                     ret = args.copyApk(mContainerService, true);
   15633                 }
   15634             }
   15635 
   15636             mRet = ret;
   15637         }
   15638 
   15639         @Override
   15640         void handleReturnCode() {
   15641             // If mArgs is null, then MCS couldn't be reached. When it
   15642             // reconnects, it will try again to install. At that point, this
   15643             // will succeed.
   15644             if (mArgs != null) {
   15645                 processPendingInstall(mArgs, mRet);
   15646             }
   15647         }
   15648 
   15649         @Override
   15650         void handleServiceError() {
   15651             mArgs = createInstallArgs(this);
   15652             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   15653         }
   15654     }
   15655 
   15656     private InstallArgs createInstallArgs(InstallParams params) {
   15657         if (params.move != null) {
   15658             return new MoveInstallArgs(params);
   15659         } else {
   15660             return new FileInstallArgs(params);
   15661         }
   15662     }
   15663 
   15664     /**
   15665      * Create args that describe an existing installed package. Typically used
   15666      * when cleaning up old installs, or used as a move source.
   15667      */
   15668     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
   15669             String resourcePath, String[] instructionSets) {
   15670         return new FileInstallArgs(codePath, resourcePath, instructionSets);
   15671     }
   15672 
   15673     static abstract class InstallArgs {
   15674         /** @see InstallParams#origin */
   15675         final OriginInfo origin;
   15676         /** @see InstallParams#move */
   15677         final MoveInfo move;
   15678 
   15679         final IPackageInstallObserver2 observer;
   15680         // Always refers to PackageManager flags only
   15681         final int installFlags;
   15682         final String installerPackageName;
   15683         final String volumeUuid;
   15684         final UserHandle user;
   15685         final String abiOverride;
   15686         final String[] installGrantPermissions;
   15687         /** If non-null, drop an async trace when the install completes */
   15688         final String traceMethod;
   15689         final int traceCookie;
   15690         final PackageParser.SigningDetails signingDetails;
   15691         final int installReason;
   15692 
   15693         // The list of instruction sets supported by this app. This is currently
   15694         // only used during the rmdex() phase to clean up resources. We can get rid of this
   15695         // if we move dex files under the common app path.
   15696         /* nullable */ String[] instructionSets;
   15697 
   15698         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
   15699                 int installFlags, String installerPackageName, String volumeUuid,
   15700                 UserHandle user, String[] instructionSets,
   15701                 String abiOverride, String[] installGrantPermissions,
   15702                 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
   15703                 int installReason) {
   15704             this.origin = origin;
   15705             this.move = move;
   15706             this.installFlags = installFlags;
   15707             this.observer = observer;
   15708             this.installerPackageName = installerPackageName;
   15709             this.volumeUuid = volumeUuid;
   15710             this.user = user;
   15711             this.instructionSets = instructionSets;
   15712             this.abiOverride = abiOverride;
   15713             this.installGrantPermissions = installGrantPermissions;
   15714             this.traceMethod = traceMethod;
   15715             this.traceCookie = traceCookie;
   15716             this.signingDetails = signingDetails;
   15717             this.installReason = installReason;
   15718         }
   15719 
   15720         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
   15721         abstract int doPreInstall(int status);
   15722 
   15723         /**
   15724          * Rename package into final resting place. All paths on the given
   15725          * scanned package should be updated to reflect the rename.
   15726          */
   15727         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
   15728         abstract int doPostInstall(int status, int uid);
   15729 
   15730         /** @see PackageSettingBase#codePathString */
   15731         abstract String getCodePath();
   15732         /** @see PackageSettingBase#resourcePathString */
   15733         abstract String getResourcePath();
   15734 
   15735         // Need installer lock especially for dex file removal.
   15736         abstract void cleanUpResourcesLI();
   15737         abstract boolean doPostDeleteLI(boolean delete);
   15738 
   15739         /**
   15740          * Called before the source arguments are copied. This is used mostly
   15741          * for MoveParams when it needs to read the source file to put it in the
   15742          * destination.
   15743          */
   15744         int doPreCopy() {
   15745             return PackageManager.INSTALL_SUCCEEDED;
   15746         }
   15747 
   15748         /**
   15749          * Called after the source arguments are copied. This is used mostly for
   15750          * MoveParams when it needs to read the source file to put it in the
   15751          * destination.
   15752          */
   15753         int doPostCopy(int uid) {
   15754             return PackageManager.INSTALL_SUCCEEDED;
   15755         }
   15756 
   15757         protected boolean isFwdLocked() {
   15758             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
   15759         }
   15760 
   15761         protected boolean isExternalAsec() {
   15762             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
   15763         }
   15764 
   15765         protected boolean isEphemeral() {
   15766             return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
   15767         }
   15768 
   15769         UserHandle getUser() {
   15770             return user;
   15771         }
   15772     }
   15773 
   15774     void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
   15775         if (!allCodePaths.isEmpty()) {
   15776             if (instructionSets == null) {
   15777                 throw new IllegalStateException("instructionSet == null");
   15778             }
   15779             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
   15780             for (String codePath : allCodePaths) {
   15781                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
   15782                     try {
   15783                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
   15784                     } catch (InstallerException ignored) {
   15785                     }
   15786                 }
   15787             }
   15788         }
   15789     }
   15790 
   15791     /**
   15792      * Logic to handle installation of non-ASEC applications, including copying
   15793      * and renaming logic.
   15794      */
   15795     class FileInstallArgs extends InstallArgs {
   15796         private File codeFile;
   15797         private File resourceFile;
   15798 
   15799         // Example topology:
   15800         // /data/app/com.example/base.apk
   15801         // /data/app/com.example/split_foo.apk
   15802         // /data/app/com.example/lib/arm/libfoo.so
   15803         // /data/app/com.example/lib/arm64/libfoo.so
   15804         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
   15805 
   15806         /** New install */
   15807         FileInstallArgs(InstallParams params) {
   15808             super(params.origin, params.move, params.observer, params.installFlags,
   15809                     params.installerPackageName, params.volumeUuid,
   15810                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
   15811                     params.grantedRuntimePermissions,
   15812                     params.traceMethod, params.traceCookie, params.signingDetails,
   15813                     params.installReason);
   15814             if (isFwdLocked()) {
   15815                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
   15816             }
   15817         }
   15818 
   15819         /** Existing install */
   15820         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
   15821             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
   15822                     null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
   15823                     PackageManager.INSTALL_REASON_UNKNOWN);
   15824             this.codeFile = (codePath != null) ? new File(codePath) : null;
   15825             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
   15826         }
   15827 
   15828         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
   15829             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
   15830             try {
   15831                 return doCopyApk(imcs, temp);
   15832             } finally {
   15833                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   15834             }
   15835         }
   15836 
   15837         private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
   15838             if (origin.staged) {
   15839                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
   15840                 codeFile = origin.file;
   15841                 resourceFile = origin.file;
   15842                 return PackageManager.INSTALL_SUCCEEDED;
   15843             }
   15844 
   15845             try {
   15846                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
   15847                 final File tempDir =
   15848                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
   15849                 codeFile = tempDir;
   15850                 resourceFile = tempDir;
   15851             } catch (IOException e) {
   15852                 Slog.w(TAG, "Failed to create copy file: " + e);
   15853                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
   15854             }
   15855 
   15856             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
   15857                 @Override
   15858                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
   15859                     if (!FileUtils.isValidExtFilename(name)) {
   15860                         throw new IllegalArgumentException("Invalid filename: " + name);
   15861                     }
   15862                     try {
   15863                         final File file = new File(codeFile, name);
   15864                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
   15865                                 O_RDWR | O_CREAT, 0644);
   15866                         Os.chmod(file.getAbsolutePath(), 0644);
   15867                         return new ParcelFileDescriptor(fd);
   15868                     } catch (ErrnoException e) {
   15869                         throw new RemoteException("Failed to open: " + e.getMessage());
   15870                     }
   15871                 }
   15872             };
   15873 
   15874             int ret = PackageManager.INSTALL_SUCCEEDED;
   15875             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
   15876             if (ret != PackageManager.INSTALL_SUCCEEDED) {
   15877                 Slog.e(TAG, "Failed to copy package");
   15878                 return ret;
   15879             }
   15880 
   15881             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
   15882             NativeLibraryHelper.Handle handle = null;
   15883             try {
   15884                 handle = NativeLibraryHelper.Handle.create(codeFile);
   15885                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
   15886                         abiOverride);
   15887             } catch (IOException e) {
   15888                 Slog.e(TAG, "Copying native libraries failed", e);
   15889                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   15890             } finally {
   15891                 IoUtils.closeQuietly(handle);
   15892             }
   15893 
   15894             return ret;
   15895         }
   15896 
   15897         int doPreInstall(int status) {
   15898             if (status != PackageManager.INSTALL_SUCCEEDED) {
   15899                 cleanUp();
   15900             }
   15901             return status;
   15902         }
   15903 
   15904         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
   15905             if (status != PackageManager.INSTALL_SUCCEEDED) {
   15906                 cleanUp();
   15907                 return false;
   15908             }
   15909 
   15910             final File targetDir = codeFile.getParentFile();
   15911             final File beforeCodeFile = codeFile;
   15912             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
   15913 
   15914             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
   15915             try {
   15916                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
   15917             } catch (ErrnoException e) {
   15918                 Slog.w(TAG, "Failed to rename", e);
   15919                 return false;
   15920             }
   15921 
   15922             if (!SELinux.restoreconRecursive(afterCodeFile)) {
   15923                 Slog.w(TAG, "Failed to restorecon");
   15924                 return false;
   15925             }
   15926 
   15927             // Reflect the rename internally
   15928             codeFile = afterCodeFile;
   15929             resourceFile = afterCodeFile;
   15930 
   15931             // Reflect the rename in scanned details
   15932             try {
   15933                 pkg.setCodePath(afterCodeFile.getCanonicalPath());
   15934             } catch (IOException e) {
   15935                 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
   15936                 return false;
   15937             }
   15938             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
   15939                     afterCodeFile, pkg.baseCodePath));
   15940             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
   15941                     afterCodeFile, pkg.splitCodePaths));
   15942 
   15943             // Reflect the rename in app info
   15944             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
   15945             pkg.setApplicationInfoCodePath(pkg.codePath);
   15946             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
   15947             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
   15948             pkg.setApplicationInfoResourcePath(pkg.codePath);
   15949             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
   15950             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
   15951 
   15952             return true;
   15953         }
   15954 
   15955         int doPostInstall(int status, int uid) {
   15956             if (status != PackageManager.INSTALL_SUCCEEDED) {
   15957                 cleanUp();
   15958             }
   15959             return status;
   15960         }
   15961 
   15962         @Override
   15963         String getCodePath() {
   15964             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
   15965         }
   15966 
   15967         @Override
   15968         String getResourcePath() {
   15969             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
   15970         }
   15971 
   15972         private boolean cleanUp() {
   15973             if (codeFile == null || !codeFile.exists()) {
   15974                 return false;
   15975             }
   15976 
   15977             removeCodePathLI(codeFile);
   15978 
   15979             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
   15980                 resourceFile.delete();
   15981             }
   15982 
   15983             return true;
   15984         }
   15985 
   15986         void cleanUpResourcesLI() {
   15987             // Try enumerating all code paths before deleting
   15988             List<String> allCodePaths = Collections.EMPTY_LIST;
   15989             if (codeFile != null && codeFile.exists()) {
   15990                 try {
   15991                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
   15992                     allCodePaths = pkg.getAllCodePaths();
   15993                 } catch (PackageParserException e) {
   15994                     // Ignored; we tried our best
   15995                 }
   15996             }
   15997 
   15998             cleanUp();
   15999             removeDexFiles(allCodePaths, instructionSets);
   16000         }
   16001 
   16002         boolean doPostDeleteLI(boolean delete) {
   16003             // XXX err, shouldn't we respect the delete flag?
   16004             cleanUpResourcesLI();
   16005             return true;
   16006         }
   16007     }
   16008 
   16009     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
   16010             PackageManagerException {
   16011         if (copyRet < 0) {
   16012             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
   16013                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
   16014                 throw new PackageManagerException(copyRet, message);
   16015             }
   16016         }
   16017     }
   16018 
   16019     /**
   16020      * Extract the StorageManagerService "container ID" from the full code path of an
   16021      * .apk.
   16022      */
   16023     static String cidFromCodePath(String fullCodePath) {
   16024         int eidx = fullCodePath.lastIndexOf("/");
   16025         String subStr1 = fullCodePath.substring(0, eidx);
   16026         int sidx = subStr1.lastIndexOf("/");
   16027         return subStr1.substring(sidx+1, eidx);
   16028     }
   16029 
   16030     /**
   16031      * Logic to handle movement of existing installed applications.
   16032      */
   16033     class MoveInstallArgs extends InstallArgs {
   16034         private File codeFile;
   16035         private File resourceFile;
   16036 
   16037         /** New install */
   16038         MoveInstallArgs(InstallParams params) {
   16039             super(params.origin, params.move, params.observer, params.installFlags,
   16040                     params.installerPackageName, params.volumeUuid,
   16041                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
   16042                     params.grantedRuntimePermissions,
   16043                     params.traceMethod, params.traceCookie, params.signingDetails,
   16044                     params.installReason);
   16045         }
   16046 
   16047         int copyApk(IMediaContainerService imcs, boolean temp) {
   16048             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
   16049                     + move.fromUuid + " to " + move.toUuid);
   16050             synchronized (mInstaller) {
   16051                 try {
   16052                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
   16053                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
   16054                 } catch (InstallerException e) {
   16055                     Slog.w(TAG, "Failed to move app", e);
   16056                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   16057                 }
   16058             }
   16059 
   16060             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
   16061             resourceFile = codeFile;
   16062             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
   16063 
   16064             return PackageManager.INSTALL_SUCCEEDED;
   16065         }
   16066 
   16067         int doPreInstall(int status) {
   16068             if (status != PackageManager.INSTALL_SUCCEEDED) {
   16069                 cleanUp(move.toUuid);
   16070             }
   16071             return status;
   16072         }
   16073 
   16074         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
   16075             if (status != PackageManager.INSTALL_SUCCEEDED) {
   16076                 cleanUp(move.toUuid);
   16077                 return false;
   16078             }
   16079 
   16080             // Reflect the move in app info
   16081             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
   16082             pkg.setApplicationInfoCodePath(pkg.codePath);
   16083             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
   16084             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
   16085             pkg.setApplicationInfoResourcePath(pkg.codePath);
   16086             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
   16087             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
   16088 
   16089             return true;
   16090         }
   16091 
   16092         int doPostInstall(int status, int uid) {
   16093             if (status == PackageManager.INSTALL_SUCCEEDED) {
   16094                 cleanUp(move.fromUuid);
   16095             } else {
   16096                 cleanUp(move.toUuid);
   16097             }
   16098             return status;
   16099         }
   16100 
   16101         @Override
   16102         String getCodePath() {
   16103             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
   16104         }
   16105 
   16106         @Override
   16107         String getResourcePath() {
   16108             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
   16109         }
   16110 
   16111         private boolean cleanUp(String volumeUuid) {
   16112             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
   16113                     move.dataAppName);
   16114             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
   16115             final int[] userIds = sUserManager.getUserIds();
   16116             synchronized (mInstallLock) {
   16117                 // Clean up both app data and code
   16118                 // All package moves are frozen until finished
   16119                 for (int userId : userIds) {
   16120                     try {
   16121                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
   16122                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
   16123                     } catch (InstallerException e) {
   16124                         Slog.w(TAG, String.valueOf(e));
   16125                     }
   16126                 }
   16127                 removeCodePathLI(codeFile);
   16128             }
   16129             return true;
   16130         }
   16131 
   16132         void cleanUpResourcesLI() {
   16133             throw new UnsupportedOperationException();
   16134         }
   16135 
   16136         boolean doPostDeleteLI(boolean delete) {
   16137             throw new UnsupportedOperationException();
   16138         }
   16139     }
   16140 
   16141     static String getAsecPackageName(String packageCid) {
   16142         int idx = packageCid.lastIndexOf("-");
   16143         if (idx == -1) {
   16144             return packageCid;
   16145         }
   16146         return packageCid.substring(0, idx);
   16147     }
   16148 
   16149     // Utility method used to create code paths based on package name and available index.
   16150     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
   16151         String idxStr = "";
   16152         int idx = 1;
   16153         // Fall back to default value of idx=1 if prefix is not
   16154         // part of oldCodePath
   16155         if (oldCodePath != null) {
   16156             String subStr = oldCodePath;
   16157             // Drop the suffix right away
   16158             if (suffix != null && subStr.endsWith(suffix)) {
   16159                 subStr = subStr.substring(0, subStr.length() - suffix.length());
   16160             }
   16161             // If oldCodePath already contains prefix find out the
   16162             // ending index to either increment or decrement.
   16163             int sidx = subStr.lastIndexOf(prefix);
   16164             if (sidx != -1) {
   16165                 subStr = subStr.substring(sidx + prefix.length());
   16166                 if (subStr != null) {
   16167                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
   16168                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
   16169                     }
   16170                     try {
   16171                         idx = Integer.parseInt(subStr);
   16172                         if (idx <= 1) {
   16173                             idx++;
   16174                         } else {
   16175                             idx--;
   16176                         }
   16177                     } catch(NumberFormatException e) {
   16178                     }
   16179                 }
   16180             }
   16181         }
   16182         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
   16183         return prefix + idxStr;
   16184     }
   16185 
   16186     private File getNextCodePath(File targetDir, String packageName) {
   16187         File result;
   16188         SecureRandom random = new SecureRandom();
   16189         byte[] bytes = new byte[16];
   16190         do {
   16191             random.nextBytes(bytes);
   16192             String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
   16193             result = new File(targetDir, packageName + "-" + suffix);
   16194         } while (result.exists());
   16195         return result;
   16196     }
   16197 
   16198     // Utility method that returns the relative package path with respect
   16199     // to the installation directory. Like say for /data/data/com.test-1.apk
   16200     // string com.test-1 is returned.
   16201     static String deriveCodePathName(String codePath) {
   16202         if (codePath == null) {
   16203             return null;
   16204         }
   16205         final File codeFile = new File(codePath);
   16206         final String name = codeFile.getName();
   16207         if (codeFile.isDirectory()) {
   16208             return name;
   16209         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
   16210             final int lastDot = name.lastIndexOf('.');
   16211             return name.substring(0, lastDot);
   16212         } else {
   16213             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
   16214             return null;
   16215         }
   16216     }
   16217 
   16218     static class PackageInstalledInfo {
   16219         String name;
   16220         int uid;
   16221         // The set of users that originally had this package installed.
   16222         int[] origUsers;
   16223         // The set of users that now have this package installed.
   16224         int[] newUsers;
   16225         PackageParser.Package pkg;
   16226         int returnCode;
   16227         String returnMsg;
   16228         String installerPackageName;
   16229         PackageRemovedInfo removedInfo;
   16230         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
   16231 
   16232         public void setError(int code, String msg) {
   16233             setReturnCode(code);
   16234             setReturnMessage(msg);
   16235             Slog.w(TAG, msg);
   16236         }
   16237 
   16238         public void setError(String msg, PackageParserException e) {
   16239             setReturnCode(e.error);
   16240             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
   16241             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
   16242             for (int i = 0; i < childCount; i++) {
   16243                 addedChildPackages.valueAt(i).setError(msg, e);
   16244             }
   16245             Slog.w(TAG, msg, e);
   16246         }
   16247 
   16248         public void setError(String msg, PackageManagerException e) {
   16249             returnCode = e.error;
   16250             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
   16251             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
   16252             for (int i = 0; i < childCount; i++) {
   16253                 addedChildPackages.valueAt(i).setError(msg, e);
   16254             }
   16255             Slog.w(TAG, msg, e);
   16256         }
   16257 
   16258         public void setReturnCode(int returnCode) {
   16259             this.returnCode = returnCode;
   16260             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
   16261             for (int i = 0; i < childCount; i++) {
   16262                 addedChildPackages.valueAt(i).returnCode = returnCode;
   16263             }
   16264         }
   16265 
   16266         private void setReturnMessage(String returnMsg) {
   16267             this.returnMsg = returnMsg;
   16268             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
   16269             for (int i = 0; i < childCount; i++) {
   16270                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
   16271             }
   16272         }
   16273 
   16274         // In some error cases we want to convey more info back to the observer
   16275         String origPackage;
   16276         String origPermission;
   16277     }
   16278 
   16279     /*
   16280      * Install a non-existing package.
   16281      */
   16282     private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
   16283             final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
   16284             String volumeUuid, PackageInstalledInfo res, int installReason) {
   16285         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
   16286 
   16287         // Remember this for later, in case we need to rollback this install
   16288         String pkgName = pkg.packageName;
   16289 
   16290         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
   16291 
   16292         synchronized(mPackages) {
   16293             final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
   16294             if (renamedPackage != null) {
   16295                 // A package with the same name is already installed, though
   16296                 // it has been renamed to an older name.  The package we
   16297                 // are trying to install should be installed as an update to
   16298                 // the existing one, but that has not been requested, so bail.
   16299                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
   16300                         + " without first uninstalling package running as "
   16301                         + renamedPackage);
   16302                 return;
   16303             }
   16304             if (mPackages.containsKey(pkgName)) {
   16305                 // Don't allow installation over an existing package with the same name.
   16306                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
   16307                         + " without first uninstalling.");
   16308                 return;
   16309             }
   16310         }
   16311 
   16312         try {
   16313             PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
   16314                     System.currentTimeMillis(), user);
   16315 
   16316             updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
   16317 
   16318             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   16319                 prepareAppDataAfterInstallLIF(newPackage);
   16320 
   16321             } else {
   16322                 // Remove package from internal structures, but keep around any
   16323                 // data that might have already existed
   16324                 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
   16325                         PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
   16326             }
   16327         } catch (PackageManagerException e) {
   16328             res.setError("Package couldn't be installed in " + pkg.codePath, e);
   16329         }
   16330 
   16331         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   16332     }
   16333 
   16334     private static void updateDigest(MessageDigest digest, File file) throws IOException {
   16335         try (DigestInputStream digestStream =
   16336                 new DigestInputStream(new FileInputStream(file), digest)) {
   16337             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
   16338         }
   16339     }
   16340 
   16341     private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
   16342             final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
   16343             PackageInstalledInfo res, int installReason) {
   16344         final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
   16345 
   16346         final PackageParser.Package oldPackage;
   16347         final PackageSetting ps;
   16348         final String pkgName = pkg.packageName;
   16349         final int[] allUsers;
   16350         final int[] installedUsers;
   16351 
   16352         synchronized(mPackages) {
   16353             oldPackage = mPackages.get(pkgName);
   16354             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
   16355 
   16356             // don't allow upgrade to target a release SDK from a pre-release SDK
   16357             final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
   16358                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
   16359             final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
   16360                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
   16361             if (oldTargetsPreRelease
   16362                     && !newTargetsPreRelease
   16363                     && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
   16364                 Slog.w(TAG, "Can't install package targeting released sdk");
   16365                 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
   16366                 return;
   16367             }
   16368 
   16369             ps = mSettings.mPackages.get(pkgName);
   16370 
   16371             // verify signatures are valid
   16372             final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   16373             if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
   16374                 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
   16375                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
   16376                             "New package not signed by keys specified by upgrade-keysets: "
   16377                                     + pkgName);
   16378                     return;
   16379                 }
   16380             } else {
   16381 
   16382                 // default to original signature matching
   16383                 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
   16384                         PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
   16385                                 && !oldPackage.mSigningDetails.checkCapability(
   16386                                         pkg.mSigningDetails,
   16387                                         PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
   16388                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
   16389                             "New package has a different signature: " + pkgName);
   16390                     return;
   16391                 }
   16392             }
   16393 
   16394             // don't allow a system upgrade unless the upgrade hash matches
   16395             if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
   16396                 byte[] digestBytes = null;
   16397                 try {
   16398                     final MessageDigest digest = MessageDigest.getInstance("SHA-512");
   16399                     updateDigest(digest, new File(pkg.baseCodePath));
   16400                     if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
   16401                         for (String path : pkg.splitCodePaths) {
   16402                             updateDigest(digest, new File(path));
   16403                         }
   16404                     }
   16405                     digestBytes = digest.digest();
   16406                 } catch (NoSuchAlgorithmException | IOException e) {
   16407                     res.setError(INSTALL_FAILED_INVALID_APK,
   16408                             "Could not compute hash: " + pkgName);
   16409                     return;
   16410                 }
   16411                 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
   16412                     res.setError(INSTALL_FAILED_INVALID_APK,
   16413                             "New package fails restrict-update check: " + pkgName);
   16414                     return;
   16415                 }
   16416                 // retain upgrade restriction
   16417                 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
   16418             }
   16419 
   16420             // Check for shared user id changes
   16421             String invalidPackageName =
   16422                     getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
   16423             if (invalidPackageName != null) {
   16424                 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
   16425                         "Package " + invalidPackageName + " tried to change user "
   16426                                 + oldPackage.mSharedUserId);
   16427                 return;
   16428             }
   16429 
   16430             // check if the new package supports all of the abis which the old package supports
   16431             boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
   16432             boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
   16433             if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
   16434                 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
   16435                         "Update to package " + pkgName + " doesn't support multi arch");
   16436                 return;
   16437             }
   16438 
   16439             // In case of rollback, remember per-user/profile install state
   16440             allUsers = sUserManager.getUserIds();
   16441             installedUsers = ps.queryInstalledUsers(allUsers, true);
   16442 
   16443             // don't allow an upgrade from full to ephemeral
   16444             if (isInstantApp) {
   16445                 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
   16446                     for (int currentUser : allUsers) {
   16447                         if (!ps.getInstantApp(currentUser)) {
   16448                             // can't downgrade from full to instant
   16449                             Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
   16450                                     + " for user: " + currentUser);
   16451                             res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
   16452                             return;
   16453                         }
   16454                     }
   16455                 } else if (!ps.getInstantApp(user.getIdentifier())) {
   16456                     // can't downgrade from full to instant
   16457                     Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
   16458                             + " for user: " + user.getIdentifier());
   16459                     res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
   16460                     return;
   16461                 }
   16462             }
   16463         }
   16464 
   16465         // Update what is removed
   16466         res.removedInfo = new PackageRemovedInfo(this);
   16467         res.removedInfo.uid = oldPackage.applicationInfo.uid;
   16468         res.removedInfo.removedPackage = oldPackage.packageName;
   16469         res.removedInfo.installerPackageName = ps.installerPackageName;
   16470         res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
   16471         res.removedInfo.isUpdate = true;
   16472         res.removedInfo.origUsers = installedUsers;
   16473         res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
   16474         for (int i = 0; i < installedUsers.length; i++) {
   16475             final int userId = installedUsers[i];
   16476             res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
   16477         }
   16478 
   16479         final int childCount = (oldPackage.childPackages != null)
   16480                 ? oldPackage.childPackages.size() : 0;
   16481         for (int i = 0; i < childCount; i++) {
   16482             boolean childPackageUpdated = false;
   16483             PackageParser.Package childPkg = oldPackage.childPackages.get(i);
   16484             final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
   16485             if (res.addedChildPackages != null) {
   16486                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
   16487                 if (childRes != null) {
   16488                     childRes.removedInfo.uid = childPkg.applicationInfo.uid;
   16489                     childRes.removedInfo.removedPackage = childPkg.packageName;
   16490                     if (childPs != null) {
   16491                         childRes.removedInfo.installerPackageName = childPs.installerPackageName;
   16492                     }
   16493                     childRes.removedInfo.isUpdate = true;
   16494                     childRes.removedInfo.installReasons = res.removedInfo.installReasons;
   16495                     childPackageUpdated = true;
   16496                 }
   16497             }
   16498             if (!childPackageUpdated) {
   16499                 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
   16500                 childRemovedRes.removedPackage = childPkg.packageName;
   16501                 if (childPs != null) {
   16502                     childRemovedRes.installerPackageName = childPs.installerPackageName;
   16503                 }
   16504                 childRemovedRes.isUpdate = false;
   16505                 childRemovedRes.dataRemoved = true;
   16506                 synchronized (mPackages) {
   16507                     if (childPs != null) {
   16508                         childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
   16509                     }
   16510                 }
   16511                 if (res.removedInfo.removedChildPackages == null) {
   16512                     res.removedInfo.removedChildPackages = new ArrayMap<>();
   16513                 }
   16514                 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
   16515             }
   16516         }
   16517 
   16518         boolean sysPkg = (isSystemApp(oldPackage));
   16519         if (sysPkg) {
   16520             // Set the system/privileged/oem/vendor/product flags as needed
   16521             final boolean privileged =
   16522                     (oldPackage.applicationInfo.privateFlags
   16523                             & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
   16524             final boolean oem =
   16525                     (oldPackage.applicationInfo.privateFlags
   16526                             & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
   16527             final boolean vendor =
   16528                     (oldPackage.applicationInfo.privateFlags
   16529                             & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
   16530             final boolean product =
   16531                     (oldPackage.applicationInfo.privateFlags
   16532                             & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
   16533             final @ParseFlags int systemParseFlags = parseFlags;
   16534             final @ScanFlags int systemScanFlags = scanFlags
   16535                     | SCAN_AS_SYSTEM
   16536                     | (privileged ? SCAN_AS_PRIVILEGED : 0)
   16537                     | (oem ? SCAN_AS_OEM : 0)
   16538                     | (vendor ? SCAN_AS_VENDOR : 0)
   16539                     | (product ? SCAN_AS_PRODUCT : 0);
   16540 
   16541             replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
   16542                     user, allUsers, installerPackageName, res, installReason);
   16543         } else {
   16544             replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
   16545                     user, allUsers, installerPackageName, res, installReason);
   16546         }
   16547     }
   16548 
   16549     private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
   16550             PackageParser.Package pkg, final @ParseFlags int parseFlags,
   16551             final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
   16552             String installerPackageName, PackageInstalledInfo res, int installReason) {
   16553         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
   16554                 + deletedPackage);
   16555 
   16556         String pkgName = deletedPackage.packageName;
   16557         boolean deletedPkg = true;
   16558         boolean addedPkg = false;
   16559         boolean updatedSettings = false;
   16560         final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
   16561         final int deleteFlags = PackageManager.DELETE_KEEP_DATA
   16562                 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
   16563 
   16564         final long origUpdateTime = (pkg.mExtras != null)
   16565                 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
   16566 
   16567         // First delete the existing package while retaining the data directory
   16568         if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
   16569                 res.removedInfo, true, pkg)) {
   16570             // If the existing package wasn't successfully deleted
   16571             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
   16572             deletedPkg = false;
   16573         } else {
   16574             // Successfully deleted the old package; proceed with replace.
   16575 
   16576             // If deleted package lived in a container, give users a chance to
   16577             // relinquish resources before killing.
   16578             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
   16579                 if (DEBUG_INSTALL) {
   16580                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
   16581                 }
   16582                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
   16583                 final ArrayList<String> pkgList = new ArrayList<String>(1);
   16584                 pkgList.add(deletedPackage.applicationInfo.packageName);
   16585                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
   16586             }
   16587 
   16588             clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
   16589                     | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   16590 
   16591             try {
   16592                 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
   16593                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
   16594                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
   16595                         installReason);
   16596 
   16597                 // Update the in-memory copy of the previous code paths.
   16598                 PackageSetting ps = mSettings.mPackages.get(pkgName);
   16599                 if (!killApp) {
   16600                     if (ps.oldCodePaths == null) {
   16601                         ps.oldCodePaths = new ArraySet<>();
   16602                     }
   16603                     Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
   16604                     if (deletedPackage.splitCodePaths != null) {
   16605                         Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
   16606                     }
   16607                 } else {
   16608                     ps.oldCodePaths = null;
   16609                 }
   16610                 if (ps.childPackageNames != null) {
   16611                     for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
   16612                         final String childPkgName = ps.childPackageNames.get(i);
   16613                         final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
   16614                         childPs.oldCodePaths = ps.oldCodePaths;
   16615                     }
   16616                 }
   16617                 prepareAppDataAfterInstallLIF(newPackage);
   16618                 addedPkg = true;
   16619                 mDexManager.notifyPackageUpdated(newPackage.packageName,
   16620                         newPackage.baseCodePath, newPackage.splitCodePaths);
   16621             } catch (PackageManagerException e) {
   16622                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
   16623             }
   16624         }
   16625 
   16626         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
   16627             if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
   16628 
   16629             // Revert all internal state mutations and added folders for the failed install
   16630             if (addedPkg) {
   16631                 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
   16632                         res.removedInfo, true, null);
   16633             }
   16634 
   16635             // Restore the old package
   16636             if (deletedPkg) {
   16637                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
   16638                 File restoreFile = new File(deletedPackage.codePath);
   16639                 // Parse old package
   16640                 boolean oldExternal = isExternal(deletedPackage);
   16641                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
   16642                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
   16643                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
   16644                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
   16645                 try {
   16646                     scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
   16647                             null);
   16648                 } catch (PackageManagerException e) {
   16649                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
   16650                             + e.getMessage());
   16651                     return;
   16652                 }
   16653 
   16654                 synchronized (mPackages) {
   16655                     // Ensure the installer package name up to date
   16656                     setInstallerPackageNameLPw(deletedPackage, installerPackageName);
   16657 
   16658                     // Update permissions for restored package
   16659                     mPermissionManager.updatePermissions(
   16660                             deletedPackage.packageName, deletedPackage, false, mPackages.values(),
   16661                             mPermissionCallback);
   16662 
   16663                     mSettings.writeLPr();
   16664                 }
   16665 
   16666                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
   16667             }
   16668         } else {
   16669             synchronized (mPackages) {
   16670                 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
   16671                 if (ps != null) {
   16672                     res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
   16673                     if (res.removedInfo.removedChildPackages != null) {
   16674                         final int childCount = res.removedInfo.removedChildPackages.size();
   16675                         // Iterate in reverse as we may modify the collection
   16676                         for (int i = childCount - 1; i >= 0; i--) {
   16677                             String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
   16678                             if (res.addedChildPackages.containsKey(childPackageName)) {
   16679                                 res.removedInfo.removedChildPackages.removeAt(i);
   16680                             } else {
   16681                                 PackageRemovedInfo childInfo = res.removedInfo
   16682                                         .removedChildPackages.valueAt(i);
   16683                                 childInfo.removedForAllUsers = mPackages.get(
   16684                                         childInfo.removedPackage) == null;
   16685                             }
   16686                         }
   16687                     }
   16688                 }
   16689             }
   16690         }
   16691     }
   16692 
   16693     private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
   16694             PackageParser.Package pkg, final @ParseFlags int parseFlags,
   16695             final @ScanFlags int scanFlags, UserHandle user,
   16696             int[] allUsers, String installerPackageName, PackageInstalledInfo res,
   16697             int installReason) {
   16698         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
   16699                 + ", old=" + deletedPackage);
   16700 
   16701         final boolean disabledSystem;
   16702 
   16703         // Remove existing system package
   16704         removePackageLI(deletedPackage, true);
   16705 
   16706         synchronized (mPackages) {
   16707             disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
   16708         }
   16709         if (!disabledSystem) {
   16710             // We didn't need to disable the .apk as a current system package,
   16711             // which means we are replacing another update that is already
   16712             // installed.  We need to make sure to delete the older one's .apk.
   16713             res.removedInfo.args = createInstallArgsForExisting(0,
   16714                     deletedPackage.applicationInfo.getCodePath(),
   16715                     deletedPackage.applicationInfo.getResourcePath(),
   16716                     getAppDexInstructionSets(deletedPackage.applicationInfo));
   16717         } else {
   16718             res.removedInfo.args = null;
   16719         }
   16720 
   16721         // Successfully disabled the old package. Now proceed with re-installation
   16722         clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
   16723                 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   16724 
   16725         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
   16726         pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
   16727                 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
   16728 
   16729         PackageParser.Package newPackage = null;
   16730         try {
   16731             // Add the package to the internal data structures
   16732             newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
   16733 
   16734             // Set the update and install times
   16735             PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
   16736             setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
   16737                     System.currentTimeMillis());
   16738 
   16739             // Update the package dynamic state if succeeded
   16740             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   16741                 // Now that the install succeeded make sure we remove data
   16742                 // directories for any child package the update removed.
   16743                 final int deletedChildCount = (deletedPackage.childPackages != null)
   16744                         ? deletedPackage.childPackages.size() : 0;
   16745                 final int newChildCount = (newPackage.childPackages != null)
   16746                         ? newPackage.childPackages.size() : 0;
   16747                 for (int i = 0; i < deletedChildCount; i++) {
   16748                     PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
   16749                     boolean childPackageDeleted = true;
   16750                     for (int j = 0; j < newChildCount; j++) {
   16751                         PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
   16752                         if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
   16753                             childPackageDeleted = false;
   16754                             break;
   16755                         }
   16756                     }
   16757                     if (childPackageDeleted) {
   16758                         PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
   16759                                 deletedChildPkg.packageName);
   16760                         if (ps != null && res.removedInfo.removedChildPackages != null) {
   16761                             PackageRemovedInfo removedChildRes = res.removedInfo
   16762                                     .removedChildPackages.get(deletedChildPkg.packageName);
   16763                             removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
   16764                             removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
   16765                         }
   16766                     }
   16767                 }
   16768 
   16769                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
   16770                         installReason);
   16771                 prepareAppDataAfterInstallLIF(newPackage);
   16772 
   16773                 mDexManager.notifyPackageUpdated(newPackage.packageName,
   16774                             newPackage.baseCodePath, newPackage.splitCodePaths);
   16775             }
   16776         } catch (PackageManagerException e) {
   16777             res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
   16778             res.setError("Package couldn't be installed in " + pkg.codePath, e);
   16779         }
   16780 
   16781         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
   16782             // Re installation failed. Restore old information
   16783             // Remove new pkg information
   16784             if (newPackage != null) {
   16785                 removeInstalledPackageLI(newPackage, true);
   16786             }
   16787             // Add back the old system package
   16788             try {
   16789                 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
   16790             } catch (PackageManagerException e) {
   16791                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
   16792             }
   16793 
   16794             synchronized (mPackages) {
   16795                 if (disabledSystem) {
   16796                     enableSystemPackageLPw(deletedPackage);
   16797                 }
   16798 
   16799                 // Ensure the installer package name up to date
   16800                 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
   16801 
   16802                 // Update permissions for restored package
   16803                 mPermissionManager.updatePermissions(
   16804                         deletedPackage.packageName, deletedPackage, false, mPackages.values(),
   16805                         mPermissionCallback);
   16806 
   16807                 mSettings.writeLPr();
   16808             }
   16809 
   16810             Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
   16811                     + " after failed upgrade");
   16812         }
   16813     }
   16814 
   16815     /**
   16816      * Checks whether the parent or any of the child packages have a change shared
   16817      * user. For a package to be a valid update the shred users of the parent and
   16818      * the children should match. We may later support changing child shared users.
   16819      * @param oldPkg The updated package.
   16820      * @param newPkg The update package.
   16821      * @return The shared user that change between the versions.
   16822      */
   16823     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
   16824             PackageParser.Package newPkg) {
   16825         // Check parent shared user
   16826         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
   16827             return newPkg.packageName;
   16828         }
   16829         // Check child shared users
   16830         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
   16831         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
   16832         for (int i = 0; i < newChildCount; i++) {
   16833             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
   16834             // If this child was present, did it have the same shared user?
   16835             for (int j = 0; j < oldChildCount; j++) {
   16836                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
   16837                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
   16838                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
   16839                     return newChildPkg.packageName;
   16840                 }
   16841             }
   16842         }
   16843         return null;
   16844     }
   16845 
   16846     private void removeNativeBinariesLI(PackageSetting ps) {
   16847         // Remove the lib path for the parent package
   16848         if (ps != null) {
   16849             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
   16850             // Remove the lib path for the child packages
   16851             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
   16852             for (int i = 0; i < childCount; i++) {
   16853                 PackageSetting childPs = null;
   16854                 synchronized (mPackages) {
   16855                     childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
   16856                 }
   16857                 if (childPs != null) {
   16858                     NativeLibraryHelper.removeNativeBinariesLI(childPs
   16859                             .legacyNativeLibraryPathString);
   16860                 }
   16861             }
   16862         }
   16863     }
   16864 
   16865     private void enableSystemPackageLPw(PackageParser.Package pkg) {
   16866         // Enable the parent package
   16867         mSettings.enableSystemPackageLPw(pkg.packageName);
   16868         // Enable the child packages
   16869         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   16870         for (int i = 0; i < childCount; i++) {
   16871             PackageParser.Package childPkg = pkg.childPackages.get(i);
   16872             mSettings.enableSystemPackageLPw(childPkg.packageName);
   16873         }
   16874     }
   16875 
   16876     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
   16877             PackageParser.Package newPkg) {
   16878         // Disable the parent package (parent always replaced)
   16879         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
   16880         // Disable the child packages
   16881         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
   16882         for (int i = 0; i < childCount; i++) {
   16883             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
   16884             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
   16885             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
   16886         }
   16887         return disabled;
   16888     }
   16889 
   16890     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
   16891             String installerPackageName) {
   16892         // Enable the parent package
   16893         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
   16894         // Enable the child packages
   16895         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   16896         for (int i = 0; i < childCount; i++) {
   16897             PackageParser.Package childPkg = pkg.childPackages.get(i);
   16898             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
   16899         }
   16900     }
   16901 
   16902     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
   16903             int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
   16904         // Update the parent package setting
   16905         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
   16906                 res, user, installReason);
   16907         // Update the child packages setting
   16908         final int childCount = (newPackage.childPackages != null)
   16909                 ? newPackage.childPackages.size() : 0;
   16910         for (int i = 0; i < childCount; i++) {
   16911             PackageParser.Package childPackage = newPackage.childPackages.get(i);
   16912             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
   16913             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
   16914                     childRes.origUsers, childRes, user, installReason);
   16915         }
   16916     }
   16917 
   16918     private void updateSettingsInternalLI(PackageParser.Package pkg,
   16919             String installerPackageName, int[] allUsers, int[] installedForUsers,
   16920             PackageInstalledInfo res, UserHandle user, int installReason) {
   16921         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
   16922 
   16923         final String pkgName = pkg.packageName;
   16924 
   16925         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
   16926         synchronized (mPackages) {
   16927 // NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
   16928             mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
   16929                     mPermissionCallback);
   16930             // For system-bundled packages, we assume that installing an upgraded version
   16931             // of the package implies that the user actually wants to run that new code,
   16932             // so we enable the package.
   16933             PackageSetting ps = mSettings.mPackages.get(pkgName);
   16934             final int userId = user.getIdentifier();
   16935             if (ps != null) {
   16936                 if (isSystemApp(pkg)) {
   16937                     if (DEBUG_INSTALL) {
   16938                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
   16939                     }
   16940                     // Enable system package for requested users
   16941                     if (res.origUsers != null) {
   16942                         for (int origUserId : res.origUsers) {
   16943                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
   16944                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
   16945                                         origUserId, installerPackageName);
   16946                             }
   16947                         }
   16948                     }
   16949                     // Also convey the prior install/uninstall state
   16950                     if (allUsers != null && installedForUsers != null) {
   16951                         for (int currentUserId : allUsers) {
   16952                             final boolean installed = ArrayUtils.contains(
   16953                                     installedForUsers, currentUserId);
   16954                             if (DEBUG_INSTALL) {
   16955                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
   16956                             }
   16957                             ps.setInstalled(installed, currentUserId);
   16958                         }
   16959                         // these install state changes will be persisted in the
   16960                         // upcoming call to mSettings.writeLPr().
   16961                     }
   16962                 }
   16963                 // It's implied that when a user requests installation, they want the app to be
   16964                 // installed and enabled.
   16965                 if (userId != UserHandle.USER_ALL) {
   16966                     ps.setInstalled(true, userId);
   16967                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
   16968                 }
   16969 
   16970                 // When replacing an existing package, preserve the original install reason for all
   16971                 // users that had the package installed before.
   16972                 final Set<Integer> previousUserIds = new ArraySet<>();
   16973                 if (res.removedInfo != null && res.removedInfo.installReasons != null) {
   16974                     final int installReasonCount = res.removedInfo.installReasons.size();
   16975                     for (int i = 0; i < installReasonCount; i++) {
   16976                         final int previousUserId = res.removedInfo.installReasons.keyAt(i);
   16977                         final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
   16978                         ps.setInstallReason(previousInstallReason, previousUserId);
   16979                         previousUserIds.add(previousUserId);
   16980                     }
   16981                 }
   16982 
   16983                 // Set install reason for users that are having the package newly installed.
   16984                 if (userId == UserHandle.USER_ALL) {
   16985                     for (int currentUserId : sUserManager.getUserIds()) {
   16986                         if (!previousUserIds.contains(currentUserId)) {
   16987                             ps.setInstallReason(installReason, currentUserId);
   16988                         }
   16989                     }
   16990                 } else if (!previousUserIds.contains(userId)) {
   16991                     ps.setInstallReason(installReason, userId);
   16992                 }
   16993                 mSettings.writeKernelMappingLPr(ps);
   16994             }
   16995             res.name = pkgName;
   16996             res.uid = pkg.applicationInfo.uid;
   16997             res.pkg = pkg;
   16998             mSettings.setInstallerPackageName(pkgName, installerPackageName);
   16999             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
   17000             //to update install status
   17001             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
   17002             mSettings.writeLPr();
   17003             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   17004         }
   17005 
   17006         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   17007     }
   17008 
   17009     private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
   17010         try {
   17011             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
   17012             installPackageLI(args, res);
   17013         } finally {
   17014             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   17015         }
   17016     }
   17017 
   17018     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
   17019         final int installFlags = args.installFlags;
   17020         final String installerPackageName = args.installerPackageName;
   17021         final String volumeUuid = args.volumeUuid;
   17022         final File tmpPackageFile = new File(args.getCodePath());
   17023         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
   17024         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
   17025                 || (args.volumeUuid != null));
   17026         final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
   17027         final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
   17028         final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
   17029         final boolean virtualPreload =
   17030                 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
   17031         boolean replace = false;
   17032         @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
   17033         if (args.move != null) {
   17034             // moving a complete application; perform an initial scan on the new install location
   17035             scanFlags |= SCAN_INITIAL;
   17036         }
   17037         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
   17038             scanFlags |= SCAN_DONT_KILL_APP;
   17039         }
   17040         if (instantApp) {
   17041             scanFlags |= SCAN_AS_INSTANT_APP;
   17042         }
   17043         if (fullApp) {
   17044             scanFlags |= SCAN_AS_FULL_APP;
   17045         }
   17046         if (virtualPreload) {
   17047             scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
   17048         }
   17049 
   17050         // Result object to be returned
   17051         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
   17052         res.installerPackageName = installerPackageName;
   17053 
   17054         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
   17055 
   17056         // Sanity check
   17057         if (instantApp && (forwardLocked || onExternal)) {
   17058             Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
   17059                     + " external=" + onExternal);
   17060             res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
   17061             return;
   17062         }
   17063 
   17064         // Retrieve PackageSettings and parse package
   17065         @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
   17066                 | PackageParser.PARSE_ENFORCE_CODE
   17067                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
   17068                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
   17069                 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
   17070         PackageParser pp = new PackageParser();
   17071         pp.setSeparateProcesses(mSeparateProcesses);
   17072         pp.setDisplayMetrics(mMetrics);
   17073         pp.setCallback(mPackageParserCallback);
   17074 
   17075         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
   17076         final PackageParser.Package pkg;
   17077         try {
   17078             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
   17079             DexMetadataHelper.validatePackageDexMetadata(pkg);
   17080         } catch (PackageParserException e) {
   17081             res.setError("Failed parse during installPackageLI", e);
   17082             return;
   17083         } finally {
   17084             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   17085         }
   17086 
   17087         // Instant apps have several additional install-time checks.
   17088         if (instantApp) {
   17089             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
   17090                 Slog.w(TAG,
   17091                         "Instant app package " + pkg.packageName + " does not target at least O");
   17092                 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
   17093                         "Instant app package must target at least O");
   17094                 return;
   17095             }
   17096             if (pkg.applicationInfo.targetSandboxVersion != 2) {
   17097                 Slog.w(TAG, "Instant app package " + pkg.packageName
   17098                         + " does not target targetSandboxVersion 2");
   17099                 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
   17100                         "Instant app package must use targetSandboxVersion 2");
   17101                 return;
   17102             }
   17103             if (pkg.mSharedUserId != null) {
   17104                 Slog.w(TAG, "Instant app package " + pkg.packageName
   17105                         + " may not declare sharedUserId.");
   17106                 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
   17107                         "Instant app package may not declare a sharedUserId");
   17108                 return;
   17109             }
   17110         }
   17111 
   17112         if (pkg.applicationInfo.isStaticSharedLibrary()) {
   17113             // Static shared libraries have synthetic package names
   17114             renameStaticSharedLibraryPackage(pkg);
   17115 
   17116             // No static shared libs on external storage
   17117             if (onExternal) {
   17118                 Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
   17119                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
   17120                         "Packages declaring static-shared libs cannot be updated");
   17121                 return;
   17122             }
   17123         }
   17124 
   17125         // If we are installing a clustered package add results for the children
   17126         if (pkg.childPackages != null) {
   17127             synchronized (mPackages) {
   17128                 final int childCount = pkg.childPackages.size();
   17129                 for (int i = 0; i < childCount; i++) {
   17130                     PackageParser.Package childPkg = pkg.childPackages.get(i);
   17131                     PackageInstalledInfo childRes = new PackageInstalledInfo();
   17132                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
   17133                     childRes.pkg = childPkg;
   17134                     childRes.name = childPkg.packageName;
   17135                     PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
   17136                     if (childPs != null) {
   17137                         childRes.origUsers = childPs.queryInstalledUsers(
   17138                                 sUserManager.getUserIds(), true);
   17139                     }
   17140                     if ((mPackages.containsKey(childPkg.packageName))) {
   17141                         childRes.removedInfo = new PackageRemovedInfo(this);
   17142                         childRes.removedInfo.removedPackage = childPkg.packageName;
   17143                         childRes.removedInfo.installerPackageName = childPs.installerPackageName;
   17144                     }
   17145                     if (res.addedChildPackages == null) {
   17146                         res.addedChildPackages = new ArrayMap<>();
   17147                     }
   17148                     res.addedChildPackages.put(childPkg.packageName, childRes);
   17149                 }
   17150             }
   17151         }
   17152 
   17153         // If package doesn't declare API override, mark that we have an install
   17154         // time CPU ABI override.
   17155         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
   17156             pkg.cpuAbiOverride = args.abiOverride;
   17157         }
   17158 
   17159         String pkgName = res.name = pkg.packageName;
   17160         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
   17161             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
   17162                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
   17163                 return;
   17164             }
   17165         }
   17166 
   17167         try {
   17168             // either use what we've been given or parse directly from the APK
   17169             if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
   17170                 pkg.setSigningDetails(args.signingDetails);
   17171             } else {
   17172                 PackageParser.collectCertificates(pkg, false /* skipVerify */);
   17173             }
   17174         } catch (PackageParserException e) {
   17175             res.setError("Failed collect during installPackageLI", e);
   17176             return;
   17177         }
   17178 
   17179         if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
   17180                 < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
   17181             Slog.w(TAG, "Instant app package " + pkg.packageName
   17182                     + " is not signed with at least APK Signature Scheme v2");
   17183             res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
   17184                     "Instant app package must be signed with APK Signature Scheme v2 or greater");
   17185             return;
   17186         }
   17187 
   17188         // Get rid of all references to package scan path via parser.
   17189         pp = null;
   17190         String oldCodePath = null;
   17191         boolean systemApp = false;
   17192         synchronized (mPackages) {
   17193             // Check if installing already existing package
   17194             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
   17195                 String oldName = mSettings.getRenamedPackageLPr(pkgName);
   17196                 if (pkg.mOriginalPackages != null
   17197                         && pkg.mOriginalPackages.contains(oldName)
   17198                         && mPackages.containsKey(oldName)) {
   17199                     // This package is derived from an original package,
   17200                     // and this device has been updating from that original
   17201                     // name.  We must continue using the original name, so
   17202                     // rename the new package here.
   17203                     pkg.setPackageName(oldName);
   17204                     pkgName = pkg.packageName;
   17205                     replace = true;
   17206                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
   17207                             + oldName + " pkgName=" + pkgName);
   17208                 } else if (mPackages.containsKey(pkgName)) {
   17209                     // This package, under its official name, already exists
   17210                     // on the device; we should replace it.
   17211                     replace = true;
   17212                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
   17213                 }
   17214 
   17215                 // Child packages are installed through the parent package
   17216                 if (pkg.parentPackage != null) {
   17217                     res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
   17218                             "Package " + pkg.packageName + " is child of package "
   17219                                     + pkg.parentPackage.parentPackage + ". Child packages "
   17220                                     + "can be updated only through the parent package.");
   17221                     return;
   17222                 }
   17223 
   17224                 if (replace) {
   17225                     // Prevent apps opting out from runtime permissions
   17226                     PackageParser.Package oldPackage = mPackages.get(pkgName);
   17227                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
   17228                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
   17229                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
   17230                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
   17231                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
   17232                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
   17233                                         + " doesn't support runtime permissions but the old"
   17234                                         + " target SDK " + oldTargetSdk + " does.");
   17235                         return;
   17236                     }
   17237                     // Prevent persistent apps from being updated
   17238                     if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
   17239                         res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
   17240                                 "Package " + oldPackage.packageName + " is a persistent app. "
   17241                                         + "Persistent apps are not updateable.");
   17242                         return;
   17243                     }
   17244                     // Prevent installing of child packages
   17245                     if (oldPackage.parentPackage != null) {
   17246                         res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
   17247                                 "Package " + pkg.packageName + " is child of package "
   17248                                         + oldPackage.parentPackage + ". Child packages "
   17249                                         + "can be updated only through the parent package.");
   17250                         return;
   17251                     }
   17252                 }
   17253             }
   17254 
   17255             PackageSetting ps = mSettings.mPackages.get(pkgName);
   17256             if (ps != null) {
   17257                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
   17258 
   17259                 // Static shared libs have same package with different versions where
   17260                 // we internally use a synthetic package name to allow multiple versions
   17261                 // of the same package, therefore we need to compare signatures against
   17262                 // the package setting for the latest library version.
   17263                 PackageSetting signatureCheckPs = ps;
   17264                 if (pkg.applicationInfo.isStaticSharedLibrary()) {
   17265                     SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
   17266                     if (libraryEntry != null) {
   17267                         signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
   17268                     }
   17269                 }
   17270 
   17271                 // Quick sanity check that we're signed correctly if updating;
   17272                 // we'll check this again later when scanning, but we want to
   17273                 // bail early here before tripping over redefined permissions.
   17274                 final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   17275                 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
   17276                     if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
   17277                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
   17278                                 + pkg.packageName + " upgrade keys do not match the "
   17279                                 + "previously installed version");
   17280                         return;
   17281                     }
   17282                 } else {
   17283                     try {
   17284                         final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
   17285                         final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
   17286                         // We don't care about disabledPkgSetting on install for now.
   17287                         final boolean compatMatch = verifySignatures(
   17288                                 signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
   17289                                 compareRecover);
   17290                         // The new KeySets will be re-added later in the scanning process.
   17291                         if (compatMatch) {
   17292                             synchronized (mPackages) {
   17293                                 ksms.removeAppKeySetDataLPw(pkg.packageName);
   17294                             }
   17295                         }
   17296                     } catch (PackageManagerException e) {
   17297                         res.setError(e.error, e.getMessage());
   17298                         return;
   17299                     }
   17300                 }
   17301 
   17302                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
   17303                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
   17304                     systemApp = (ps.pkg.applicationInfo.flags &
   17305                             ApplicationInfo.FLAG_SYSTEM) != 0;
   17306                 }
   17307                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
   17308             }
   17309 
   17310             int N = pkg.permissions.size();
   17311             for (int i = N-1; i >= 0; i--) {
   17312                 final PackageParser.Permission perm = pkg.permissions.get(i);
   17313                 final BasePermission bp =
   17314                         (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
   17315 
   17316                 // Don't allow anyone but the system to define ephemeral permissions.
   17317                 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
   17318                         && !systemApp) {
   17319                     Slog.w(TAG, "Non-System package " + pkg.packageName
   17320                             + " attempting to delcare ephemeral permission "
   17321                             + perm.info.name + "; Removing ephemeral.");
   17322                     perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
   17323                 }
   17324 
   17325                 // Check whether the newly-scanned package wants to define an already-defined perm
   17326                 if (bp != null) {
   17327                     // If the defining package is signed with our cert, it's okay.  This
   17328                     // also includes the "updating the same package" case, of course.
   17329                     // "updating same package" could also involve key-rotation.
   17330                     final boolean sigsOk;
   17331                     final String sourcePackageName = bp.getSourcePackageName();
   17332                     final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
   17333                     final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   17334                     if (sourcePackageName.equals(pkg.packageName)
   17335                             && (ksms.shouldCheckUpgradeKeySetLocked(
   17336                                     sourcePackageSetting, scanFlags))) {
   17337                         sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
   17338                     } else {
   17339 
   17340                         // in the event of signing certificate rotation, we need to see if the
   17341                         // package's certificate has rotated from the current one, or if it is an
   17342                         // older certificate with which the current is ok with sharing permissions
   17343                         if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
   17344                                         pkg.mSigningDetails,
   17345                                         PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
   17346                             sigsOk = true;
   17347                         } else if (pkg.mSigningDetails.checkCapability(
   17348                                         sourcePackageSetting.signatures.mSigningDetails,
   17349                                         PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
   17350 
   17351                             // the scanned package checks out, has signing certificate rotation
   17352                             // history, and is newer; bring it over
   17353                             sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
   17354                             sigsOk = true;
   17355                         } else {
   17356                             sigsOk = false;
   17357                         }
   17358                     }
   17359                     if (!sigsOk) {
   17360                         // If the owning package is the system itself, we log but allow
   17361                         // install to proceed; we fail the install on all other permission
   17362                         // redefinitions.
   17363                         if (!sourcePackageName.equals("android")) {
   17364                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
   17365                                     + pkg.packageName + " attempting to redeclare permission "
   17366                                     + perm.info.name + " already owned by " + sourcePackageName);
   17367                             res.origPermission = perm.info.name;
   17368                             res.origPackage = sourcePackageName;
   17369                             return;
   17370                         } else {
   17371                             Slog.w(TAG, "Package " + pkg.packageName
   17372                                     + " attempting to redeclare system permission "
   17373                                     + perm.info.name + "; ignoring new declaration");
   17374                             pkg.permissions.remove(i);
   17375                         }
   17376                     } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
   17377                         // Prevent apps to change protection level to dangerous from any other
   17378                         // type as this would allow a privilege escalation where an app adds a
   17379                         // normal/signature permission in other app's group and later redefines
   17380                         // it as dangerous leading to the group auto-grant.
   17381                         if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
   17382                                 == PermissionInfo.PROTECTION_DANGEROUS) {
   17383                             if (bp != null && !bp.isRuntime()) {
   17384                                 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
   17385                                         + "non-runtime permission " + perm.info.name
   17386                                         + " to runtime; keeping old protection level");
   17387                                 perm.info.protectionLevel = bp.getProtectionLevel();
   17388                             }
   17389                         }
   17390                     }
   17391                 }
   17392             }
   17393         }
   17394 
   17395         if (systemApp) {
   17396             if (onExternal) {
   17397                 // Abort update; system app can't be replaced with app on sdcard
   17398                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
   17399                         "Cannot install updates to system apps on sdcard");
   17400                 return;
   17401             } else if (instantApp) {
   17402                 // Abort update; system app can't be replaced with an instant app
   17403                 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
   17404                         "Cannot update a system app with an instant app");
   17405                 return;
   17406             }
   17407         }
   17408 
   17409         if (args.move != null) {
   17410             // We did an in-place move, so dex is ready to roll
   17411             scanFlags |= SCAN_NO_DEX;
   17412             scanFlags |= SCAN_MOVE;
   17413 
   17414             synchronized (mPackages) {
   17415                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
   17416                 if (ps == null) {
   17417                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
   17418                             "Missing settings for moved package " + pkgName);
   17419                 }
   17420 
   17421                 // We moved the entire application as-is, so bring over the
   17422                 // previously derived ABI information.
   17423                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
   17424                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
   17425             }
   17426 
   17427         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
   17428             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
   17429             scanFlags |= SCAN_NO_DEX;
   17430 
   17431             try {
   17432                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
   17433                     args.abiOverride : pkg.cpuAbiOverride);
   17434                 final boolean extractNativeLibs = !pkg.isLibrary();
   17435                 derivePackageAbi(pkg, abiOverride, extractNativeLibs);
   17436             } catch (PackageManagerException pme) {
   17437                 Slog.e(TAG, "Error deriving application ABI", pme);
   17438                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
   17439                 return;
   17440             }
   17441 
   17442             // Shared libraries for the package need to be updated.
   17443             synchronized (mPackages) {
   17444                 try {
   17445                     updateSharedLibrariesLPr(pkg, null);
   17446                 } catch (PackageManagerException e) {
   17447                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
   17448                 }
   17449             }
   17450         }
   17451 
   17452         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
   17453             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
   17454             return;
   17455         }
   17456 
   17457         if (PackageManagerServiceUtils.isApkVerityEnabled()) {
   17458             String apkPath = null;
   17459             synchronized (mPackages) {
   17460                 // Note that if the attacker managed to skip verify setup, for example by tampering
   17461                 // with the package settings, upon reboot we will do full apk verification when
   17462                 // verity is not detected.
   17463                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
   17464                 if (ps != null && ps.isPrivileged()) {
   17465                     apkPath = pkg.baseCodePath;
   17466                 }
   17467             }
   17468 
   17469             if (apkPath != null) {
   17470                 final VerityUtils.SetupResult result =
   17471                         VerityUtils.generateApkVeritySetupData(apkPath);
   17472                 if (result.isOk()) {
   17473                     if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
   17474                     FileDescriptor fd = result.getUnownedFileDescriptor();
   17475                     try {
   17476                         final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
   17477                         mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
   17478                         mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
   17479                     } catch (InstallerException | IOException | DigestException |
   17480                              NoSuchAlgorithmException e) {
   17481                         res.setError(INSTALL_FAILED_INTERNAL_ERROR,
   17482                                 "Failed to set up verity: " + e);
   17483                         return;
   17484                     } finally {
   17485                         IoUtils.closeQuietly(fd);
   17486                     }
   17487                 } else if (result.isFailed()) {
   17488                     res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
   17489                     return;
   17490                 } else {
   17491                     // Do nothing if verity is skipped. Will fall back to full apk verification on
   17492                     // reboot.
   17493                 }
   17494             }
   17495         }
   17496 
   17497         if (!instantApp) {
   17498             startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
   17499         } else {
   17500             if (DEBUG_DOMAIN_VERIFICATION) {
   17501                 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
   17502             }
   17503         }
   17504 
   17505         try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
   17506                 "installPackageLI")) {
   17507             if (replace) {
   17508                 if (pkg.applicationInfo.isStaticSharedLibrary()) {
   17509                     // Static libs have a synthetic package name containing the version
   17510                     // and cannot be updated as an update would get a new package name,
   17511                     // unless this is the exact same version code which is useful for
   17512                     // development.
   17513                     PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
   17514                     if (existingPkg != null &&
   17515                             existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
   17516                         res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
   17517                                 + "static-shared libs cannot be updated");
   17518                         return;
   17519                     }
   17520                 }
   17521                 replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
   17522                         installerPackageName, res, args.installReason);
   17523             } else {
   17524                 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
   17525                         args.user, installerPackageName, volumeUuid, res, args.installReason);
   17526             }
   17527         }
   17528 
   17529         // Prepare the application profiles for the new code paths.
   17530         // This needs to be done before invoking dexopt so that any install-time profile
   17531         // can be used for optimizations.
   17532         mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
   17533 
   17534         // Check whether we need to dexopt the app.
   17535         //
   17536         // NOTE: it is IMPORTANT to call dexopt:
   17537         //   - after doRename which will sync the package data from PackageParser.Package and its
   17538         //     corresponding ApplicationInfo.
   17539         //   - after installNewPackageLIF or replacePackageLIF which will update result with the
   17540         //     uid of the application (pkg.applicationInfo.uid).
   17541         //     This update happens in place!
   17542         //
   17543         // We only need to dexopt if the package meets ALL of the following conditions:
   17544         //   1) it is not forward locked.
   17545         //   2) it is not on on an external ASEC container.
   17546         //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
   17547         //   4) it is not debuggable.
   17548         //
   17549         // Note that we do not dexopt instant apps by default. dexopt can take some time to
   17550         // complete, so we skip this step during installation. Instead, we'll take extra time
   17551         // the first time the instant app starts. It's preferred to do it this way to provide
   17552         // continuous progress to the useur instead of mysteriously blocking somewhere in the
   17553         // middle of running an instant app. The default behaviour can be overridden
   17554         // via gservices.
   17555         final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
   17556                 && !forwardLocked
   17557                 && !pkg.applicationInfo.isExternalAsec()
   17558                 && (!instantApp || Global.getInt(mContext.getContentResolver(),
   17559                 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
   17560                 && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
   17561 
   17562         if (performDexopt) {
   17563             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
   17564             // Do not run PackageDexOptimizer through the local performDexOpt
   17565             // method because `pkg` may not be in `mPackages` yet.
   17566             //
   17567             // Also, don't fail application installs if the dexopt step fails.
   17568             DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
   17569                     REASON_INSTALL,
   17570                     DexoptOptions.DEXOPT_BOOT_COMPLETE |
   17571                     DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
   17572             mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
   17573                     null /* instructionSets */,
   17574                     getOrCreateCompilerPackageStats(pkg),
   17575                     mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
   17576                     dexoptOptions);
   17577             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
   17578         }
   17579 
   17580         // Notify BackgroundDexOptService that the package has been changed.
   17581         // If this is an update of a package which used to fail to compile,
   17582         // BackgroundDexOptService will remove it from its blacklist.
   17583         // TODO: Layering violation
   17584         BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
   17585 
   17586         synchronized (mPackages) {
   17587             final PackageSetting ps = mSettings.mPackages.get(pkgName);
   17588             if (ps != null) {
   17589                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
   17590                 ps.setUpdateAvailable(false /*updateAvailable*/);
   17591             }
   17592 
   17593             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   17594             for (int i = 0; i < childCount; i++) {
   17595                 PackageParser.Package childPkg = pkg.childPackages.get(i);
   17596                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
   17597                 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
   17598                 if (childPs != null) {
   17599                     childRes.newUsers = childPs.queryInstalledUsers(
   17600                             sUserManager.getUserIds(), true);
   17601                 }
   17602             }
   17603 
   17604             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   17605                 updateSequenceNumberLP(ps, res.newUsers);
   17606                 updateInstantAppInstallerLocked(pkgName);
   17607             }
   17608         }
   17609     }
   17610 
   17611     private void startIntentFilterVerifications(int userId, boolean replacing,
   17612             PackageParser.Package pkg) {
   17613         if (mIntentFilterVerifierComponent == null) {
   17614             Slog.w(TAG, "No IntentFilter verification will not be done as "
   17615                     + "there is no IntentFilterVerifier available!");
   17616             return;
   17617         }
   17618 
   17619         final int verifierUid = getPackageUid(
   17620                 mIntentFilterVerifierComponent.getPackageName(),
   17621                 MATCH_DEBUG_TRIAGED_MISSING,
   17622                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
   17623 
   17624         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
   17625         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
   17626         mHandler.sendMessage(msg);
   17627 
   17628         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   17629         for (int i = 0; i < childCount; i++) {
   17630             PackageParser.Package childPkg = pkg.childPackages.get(i);
   17631             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
   17632             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
   17633             mHandler.sendMessage(msg);
   17634         }
   17635     }
   17636 
   17637     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
   17638             PackageParser.Package pkg) {
   17639         int size = pkg.activities.size();
   17640         if (size == 0) {
   17641             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   17642                     "No activity, so no need to verify any IntentFilter!");
   17643             return;
   17644         }
   17645 
   17646         final boolean hasDomainURLs = hasDomainURLs(pkg);
   17647         if (!hasDomainURLs) {
   17648             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   17649                     "No domain URLs, so no need to verify any IntentFilter!");
   17650             return;
   17651         }
   17652 
   17653         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
   17654                 + " if any IntentFilter from the " + size
   17655                 + " Activities needs verification ...");
   17656 
   17657         int count = 0;
   17658         final String packageName = pkg.packageName;
   17659 
   17660         synchronized (mPackages) {
   17661             // If this is a new install and we see that we've already run verification for this
   17662             // package, we have nothing to do: it means the state was restored from backup.
   17663             if (!replacing) {
   17664                 IntentFilterVerificationInfo ivi =
   17665                         mSettings.getIntentFilterVerificationLPr(packageName);
   17666                 if (ivi != null) {
   17667                     if (DEBUG_DOMAIN_VERIFICATION) {
   17668                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
   17669                                 + ivi.getStatusString());
   17670                     }
   17671                     return;
   17672                 }
   17673             }
   17674 
   17675             // If any filters need to be verified, then all need to be.
   17676             boolean needToVerify = false;
   17677             for (PackageParser.Activity a : pkg.activities) {
   17678                 for (ActivityIntentInfo filter : a.intents) {
   17679                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
   17680                         if (DEBUG_DOMAIN_VERIFICATION) {
   17681                             Slog.d(TAG,
   17682                                     "Intent filter needs verification, so processing all filters");
   17683                         }
   17684                         needToVerify = true;
   17685                         break;
   17686                     }
   17687                 }
   17688             }
   17689 
   17690             if (needToVerify) {
   17691                 final int verificationId = mIntentFilterVerificationToken++;
   17692                 for (PackageParser.Activity a : pkg.activities) {
   17693                     for (ActivityIntentInfo filter : a.intents) {
   17694                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
   17695                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
   17696                                     "Verification needed for IntentFilter:" + filter.toString());
   17697                             mIntentFilterVerifier.addOneIntentFilterVerification(
   17698                                     verifierUid, userId, verificationId, filter, packageName);
   17699                             count++;
   17700                         }
   17701                     }
   17702                 }
   17703             }
   17704         }
   17705 
   17706         if (count > 0) {
   17707             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
   17708                     + " IntentFilter verification" + (count > 1 ? "s" : "")
   17709                     +  " for userId:" + userId);
   17710             mIntentFilterVerifier.startVerifications(userId);
   17711         } else {
   17712             if (DEBUG_DOMAIN_VERIFICATION) {
   17713                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
   17714             }
   17715         }
   17716     }
   17717 
   17718     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
   17719         final ComponentName cn  = filter.activity.getComponentName();
   17720         final String packageName = cn.getPackageName();
   17721 
   17722         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
   17723                 packageName);
   17724         if (ivi == null) {
   17725             return true;
   17726         }
   17727         int status = ivi.getStatus();
   17728         switch (status) {
   17729             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
   17730             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
   17731                 return true;
   17732 
   17733             default:
   17734                 // Nothing to do
   17735                 return false;
   17736         }
   17737     }
   17738 
   17739     private static boolean isMultiArch(ApplicationInfo info) {
   17740         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
   17741     }
   17742 
   17743     private static boolean isExternal(PackageParser.Package pkg) {
   17744         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
   17745     }
   17746 
   17747     private static boolean isExternal(PackageSetting ps) {
   17748         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
   17749     }
   17750 
   17751     private static boolean isSystemApp(PackageParser.Package pkg) {
   17752         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   17753     }
   17754 
   17755     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
   17756         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
   17757     }
   17758 
   17759     private static boolean isOemApp(PackageParser.Package pkg) {
   17760         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
   17761     }
   17762 
   17763     private static boolean isVendorApp(PackageParser.Package pkg) {
   17764         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
   17765     }
   17766 
   17767     private static boolean isProductApp(PackageParser.Package pkg) {
   17768         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
   17769     }
   17770 
   17771     private static boolean hasDomainURLs(PackageParser.Package pkg) {
   17772         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
   17773     }
   17774 
   17775     private static boolean isSystemApp(PackageSetting ps) {
   17776         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
   17777     }
   17778 
   17779     private static boolean isUpdatedSystemApp(PackageSetting ps) {
   17780         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
   17781     }
   17782 
   17783     private int packageFlagsToInstallFlags(PackageSetting ps) {
   17784         int installFlags = 0;
   17785         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
   17786             // This existing package was an external ASEC install when we have
   17787             // the external flag without a UUID
   17788             installFlags |= PackageManager.INSTALL_EXTERNAL;
   17789         }
   17790         if (ps.isForwardLocked()) {
   17791             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
   17792         }
   17793         return installFlags;
   17794     }
   17795 
   17796     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
   17797         if (isExternal(pkg)) {
   17798             if (TextUtils.isEmpty(pkg.volumeUuid)) {
   17799                 return mSettings.getExternalVersion();
   17800             } else {
   17801                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
   17802             }
   17803         } else {
   17804             return mSettings.getInternalVersion();
   17805         }
   17806     }
   17807 
   17808     private void deleteTempPackageFiles() {
   17809         final FilenameFilter filter = new FilenameFilter() {
   17810             public boolean accept(File dir, String name) {
   17811                 return name.startsWith("vmdl") && name.endsWith(".tmp");
   17812             }
   17813         };
   17814         for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
   17815             file.delete();
   17816         }
   17817     }
   17818 
   17819     @Override
   17820     public void deletePackageAsUser(String packageName, int versionCode,
   17821             IPackageDeleteObserver observer, int userId, int flags) {
   17822         deletePackageVersioned(new VersionedPackage(packageName, versionCode),
   17823                 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
   17824     }
   17825 
   17826     @Override
   17827     public void deletePackageVersioned(VersionedPackage versionedPackage,
   17828             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
   17829         final int callingUid = Binder.getCallingUid();
   17830         mContext.enforceCallingOrSelfPermission(
   17831                 android.Manifest.permission.DELETE_PACKAGES, null);
   17832         final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
   17833         Preconditions.checkNotNull(versionedPackage);
   17834         Preconditions.checkNotNull(observer);
   17835         Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
   17836                 PackageManager.VERSION_CODE_HIGHEST,
   17837                 Long.MAX_VALUE, "versionCode must be >= -1");
   17838 
   17839         final String packageName = versionedPackage.getPackageName();
   17840         final long versionCode = versionedPackage.getLongVersionCode();
   17841         final String internalPackageName;
   17842         synchronized (mPackages) {
   17843             // Normalize package name to handle renamed packages and static libs
   17844             internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
   17845         }
   17846 
   17847         final int uid = Binder.getCallingUid();
   17848         if (!isOrphaned(internalPackageName)
   17849                 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
   17850             try {
   17851                 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
   17852                 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
   17853                 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
   17854                 observer.onUserActionRequired(intent);
   17855             } catch (RemoteException re) {
   17856             }
   17857             return;
   17858         }
   17859         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
   17860         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
   17861         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
   17862             mContext.enforceCallingOrSelfPermission(
   17863                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   17864                     "deletePackage for user " + userId);
   17865         }
   17866 
   17867         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
   17868             try {
   17869                 observer.onPackageDeleted(packageName,
   17870                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
   17871             } catch (RemoteException re) {
   17872             }
   17873             return;
   17874         }
   17875 
   17876         if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
   17877             try {
   17878                 observer.onPackageDeleted(packageName,
   17879                         PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
   17880             } catch (RemoteException re) {
   17881             }
   17882             return;
   17883         }
   17884 
   17885         if (DEBUG_REMOVE) {
   17886             Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
   17887                     + " deleteAllUsers: " + deleteAllUsers + " version="
   17888                     + (versionCode == PackageManager.VERSION_CODE_HIGHEST
   17889                     ? "VERSION_CODE_HIGHEST" : versionCode));
   17890         }
   17891         // Queue up an async operation since the package deletion may take a little while.
   17892         mHandler.post(new Runnable() {
   17893             public void run() {
   17894                 mHandler.removeCallbacks(this);
   17895                 int returnCode;
   17896                 final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
   17897                 boolean doDeletePackage = true;
   17898                 if (ps != null) {
   17899                     final boolean targetIsInstantApp =
   17900                             ps.getInstantApp(UserHandle.getUserId(callingUid));
   17901                     doDeletePackage = !targetIsInstantApp
   17902                             || canViewInstantApps;
   17903                 }
   17904                 if (doDeletePackage) {
   17905                     if (!deleteAllUsers) {
   17906                         returnCode = deletePackageX(internalPackageName, versionCode,
   17907                                 userId, deleteFlags);
   17908                     } else {
   17909                         int[] blockUninstallUserIds = getBlockUninstallForUsers(
   17910                                 internalPackageName, users);
   17911                         // If nobody is blocking uninstall, proceed with delete for all users
   17912                         if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
   17913                             returnCode = deletePackageX(internalPackageName, versionCode,
   17914                                     userId, deleteFlags);
   17915                         } else {
   17916                             // Otherwise uninstall individually for users with blockUninstalls=false
   17917                             final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
   17918                             for (int userId : users) {
   17919                                 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
   17920                                     returnCode = deletePackageX(internalPackageName, versionCode,
   17921                                             userId, userFlags);
   17922                                     if (returnCode != PackageManager.DELETE_SUCCEEDED) {
   17923                                         Slog.w(TAG, "Package delete failed for user " + userId
   17924                                                 + ", returnCode " + returnCode);
   17925                                     }
   17926                                 }
   17927                             }
   17928                             // The app has only been marked uninstalled for certain users.
   17929                             // We still need to report that delete was blocked
   17930                             returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
   17931                         }
   17932                     }
   17933                 } else {
   17934                     returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
   17935                 }
   17936                 try {
   17937                     observer.onPackageDeleted(packageName, returnCode, null);
   17938                 } catch (RemoteException e) {
   17939                     Log.i(TAG, "Observer no longer exists.");
   17940                 } //end catch
   17941             } //end run
   17942         });
   17943     }
   17944 
   17945     private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
   17946         if (pkg.staticSharedLibName != null) {
   17947             return pkg.manifestPackageName;
   17948         }
   17949         return pkg.packageName;
   17950     }
   17951 
   17952     private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
   17953         // Handle renamed packages
   17954         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
   17955         packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
   17956 
   17957         // Is this a static library?
   17958         LongSparseArray<SharedLibraryEntry> versionedLib =
   17959                 mStaticLibsByDeclaringPackage.get(packageName);
   17960         if (versionedLib == null || versionedLib.size() <= 0) {
   17961             return packageName;
   17962         }
   17963 
   17964         // Figure out which lib versions the caller can see
   17965         LongSparseLongArray versionsCallerCanSee = null;
   17966         final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
   17967         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
   17968                 && callingAppId != Process.ROOT_UID) {
   17969             versionsCallerCanSee = new LongSparseLongArray();
   17970             String libName = versionedLib.valueAt(0).info.getName();
   17971             String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
   17972             if (uidPackages != null) {
   17973                 for (String uidPackage : uidPackages) {
   17974                     PackageSetting ps = mSettings.getPackageLPr(uidPackage);
   17975                     final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
   17976                     if (libIdx >= 0) {
   17977                         final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
   17978                         versionsCallerCanSee.append(libVersion, libVersion);
   17979                     }
   17980                 }
   17981             }
   17982         }
   17983 
   17984         // Caller can see nothing - done
   17985         if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
   17986             return packageName;
   17987         }
   17988 
   17989         // Find the version the caller can see and the app version code
   17990         SharedLibraryEntry highestVersion = null;
   17991         final int versionCount = versionedLib.size();
   17992         for (int i = 0; i < versionCount; i++) {
   17993             SharedLibraryEntry libEntry = versionedLib.valueAt(i);
   17994             if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
   17995                     libEntry.info.getLongVersion()) < 0) {
   17996                 continue;
   17997             }
   17998             final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
   17999             if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
   18000                 if (libVersionCode == versionCode) {
   18001                     return libEntry.apk;
   18002                 }
   18003             } else if (highestVersion == null) {
   18004                 highestVersion = libEntry;
   18005             } else if (libVersionCode  > highestVersion.info
   18006                     .getDeclaringPackage().getLongVersionCode()) {
   18007                 highestVersion = libEntry;
   18008             }
   18009         }
   18010 
   18011         if (highestVersion != null) {
   18012             return highestVersion.apk;
   18013         }
   18014 
   18015         return packageName;
   18016     }
   18017 
   18018     boolean isCallerVerifier(int callingUid) {
   18019         final int callingUserId = UserHandle.getUserId(callingUid);
   18020         return mRequiredVerifierPackage != null &&
   18021                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
   18022     }
   18023 
   18024     private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
   18025         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
   18026               || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
   18027             return true;
   18028         }
   18029         final int callingUserId = UserHandle.getUserId(callingUid);
   18030         // If the caller installed the pkgName, then allow it to silently uninstall.
   18031         if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
   18032             return true;
   18033         }
   18034 
   18035         // Allow package verifier to silently uninstall.
   18036         if (mRequiredVerifierPackage != null &&
   18037                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
   18038             return true;
   18039         }
   18040 
   18041         // Allow package uninstaller to silently uninstall.
   18042         if (mRequiredUninstallerPackage != null &&
   18043                 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
   18044             return true;
   18045         }
   18046 
   18047         // Allow storage manager to silently uninstall.
   18048         if (mStorageManagerPackage != null &&
   18049                 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
   18050             return true;
   18051         }
   18052 
   18053         // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
   18054         // uninstall for device owner provisioning.
   18055         if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
   18056                 == PERMISSION_GRANTED) {
   18057             return true;
   18058         }
   18059 
   18060         return false;
   18061     }
   18062 
   18063     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
   18064         int[] result = EMPTY_INT_ARRAY;
   18065         for (int userId : userIds) {
   18066             if (getBlockUninstallForUser(packageName, userId)) {
   18067                 result = ArrayUtils.appendInt(result, userId);
   18068             }
   18069         }
   18070         return result;
   18071     }
   18072 
   18073     @Override
   18074     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
   18075         final int callingUid = Binder.getCallingUid();
   18076         if (getInstantAppPackageName(callingUid) != null
   18077                 && !isCallerSameApp(packageName, callingUid)) {
   18078             return false;
   18079         }
   18080         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
   18081     }
   18082 
   18083     private boolean isPackageDeviceAdmin(String packageName, int userId) {
   18084         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
   18085                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
   18086         try {
   18087             if (dpm != null) {
   18088                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
   18089                         /* callingUserOnly =*/ false);
   18090                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
   18091                         : deviceOwnerComponentName.getPackageName();
   18092                 // Does the package contains the device owner?
   18093                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
   18094                 // this check is probably not needed, since DO should be registered as a device
   18095                 // admin on some user too. (Original bug for this: b/17657954)
   18096                 if (packageName.equals(deviceOwnerPackageName)) {
   18097                     return true;
   18098                 }
   18099                 // Does it contain a device admin for any user?
   18100                 int[] users;
   18101                 if (userId == UserHandle.USER_ALL) {
   18102                     users = sUserManager.getUserIds();
   18103                 } else {
   18104                     users = new int[]{userId};
   18105                 }
   18106                 for (int i = 0; i < users.length; ++i) {
   18107                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
   18108                         return true;
   18109                     }
   18110                 }
   18111             }
   18112         } catch (RemoteException e) {
   18113         }
   18114         return false;
   18115     }
   18116 
   18117     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
   18118         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
   18119     }
   18120 
   18121     /**
   18122      *  This method is an internal method that could be get invoked either
   18123      *  to delete an installed package or to clean up a failed installation.
   18124      *  After deleting an installed package, a broadcast is sent to notify any
   18125      *  listeners that the package has been removed. For cleaning up a failed
   18126      *  installation, the broadcast is not necessary since the package's
   18127      *  installation wouldn't have sent the initial broadcast either
   18128      *  The key steps in deleting a package are
   18129      *  deleting the package information in internal structures like mPackages,
   18130      *  deleting the packages base directories through installd
   18131      *  updating mSettings to reflect current status
   18132      *  persisting settings for later use
   18133      *  sending a broadcast if necessary
   18134      */
   18135     int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
   18136         final PackageRemovedInfo info = new PackageRemovedInfo(this);
   18137         final boolean res;
   18138 
   18139         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
   18140                 ? UserHandle.USER_ALL : userId;
   18141 
   18142         if (isPackageDeviceAdmin(packageName, removeUser)) {
   18143             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
   18144             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
   18145         }
   18146 
   18147         PackageSetting uninstalledPs = null;
   18148         PackageParser.Package pkg = null;
   18149 
   18150         // for the uninstall-updates case and restricted profiles, remember the per-
   18151         // user handle installed state
   18152         int[] allUsers;
   18153         synchronized (mPackages) {
   18154             uninstalledPs = mSettings.mPackages.get(packageName);
   18155             if (uninstalledPs == null) {
   18156                 Slog.w(TAG, "Not removing non-existent package " + packageName);
   18157                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
   18158             }
   18159 
   18160             if (versionCode != PackageManager.VERSION_CODE_HIGHEST
   18161                     && uninstalledPs.versionCode != versionCode) {
   18162                 Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
   18163                         + uninstalledPs.versionCode + " != " + versionCode);
   18164                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
   18165             }
   18166 
   18167             // Static shared libs can be declared by any package, so let us not
   18168             // allow removing a package if it provides a lib others depend on.
   18169             pkg = mPackages.get(packageName);
   18170 
   18171             allUsers = sUserManager.getUserIds();
   18172 
   18173             if (pkg != null && pkg.staticSharedLibName != null) {
   18174                 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
   18175                         pkg.staticSharedLibVersion);
   18176                 if (libEntry != null) {
   18177                     for (int currUserId : allUsers) {
   18178                         if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
   18179                             continue;
   18180                         }
   18181                         List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
   18182                                 libEntry.info, 0, currUserId);
   18183                         if (!ArrayUtils.isEmpty(libClientPackages)) {
   18184                             Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
   18185                                     + " hosting lib " + libEntry.info.getName() + " version "
   18186                                     + libEntry.info.getLongVersion() + " used by " + libClientPackages
   18187                                     + " for user " + currUserId);
   18188                             return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
   18189                         }
   18190                     }
   18191                 }
   18192             }
   18193 
   18194             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
   18195         }
   18196 
   18197         final int freezeUser;
   18198         if (isUpdatedSystemApp(uninstalledPs)
   18199                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
   18200             // We're downgrading a system app, which will apply to all users, so
   18201             // freeze them all during the downgrade
   18202             freezeUser = UserHandle.USER_ALL;
   18203         } else {
   18204             freezeUser = removeUser;
   18205         }
   18206 
   18207         synchronized (mInstallLock) {
   18208             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
   18209             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
   18210                     deleteFlags, "deletePackageX")) {
   18211                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
   18212                         deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
   18213             }
   18214             synchronized (mPackages) {
   18215                 if (res) {
   18216                     if (pkg != null) {
   18217                         mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
   18218                     }
   18219                     updateSequenceNumberLP(uninstalledPs, info.removedUsers);
   18220                     updateInstantAppInstallerLocked(packageName);
   18221                 }
   18222             }
   18223         }
   18224 
   18225         if (res) {
   18226             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
   18227             info.sendPackageRemovedBroadcasts(killApp);
   18228             info.sendSystemPackageUpdatedBroadcasts();
   18229             info.sendSystemPackageAppearedBroadcasts();
   18230         }
   18231         // Force a gc here.
   18232         Runtime.getRuntime().gc();
   18233         // Delete the resources here after sending the broadcast to let
   18234         // other processes clean up before deleting resources.
   18235         if (info.args != null) {
   18236             synchronized (mInstallLock) {
   18237                 info.args.doPostDeleteLI(true);
   18238             }
   18239         }
   18240 
   18241         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
   18242     }
   18243 
   18244     static class PackageRemovedInfo {
   18245         final PackageSender packageSender;
   18246         String removedPackage;
   18247         String installerPackageName;
   18248         int uid = -1;
   18249         int removedAppId = -1;
   18250         int[] origUsers;
   18251         int[] removedUsers = null;
   18252         int[] broadcastUsers = null;
   18253         int[] instantUserIds = null;
   18254         SparseArray<Integer> installReasons;
   18255         boolean isRemovedPackageSystemUpdate = false;
   18256         boolean isUpdate;
   18257         boolean dataRemoved;
   18258         boolean removedForAllUsers;
   18259         boolean isStaticSharedLib;
   18260         // Clean up resources deleted packages.
   18261         InstallArgs args = null;
   18262         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
   18263         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
   18264 
   18265         PackageRemovedInfo(PackageSender packageSender) {
   18266             this.packageSender = packageSender;
   18267         }
   18268 
   18269         void sendPackageRemovedBroadcasts(boolean killApp) {
   18270             sendPackageRemovedBroadcastInternal(killApp);
   18271             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
   18272             for (int i = 0; i < childCount; i++) {
   18273                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
   18274                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
   18275             }
   18276         }
   18277 
   18278         void sendSystemPackageUpdatedBroadcasts() {
   18279             if (isRemovedPackageSystemUpdate) {
   18280                 sendSystemPackageUpdatedBroadcastsInternal();
   18281                 final int childCount = (removedChildPackages != null)
   18282                         ? removedChildPackages.size() : 0;
   18283                 for (int i = 0; i < childCount; i++) {
   18284                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
   18285                     if (childInfo.isRemovedPackageSystemUpdate) {
   18286                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
   18287                     }
   18288                 }
   18289             }
   18290         }
   18291 
   18292         void sendSystemPackageAppearedBroadcasts() {
   18293             final int packageCount = (appearedChildPackages != null)
   18294                     ? appearedChildPackages.size() : 0;
   18295             for (int i = 0; i < packageCount; i++) {
   18296                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
   18297                 packageSender.sendPackageAddedForNewUsers(installedInfo.name,
   18298                     true /*sendBootCompleted*/, false /*startReceiver*/,
   18299                     UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
   18300             }
   18301         }
   18302 
   18303         private void sendSystemPackageUpdatedBroadcastsInternal() {
   18304             Bundle extras = new Bundle(2);
   18305             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
   18306             extras.putBoolean(Intent.EXTRA_REPLACING, true);
   18307             packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
   18308                 removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
   18309             packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
   18310                 removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
   18311             packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
   18312                 null, null, 0, removedPackage, null, null, null);
   18313             if (installerPackageName != null) {
   18314                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
   18315                         removedPackage, extras, 0 /*flags*/,
   18316                         installerPackageName, null, null, null);
   18317                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
   18318                         removedPackage, extras, 0 /*flags*/,
   18319                         installerPackageName, null, null, null);
   18320             }
   18321         }
   18322 
   18323         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
   18324             // Don't send static shared library removal broadcasts as these
   18325             // libs are visible only the the apps that depend on them an one
   18326             // cannot remove the library if it has a dependency.
   18327             if (isStaticSharedLib) {
   18328                 return;
   18329             }
   18330             Bundle extras = new Bundle(2);
   18331             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
   18332             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
   18333             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
   18334             if (isUpdate || isRemovedPackageSystemUpdate) {
   18335                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
   18336             }
   18337             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
   18338             if (removedPackage != null) {
   18339                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
   18340                     removedPackage, extras, 0, null /*targetPackage*/, null,
   18341                     broadcastUsers, instantUserIds);
   18342                 if (installerPackageName != null) {
   18343                     packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
   18344                             removedPackage, extras, 0 /*flags*/,
   18345                             installerPackageName, null, broadcastUsers, instantUserIds);
   18346                 }
   18347                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
   18348                     packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
   18349                         removedPackage, extras,
   18350                         Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
   18351                         null, null, broadcastUsers, instantUserIds);
   18352                     packageSender.notifyPackageRemoved(removedPackage);
   18353                 }
   18354             }
   18355             if (removedAppId >= 0) {
   18356                 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
   18357                     null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
   18358                     null, null, broadcastUsers, instantUserIds);
   18359             }
   18360         }
   18361 
   18362         void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
   18363             removedUsers = userIds;
   18364             if (removedUsers == null) {
   18365                 broadcastUsers = null;
   18366                 return;
   18367             }
   18368 
   18369             broadcastUsers = EMPTY_INT_ARRAY;
   18370             instantUserIds = EMPTY_INT_ARRAY;
   18371             for (int i = userIds.length - 1; i >= 0; --i) {
   18372                 final int userId = userIds[i];
   18373                 if (deletedPackageSetting.getInstantApp(userId)) {
   18374                     instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
   18375                 } else {
   18376                     broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
   18377                 }
   18378             }
   18379         }
   18380     }
   18381 
   18382     /*
   18383      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
   18384      * flag is not set, the data directory is removed as well.
   18385      * make sure this flag is set for partially installed apps. If not its meaningless to
   18386      * delete a partially installed application.
   18387      */
   18388     private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
   18389             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
   18390         String packageName = ps.name;
   18391         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
   18392         // Retrieve object to delete permissions for shared user later on
   18393         final PackageParser.Package deletedPkg;
   18394         final PackageSetting deletedPs;
   18395         // reader
   18396         synchronized (mPackages) {
   18397             deletedPkg = mPackages.get(packageName);
   18398             deletedPs = mSettings.mPackages.get(packageName);
   18399             if (outInfo != null) {
   18400                 outInfo.removedPackage = packageName;
   18401                 outInfo.installerPackageName = ps.installerPackageName;
   18402                 outInfo.isStaticSharedLib = deletedPkg != null
   18403                         && deletedPkg.staticSharedLibName != null;
   18404                 outInfo.populateUsers(deletedPs == null ? null
   18405                         : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
   18406             }
   18407         }
   18408 
   18409         removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
   18410 
   18411         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
   18412             final PackageParser.Package resolvedPkg;
   18413             if (deletedPkg != null) {
   18414                 resolvedPkg = deletedPkg;
   18415             } else {
   18416                 // We don't have a parsed package when it lives on an ejected
   18417                 // adopted storage device, so fake something together
   18418                 resolvedPkg = new PackageParser.Package(ps.name);
   18419                 resolvedPkg.setVolumeUuid(ps.volumeUuid);
   18420             }
   18421             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
   18422                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
   18423             destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
   18424             if (outInfo != null) {
   18425                 outInfo.dataRemoved = true;
   18426             }
   18427             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
   18428         }
   18429 
   18430         int removedAppId = -1;
   18431 
   18432         // writer
   18433         synchronized (mPackages) {
   18434             boolean installedStateChanged = false;
   18435             if (deletedPs != null) {
   18436                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
   18437                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
   18438                     clearDefaultBrowserIfNeeded(packageName);
   18439                     mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
   18440                     removedAppId = mSettings.removePackageLPw(packageName);
   18441                     if (outInfo != null) {
   18442                         outInfo.removedAppId = removedAppId;
   18443                     }
   18444                     mPermissionManager.updatePermissions(
   18445                             deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
   18446                     if (deletedPs.sharedUser != null) {
   18447                         // Remove permissions associated with package. Since runtime
   18448                         // permissions are per user we have to kill the removed package
   18449                         // or packages running under the shared user of the removed
   18450                         // package if revoking the permissions requested only by the removed
   18451                         // package is successful and this causes a change in gids.
   18452                         for (int userId : UserManagerService.getInstance().getUserIds()) {
   18453                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
   18454                                     userId);
   18455                             if (userIdToKill == UserHandle.USER_ALL
   18456                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
   18457                                 // If gids changed for this user, kill all affected packages.
   18458                                 mHandler.post(new Runnable() {
   18459                                     @Override
   18460                                     public void run() {
   18461                                         // This has to happen with no lock held.
   18462                                         killApplication(deletedPs.name, deletedPs.appId,
   18463                                                 KILL_APP_REASON_GIDS_CHANGED);
   18464                                     }
   18465                                 });
   18466                                 break;
   18467                             }
   18468                         }
   18469                     }
   18470                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
   18471                 }
   18472                 // make sure to preserve per-user disabled state if this removal was just
   18473                 // a downgrade of a system app to the factory package
   18474                 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
   18475                     if (DEBUG_REMOVE) {
   18476                         Slog.d(TAG, "Propagating install state across downgrade");
   18477                     }
   18478                     for (int userId : allUserHandles) {
   18479                         final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
   18480                         if (DEBUG_REMOVE) {
   18481                             Slog.d(TAG, "    user " + userId + " => " + installed);
   18482                         }
   18483                         if (installed != ps.getInstalled(userId)) {
   18484                             installedStateChanged = true;
   18485                         }
   18486                         ps.setInstalled(installed, userId);
   18487                     }
   18488                 }
   18489             }
   18490             // can downgrade to reader
   18491             if (writeSettings) {
   18492                 // Save settings now
   18493                 mSettings.writeLPr();
   18494             }
   18495             if (installedStateChanged) {
   18496                 mSettings.writeKernelMappingLPr(ps);
   18497             }
   18498         }
   18499         if (removedAppId != -1) {
   18500             // A user ID was deleted here. Go through all users and remove it
   18501             // from KeyStore.
   18502             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
   18503         }
   18504     }
   18505 
   18506     static boolean locationIsPrivileged(String path) {
   18507         try {
   18508             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
   18509             final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
   18510             final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
   18511             final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
   18512             return path.startsWith(privilegedAppDir.getCanonicalPath())
   18513                     || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
   18514                     || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
   18515                     || path.startsWith(privilegedProductAppDir.getCanonicalPath());
   18516         } catch (IOException e) {
   18517             Slog.e(TAG, "Unable to access code path " + path);
   18518         }
   18519         return false;
   18520     }
   18521 
   18522     static boolean locationIsOem(String path) {
   18523         try {
   18524             return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
   18525         } catch (IOException e) {
   18526             Slog.e(TAG, "Unable to access code path " + path);
   18527         }
   18528         return false;
   18529     }
   18530 
   18531     static boolean locationIsVendor(String path) {
   18532         try {
   18533             return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
   18534                     || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
   18535         } catch (IOException e) {
   18536             Slog.e(TAG, "Unable to access code path " + path);
   18537         }
   18538         return false;
   18539     }
   18540 
   18541     static boolean locationIsProduct(String path) {
   18542         try {
   18543             return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
   18544         } catch (IOException e) {
   18545             Slog.e(TAG, "Unable to access code path " + path);
   18546         }
   18547         return false;
   18548     }
   18549 
   18550     /*
   18551      * Tries to delete system package.
   18552      */
   18553     private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
   18554             PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
   18555             boolean writeSettings) {
   18556         if (deletedPs.parentPackageName != null) {
   18557             Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
   18558             return false;
   18559         }
   18560 
   18561         final boolean applyUserRestrictions
   18562                 = (allUserHandles != null) && (outInfo.origUsers != null);
   18563         final PackageSetting disabledPs;
   18564         // Confirm if the system package has been updated
   18565         // An updated system app can be deleted. This will also have to restore
   18566         // the system pkg from system partition
   18567         // reader
   18568         synchronized (mPackages) {
   18569             disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
   18570         }
   18571 
   18572         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
   18573                 + " disabledPs=" + disabledPs);
   18574 
   18575         if (disabledPs == null) {
   18576             Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
   18577             return false;
   18578         } else if (DEBUG_REMOVE) {
   18579             Slog.d(TAG, "Deleting system pkg from data partition");
   18580         }
   18581 
   18582         if (DEBUG_REMOVE) {
   18583             if (applyUserRestrictions) {
   18584                 Slog.d(TAG, "Remembering install states:");
   18585                 for (int userId : allUserHandles) {
   18586                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
   18587                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
   18588                 }
   18589             }
   18590         }
   18591 
   18592         // Delete the updated package
   18593         outInfo.isRemovedPackageSystemUpdate = true;
   18594         if (outInfo.removedChildPackages != null) {
   18595             final int childCount = (deletedPs.childPackageNames != null)
   18596                     ? deletedPs.childPackageNames.size() : 0;
   18597             for (int i = 0; i < childCount; i++) {
   18598                 String childPackageName = deletedPs.childPackageNames.get(i);
   18599                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
   18600                         .contains(childPackageName)) {
   18601                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
   18602                             childPackageName);
   18603                     if (childInfo != null) {
   18604                         childInfo.isRemovedPackageSystemUpdate = true;
   18605                     }
   18606                 }
   18607             }
   18608         }
   18609 
   18610         if (disabledPs.versionCode < deletedPs.versionCode) {
   18611             // Delete data for downgrades
   18612             flags &= ~PackageManager.DELETE_KEEP_DATA;
   18613         } else {
   18614             // Preserve data by setting flag
   18615             flags |= PackageManager.DELETE_KEEP_DATA;
   18616         }
   18617 
   18618         boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
   18619                 outInfo, writeSettings, disabledPs.pkg);
   18620         if (!ret) {
   18621             return false;
   18622         }
   18623 
   18624         // writer
   18625         synchronized (mPackages) {
   18626             // NOTE: The system package always needs to be enabled; even if it's for
   18627             // a compressed stub. If we don't, installing the system package fails
   18628             // during scan [scanning checks the disabled packages]. We will reverse
   18629             // this later, after we've "installed" the stub.
   18630             // Reinstate the old system package
   18631             enableSystemPackageLPw(disabledPs.pkg);
   18632             // Remove any native libraries from the upgraded package.
   18633             removeNativeBinariesLI(deletedPs);
   18634         }
   18635 
   18636         // Install the system package
   18637         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
   18638         try {
   18639             installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
   18640                     outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
   18641         } catch (PackageManagerException e) {
   18642             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
   18643                     + e.getMessage());
   18644             return false;
   18645         } finally {
   18646             if (disabledPs.pkg.isStub) {
   18647                 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
   18648             }
   18649         }
   18650         return true;
   18651     }
   18652 
   18653     /**
   18654      * Installs a package that's already on the system partition.
   18655      */
   18656     private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
   18657             boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
   18658             @Nullable PermissionsState origPermissionState, boolean writeSettings)
   18659                     throws PackageManagerException {
   18660         @ParseFlags int parseFlags =
   18661                 mDefParseFlags
   18662                 | PackageParser.PARSE_MUST_BE_APK
   18663                 | PackageParser.PARSE_IS_SYSTEM_DIR;
   18664         @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
   18665         if (isPrivileged || locationIsPrivileged(codePathString)) {
   18666             scanFlags |= SCAN_AS_PRIVILEGED;
   18667         }
   18668         if (locationIsOem(codePathString)) {
   18669             scanFlags |= SCAN_AS_OEM;
   18670         }
   18671         if (locationIsVendor(codePathString)) {
   18672             scanFlags |= SCAN_AS_VENDOR;
   18673         }
   18674         if (locationIsProduct(codePathString)) {
   18675             scanFlags |= SCAN_AS_PRODUCT;
   18676         }
   18677 
   18678         final File codePath = new File(codePathString);
   18679         final PackageParser.Package pkg =
   18680                 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
   18681 
   18682         try {
   18683             // update shared libraries for the newly re-installed system package
   18684             updateSharedLibrariesLPr(pkg, null);
   18685         } catch (PackageManagerException e) {
   18686             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
   18687         }
   18688 
   18689         prepareAppDataAfterInstallLIF(pkg);
   18690 
   18691         // writer
   18692         synchronized (mPackages) {
   18693             PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
   18694 
   18695             // Propagate the permissions state as we do not want to drop on the floor
   18696             // runtime permissions. The update permissions method below will take
   18697             // care of removing obsolete permissions and grant install permissions.
   18698             if (origPermissionState != null) {
   18699                 ps.getPermissionsState().copyFrom(origPermissionState);
   18700             }
   18701             mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
   18702                     mPermissionCallback);
   18703 
   18704             final boolean applyUserRestrictions
   18705                     = (allUserHandles != null) && (origUserHandles != null);
   18706             if (applyUserRestrictions) {
   18707                 boolean installedStateChanged = false;
   18708                 if (DEBUG_REMOVE) {
   18709                     Slog.d(TAG, "Propagating install state across reinstall");
   18710                 }
   18711                 for (int userId : allUserHandles) {
   18712                     final boolean installed = ArrayUtils.contains(origUserHandles, userId);
   18713                     if (DEBUG_REMOVE) {
   18714                         Slog.d(TAG, "    user " + userId + " => " + installed);
   18715                     }
   18716                     if (installed != ps.getInstalled(userId)) {
   18717                         installedStateChanged = true;
   18718                     }
   18719                     ps.setInstalled(installed, userId);
   18720 
   18721                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   18722                 }
   18723                 // Regardless of writeSettings we need to ensure that this restriction
   18724                 // state propagation is persisted
   18725                 mSettings.writeAllUsersPackageRestrictionsLPr();
   18726                 if (installedStateChanged) {
   18727                     mSettings.writeKernelMappingLPr(ps);
   18728                 }
   18729             }
   18730             // can downgrade to reader here
   18731             if (writeSettings) {
   18732                 mSettings.writeLPr();
   18733             }
   18734         }
   18735         return pkg;
   18736     }
   18737 
   18738     private boolean deleteInstalledPackageLIF(PackageSetting ps,
   18739             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
   18740             PackageRemovedInfo outInfo, boolean writeSettings,
   18741             PackageParser.Package replacingPackage) {
   18742         synchronized (mPackages) {
   18743             if (outInfo != null) {
   18744                 outInfo.uid = ps.appId;
   18745             }
   18746 
   18747             if (outInfo != null && outInfo.removedChildPackages != null) {
   18748                 final int childCount = (ps.childPackageNames != null)
   18749                         ? ps.childPackageNames.size() : 0;
   18750                 for (int i = 0; i < childCount; i++) {
   18751                     String childPackageName = ps.childPackageNames.get(i);
   18752                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
   18753                     if (childPs == null) {
   18754                         return false;
   18755                     }
   18756                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
   18757                             childPackageName);
   18758                     if (childInfo != null) {
   18759                         childInfo.uid = childPs.appId;
   18760                     }
   18761                 }
   18762             }
   18763         }
   18764 
   18765         // Delete package data from internal structures and also remove data if flag is set
   18766         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
   18767 
   18768         // Delete the child packages data
   18769         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
   18770         for (int i = 0; i < childCount; i++) {
   18771             PackageSetting childPs;
   18772             synchronized (mPackages) {
   18773                 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
   18774             }
   18775             if (childPs != null) {
   18776                 PackageRemovedInfo childOutInfo = (outInfo != null
   18777                         && outInfo.removedChildPackages != null)
   18778                         ? outInfo.removedChildPackages.get(childPs.name) : null;
   18779                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
   18780                         && (replacingPackage != null
   18781                         && !replacingPackage.hasChildPackage(childPs.name))
   18782                         ? flags & ~DELETE_KEEP_DATA : flags;
   18783                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
   18784                         deleteFlags, writeSettings);
   18785             }
   18786         }
   18787 
   18788         // Delete application code and resources only for parent packages
   18789         if (ps.parentPackageName == null) {
   18790             if (deleteCodeAndResources && (outInfo != null)) {
   18791                 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
   18792                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
   18793                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
   18794             }
   18795         }
   18796 
   18797         return true;
   18798     }
   18799 
   18800     @Override
   18801     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
   18802             int userId) {
   18803         mContext.enforceCallingOrSelfPermission(
   18804                 android.Manifest.permission.DELETE_PACKAGES, null);
   18805         synchronized (mPackages) {
   18806             // Cannot block uninstall of static shared libs as they are
   18807             // considered a part of the using app (emulating static linking).
   18808             // Also static libs are installed always on internal storage.
   18809             PackageParser.Package pkg = mPackages.get(packageName);
   18810             if (pkg != null && pkg.staticSharedLibName != null) {
   18811                 Slog.w(TAG, "Cannot block uninstall of package: " + packageName
   18812                         + " providing static shared library: " + pkg.staticSharedLibName);
   18813                 return false;
   18814             }
   18815             mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
   18816             mSettings.writePackageRestrictionsLPr(userId);
   18817         }
   18818         return true;
   18819     }
   18820 
   18821     @Override
   18822     public boolean getBlockUninstallForUser(String packageName, int userId) {
   18823         synchronized (mPackages) {
   18824             final PackageSetting ps = mSettings.mPackages.get(packageName);
   18825             if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
   18826                 return false;
   18827             }
   18828             return mSettings.getBlockUninstallLPr(userId, packageName);
   18829         }
   18830     }
   18831 
   18832     @Override
   18833     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
   18834         enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
   18835         synchronized (mPackages) {
   18836             PackageSetting ps = mSettings.mPackages.get(packageName);
   18837             if (ps == null) {
   18838                 Log.w(TAG, "Package doesn't exist: " + packageName);
   18839                 return false;
   18840             }
   18841             if (systemUserApp) {
   18842                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
   18843             } else {
   18844                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
   18845             }
   18846             mSettings.writeLPr();
   18847         }
   18848         return true;
   18849     }
   18850 
   18851     /*
   18852      * This method handles package deletion in general
   18853      */
   18854     private boolean deletePackageLIF(String packageName, UserHandle user,
   18855             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
   18856             PackageRemovedInfo outInfo, boolean writeSettings,
   18857             PackageParser.Package replacingPackage) {
   18858         if (packageName == null) {
   18859             Slog.w(TAG, "Attempt to delete null packageName.");
   18860             return false;
   18861         }
   18862 
   18863         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
   18864 
   18865         PackageSetting ps;
   18866         synchronized (mPackages) {
   18867             ps = mSettings.mPackages.get(packageName);
   18868             if (ps == null) {
   18869                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
   18870                 return false;
   18871             }
   18872 
   18873             if (ps.parentPackageName != null && (!isSystemApp(ps)
   18874                     || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
   18875                 if (DEBUG_REMOVE) {
   18876                     Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
   18877                             + ((user == null) ? UserHandle.USER_ALL : user));
   18878                 }
   18879                 final int removedUserId = (user != null) ? user.getIdentifier()
   18880                         : UserHandle.USER_ALL;
   18881 
   18882                 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
   18883                     return false;
   18884                 }
   18885                 markPackageUninstalledForUserLPw(ps, user);
   18886                 scheduleWritePackageRestrictionsLocked(user);
   18887                 return true;
   18888             }
   18889         }
   18890 
   18891         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
   18892         if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
   18893             unsuspendForSuspendingPackage(packageName, userId);
   18894         }
   18895 
   18896 
   18897         if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
   18898                 && user.getIdentifier() != UserHandle.USER_ALL)) {
   18899             // The caller is asking that the package only be deleted for a single
   18900             // user.  To do this, we just mark its uninstalled state and delete
   18901             // its data. If this is a system app, we only allow this to happen if
   18902             // they have set the special DELETE_SYSTEM_APP which requests different
   18903             // semantics than normal for uninstalling system apps.
   18904             markPackageUninstalledForUserLPw(ps, user);
   18905 
   18906             if (!isSystemApp(ps)) {
   18907                 // Do not uninstall the APK if an app should be cached
   18908                 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
   18909                 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
   18910                     // Other user still have this package installed, so all
   18911                     // we need to do is clear this user's data and save that
   18912                     // it is uninstalled.
   18913                     if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
   18914                     if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
   18915                         return false;
   18916                     }
   18917                     scheduleWritePackageRestrictionsLocked(user);
   18918                     return true;
   18919                 } else {
   18920                     // We need to set it back to 'installed' so the uninstall
   18921                     // broadcasts will be sent correctly.
   18922                     if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
   18923                     ps.setInstalled(true, user.getIdentifier());
   18924                     mSettings.writeKernelMappingLPr(ps);
   18925                 }
   18926             } else {
   18927                 // This is a system app, so we assume that the
   18928                 // other users still have this package installed, so all
   18929                 // we need to do is clear this user's data and save that
   18930                 // it is uninstalled.
   18931                 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
   18932                 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
   18933                     return false;
   18934                 }
   18935                 scheduleWritePackageRestrictionsLocked(user);
   18936                 return true;
   18937             }
   18938         }
   18939 
   18940         // If we are deleting a composite package for all users, keep track
   18941         // of result for each child.
   18942         if (ps.childPackageNames != null && outInfo != null) {
   18943             synchronized (mPackages) {
   18944                 final int childCount = ps.childPackageNames.size();
   18945                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
   18946                 for (int i = 0; i < childCount; i++) {
   18947                     String childPackageName = ps.childPackageNames.get(i);
   18948                     PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
   18949                     childInfo.removedPackage = childPackageName;
   18950                     childInfo.installerPackageName = ps.installerPackageName;
   18951                     outInfo.removedChildPackages.put(childPackageName, childInfo);
   18952                     PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
   18953                     if (childPs != null) {
   18954                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
   18955                     }
   18956                 }
   18957             }
   18958         }
   18959 
   18960         boolean ret = false;
   18961         if (isSystemApp(ps)) {
   18962             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
   18963             // When an updated system application is deleted we delete the existing resources
   18964             // as well and fall back to existing code in system partition
   18965             ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
   18966         } else {
   18967             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
   18968             ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
   18969                     outInfo, writeSettings, replacingPackage);
   18970         }
   18971 
   18972         // Take a note whether we deleted the package for all users
   18973         if (outInfo != null) {
   18974             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
   18975             if (outInfo.removedChildPackages != null) {
   18976                 synchronized (mPackages) {
   18977                     final int childCount = outInfo.removedChildPackages.size();
   18978                     for (int i = 0; i < childCount; i++) {
   18979                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
   18980                         if (childInfo != null) {
   18981                             childInfo.removedForAllUsers = mPackages.get(
   18982                                     childInfo.removedPackage) == null;
   18983                         }
   18984                     }
   18985                 }
   18986             }
   18987             // If we uninstalled an update to a system app there may be some
   18988             // child packages that appeared as they are declared in the system
   18989             // app but were not declared in the update.
   18990             if (isSystemApp(ps)) {
   18991                 synchronized (mPackages) {
   18992                     PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
   18993                     final int childCount = (updatedPs.childPackageNames != null)
   18994                             ? updatedPs.childPackageNames.size() : 0;
   18995                     for (int i = 0; i < childCount; i++) {
   18996                         String childPackageName = updatedPs.childPackageNames.get(i);
   18997                         if (outInfo.removedChildPackages == null
   18998                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
   18999                             PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
   19000                             if (childPs == null) {
   19001                                 continue;
   19002                             }
   19003                             PackageInstalledInfo installRes = new PackageInstalledInfo();
   19004                             installRes.name = childPackageName;
   19005                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
   19006                             installRes.pkg = mPackages.get(childPackageName);
   19007                             installRes.uid = childPs.pkg.applicationInfo.uid;
   19008                             if (outInfo.appearedChildPackages == null) {
   19009                                 outInfo.appearedChildPackages = new ArrayMap<>();
   19010                             }
   19011                             outInfo.appearedChildPackages.put(childPackageName, installRes);
   19012                         }
   19013                     }
   19014                 }
   19015             }
   19016         }
   19017 
   19018         return ret;
   19019     }
   19020 
   19021     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
   19022         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
   19023                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
   19024         for (int nextUserId : userIds) {
   19025             if (DEBUG_REMOVE) {
   19026                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
   19027             }
   19028             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
   19029                     false /*installed*/,
   19030                     true /*stopped*/,
   19031                     true /*notLaunched*/,
   19032                     false /*hidden*/,
   19033                     false /*suspended*/,
   19034                     null /*suspendingPackage*/,
   19035                     null /*dialogMessage*/,
   19036                     null /*suspendedAppExtras*/,
   19037                     null /*suspendedLauncherExtras*/,
   19038                     false /*instantApp*/,
   19039                     false /*virtualPreload*/,
   19040                     null /*lastDisableAppCaller*/,
   19041                     null /*enabledComponents*/,
   19042                     null /*disabledComponents*/,
   19043                     ps.readUserState(nextUserId).domainVerificationStatus,
   19044                     0, PackageManager.INSTALL_REASON_UNKNOWN,
   19045                     null /*harmfulAppWarning*/);
   19046         }
   19047         mSettings.writeKernelMappingLPr(ps);
   19048     }
   19049 
   19050     private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
   19051             PackageRemovedInfo outInfo) {
   19052         final PackageParser.Package pkg;
   19053         synchronized (mPackages) {
   19054             pkg = mPackages.get(ps.name);
   19055         }
   19056 
   19057         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
   19058                 : new int[] {userId};
   19059         for (int nextUserId : userIds) {
   19060             if (DEBUG_REMOVE) {
   19061                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
   19062                         + nextUserId);
   19063             }
   19064 
   19065             destroyAppDataLIF(pkg, userId,
   19066                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
   19067             destroyAppProfilesLIF(pkg, userId);
   19068             clearDefaultBrowserIfNeededForUser(ps.name, userId);
   19069             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
   19070             schedulePackageCleaning(ps.name, nextUserId, false);
   19071             synchronized (mPackages) {
   19072                 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
   19073                     scheduleWritePackageRestrictionsLocked(nextUserId);
   19074                 }
   19075                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
   19076             }
   19077         }
   19078 
   19079         if (outInfo != null) {
   19080             outInfo.removedPackage = ps.name;
   19081             outInfo.installerPackageName = ps.installerPackageName;
   19082             outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
   19083             outInfo.removedAppId = ps.appId;
   19084             outInfo.removedUsers = userIds;
   19085             outInfo.broadcastUsers = userIds;
   19086         }
   19087 
   19088         return true;
   19089     }
   19090 
   19091     private final class ClearStorageConnection implements ServiceConnection {
   19092         IMediaContainerService mContainerService;
   19093 
   19094         @Override
   19095         public void onServiceConnected(ComponentName name, IBinder service) {
   19096             synchronized (this) {
   19097                 mContainerService = IMediaContainerService.Stub
   19098                         .asInterface(Binder.allowBlocking(service));
   19099                 notifyAll();
   19100             }
   19101         }
   19102 
   19103         @Override
   19104         public void onServiceDisconnected(ComponentName name) {
   19105         }
   19106     }
   19107 
   19108     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
   19109         if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
   19110 
   19111         final boolean mounted;
   19112         if (Environment.isExternalStorageEmulated()) {
   19113             mounted = true;
   19114         } else {
   19115             final String status = Environment.getExternalStorageState();
   19116 
   19117             mounted = status.equals(Environment.MEDIA_MOUNTED)
   19118                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
   19119         }
   19120 
   19121         if (!mounted) {
   19122             return;
   19123         }
   19124 
   19125         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
   19126         int[] users;
   19127         if (userId == UserHandle.USER_ALL) {
   19128             users = sUserManager.getUserIds();
   19129         } else {
   19130             users = new int[] { userId };
   19131         }
   19132         final ClearStorageConnection conn = new ClearStorageConnection();
   19133         if (mContext.bindServiceAsUser(
   19134                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
   19135             try {
   19136                 for (int curUser : users) {
   19137                     long timeout = SystemClock.uptimeMillis() + 5000;
   19138                     synchronized (conn) {
   19139                         long now;
   19140                         while (conn.mContainerService == null &&
   19141                                 (now = SystemClock.uptimeMillis()) < timeout) {
   19142                             try {
   19143                                 conn.wait(timeout - now);
   19144                             } catch (InterruptedException e) {
   19145                             }
   19146                         }
   19147                     }
   19148                     if (conn.mContainerService == null) {
   19149                         return;
   19150                     }
   19151 
   19152                     final UserEnvironment userEnv = new UserEnvironment(curUser);
   19153                     clearDirectory(conn.mContainerService,
   19154                             userEnv.buildExternalStorageAppCacheDirs(packageName));
   19155                     if (allData) {
   19156                         clearDirectory(conn.mContainerService,
   19157                                 userEnv.buildExternalStorageAppDataDirs(packageName));
   19158                         clearDirectory(conn.mContainerService,
   19159                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
   19160                     }
   19161                 }
   19162             } finally {
   19163                 mContext.unbindService(conn);
   19164             }
   19165         }
   19166     }
   19167 
   19168     @Override
   19169     public void clearApplicationProfileData(String packageName) {
   19170         enforceSystemOrRoot("Only the system can clear all profile data");
   19171 
   19172         final PackageParser.Package pkg;
   19173         synchronized (mPackages) {
   19174             pkg = mPackages.get(packageName);
   19175         }
   19176 
   19177         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
   19178             synchronized (mInstallLock) {
   19179                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
   19180             }
   19181         }
   19182     }
   19183 
   19184     @Override
   19185     public void clearApplicationUserData(final String packageName,
   19186             final IPackageDataObserver observer, final int userId) {
   19187         mContext.enforceCallingOrSelfPermission(
   19188                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
   19189 
   19190         final int callingUid = Binder.getCallingUid();
   19191         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   19192                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
   19193 
   19194         final PackageSetting ps = mSettings.getPackageLPr(packageName);
   19195         final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
   19196         if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
   19197             throw new SecurityException("Cannot clear data for a protected package: "
   19198                     + packageName);
   19199         }
   19200         // Queue up an async operation since the package deletion may take a little while.
   19201         mHandler.post(new Runnable() {
   19202             public void run() {
   19203                 mHandler.removeCallbacks(this);
   19204                 final boolean succeeded;
   19205                 if (!filterApp) {
   19206                     try (PackageFreezer freezer = freezePackage(packageName,
   19207                             "clearApplicationUserData")) {
   19208                         synchronized (mInstallLock) {
   19209                             succeeded = clearApplicationUserDataLIF(packageName, userId);
   19210                         }
   19211                         clearExternalStorageDataSync(packageName, userId, true);
   19212                         synchronized (mPackages) {
   19213                             mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
   19214                                     packageName, userId);
   19215                         }
   19216                     }
   19217                     if (succeeded) {
   19218                         // invoke DeviceStorageMonitor's update method to clear any notifications
   19219                         DeviceStorageMonitorInternal dsm = LocalServices
   19220                                 .getService(DeviceStorageMonitorInternal.class);
   19221                         if (dsm != null) {
   19222                             dsm.checkMemory();
   19223                         }
   19224                         if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
   19225                                 == PERMISSION_GRANTED) {
   19226                             unsuspendForSuspendingPackage(packageName, userId);
   19227                         }
   19228                     }
   19229                 } else {
   19230                     succeeded = false;
   19231                 }
   19232                 if (observer != null) {
   19233                     try {
   19234                         observer.onRemoveCompleted(packageName, succeeded);
   19235                     } catch (RemoteException e) {
   19236                         Log.i(TAG, "Observer no longer exists.");
   19237                     }
   19238                 } //end if observer
   19239             } //end run
   19240         });
   19241     }
   19242 
   19243     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
   19244         if (packageName == null) {
   19245             Slog.w(TAG, "Attempt to delete null packageName.");
   19246             return false;
   19247         }
   19248 
   19249         // Try finding details about the requested package
   19250         PackageParser.Package pkg;
   19251         synchronized (mPackages) {
   19252             pkg = mPackages.get(packageName);
   19253             if (pkg == null) {
   19254                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   19255                 if (ps != null) {
   19256                     pkg = ps.pkg;
   19257                 }
   19258             }
   19259 
   19260             if (pkg == null) {
   19261                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
   19262                 return false;
   19263             }
   19264 
   19265             PackageSetting ps = (PackageSetting) pkg.mExtras;
   19266             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
   19267         }
   19268 
   19269         clearAppDataLIF(pkg, userId,
   19270                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
   19271 
   19272         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
   19273         removeKeystoreDataIfNeeded(userId, appId);
   19274 
   19275         UserManagerInternal umInternal = getUserManagerInternal();
   19276         final int flags;
   19277         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
   19278             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
   19279         } else if (umInternal.isUserRunning(userId)) {
   19280             flags = StorageManager.FLAG_STORAGE_DE;
   19281         } else {
   19282             flags = 0;
   19283         }
   19284         prepareAppDataContentsLIF(pkg, userId, flags);
   19285 
   19286         return true;
   19287     }
   19288 
   19289     /**
   19290      * Reverts user permission state changes (permissions and flags) in
   19291      * all packages for a given user.
   19292      *
   19293      * @param userId The device user for which to do a reset.
   19294      */
   19295     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
   19296         final int packageCount = mPackages.size();
   19297         for (int i = 0; i < packageCount; i++) {
   19298             PackageParser.Package pkg = mPackages.valueAt(i);
   19299             PackageSetting ps = (PackageSetting) pkg.mExtras;
   19300             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
   19301         }
   19302     }
   19303 
   19304     private void resetNetworkPolicies(int userId) {
   19305         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
   19306     }
   19307 
   19308     /**
   19309      * Reverts user permission state changes (permissions and flags).
   19310      *
   19311      * @param ps The package for which to reset.
   19312      * @param userId The device user for which to do a reset.
   19313      */
   19314     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
   19315             final PackageSetting ps, final int userId) {
   19316         if (ps.pkg == null) {
   19317             return;
   19318         }
   19319 
   19320         // These are flags that can change base on user actions.
   19321         final int userSettableMask = FLAG_PERMISSION_USER_SET
   19322                 | FLAG_PERMISSION_USER_FIXED
   19323                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
   19324                 | FLAG_PERMISSION_REVIEW_REQUIRED;
   19325 
   19326         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
   19327                 | FLAG_PERMISSION_POLICY_FIXED;
   19328 
   19329         boolean writeInstallPermissions = false;
   19330         boolean writeRuntimePermissions = false;
   19331 
   19332         final int permissionCount = ps.pkg.requestedPermissions.size();
   19333         for (int i = 0; i < permissionCount; i++) {
   19334             final String permName = ps.pkg.requestedPermissions.get(i);
   19335             final BasePermission bp =
   19336                     (BasePermission) mPermissionManager.getPermissionTEMP(permName);
   19337             if (bp == null) {
   19338                 continue;
   19339             }
   19340 
   19341             // If shared user we just reset the state to which only this app contributed.
   19342             if (ps.sharedUser != null) {
   19343                 boolean used = false;
   19344                 final int packageCount = ps.sharedUser.packages.size();
   19345                 for (int j = 0; j < packageCount; j++) {
   19346                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
   19347                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
   19348                             && pkg.pkg.requestedPermissions.contains(permName)) {
   19349                         used = true;
   19350                         break;
   19351                     }
   19352                 }
   19353                 if (used) {
   19354                     continue;
   19355                 }
   19356             }
   19357 
   19358             final PermissionsState permissionsState = ps.getPermissionsState();
   19359 
   19360             final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
   19361 
   19362             // Always clear the user settable flags.
   19363             final boolean hasInstallState =
   19364                     permissionsState.getInstallPermissionState(permName) != null;
   19365             // If permission review is enabled and this is a legacy app, mark the
   19366             // permission as requiring a review as this is the initial state.
   19367             int flags = 0;
   19368             if (mSettings.mPermissions.mPermissionReviewRequired
   19369                     && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
   19370                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
   19371             }
   19372             if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
   19373                 if (hasInstallState) {
   19374                     writeInstallPermissions = true;
   19375                 } else {
   19376                     writeRuntimePermissions = true;
   19377                 }
   19378             }
   19379 
   19380             // Below is only runtime permission handling.
   19381             if (!bp.isRuntime()) {
   19382                 continue;
   19383             }
   19384 
   19385             // Never clobber system or policy.
   19386             if ((oldFlags & policyOrSystemFlags) != 0) {
   19387                 continue;
   19388             }
   19389 
   19390             // If this permission was granted by default, make sure it is.
   19391             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
   19392                 if (permissionsState.grantRuntimePermission(bp, userId)
   19393                         != PERMISSION_OPERATION_FAILURE) {
   19394                     writeRuntimePermissions = true;
   19395                 }
   19396             // If permission review is enabled the permissions for a legacy apps
   19397             // are represented as constantly granted runtime ones, so don't revoke.
   19398             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
   19399                 // Otherwise, reset the permission.
   19400                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
   19401                 switch (revokeResult) {
   19402                     case PERMISSION_OPERATION_SUCCESS:
   19403                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
   19404                         writeRuntimePermissions = true;
   19405                         final int appId = ps.appId;
   19406                         mHandler.post(new Runnable() {
   19407                             @Override
   19408                             public void run() {
   19409                                 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
   19410                             }
   19411                         });
   19412                     } break;
   19413                 }
   19414             }
   19415         }
   19416 
   19417         // Synchronously write as we are taking permissions away.
   19418         if (writeRuntimePermissions) {
   19419             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
   19420         }
   19421 
   19422         // Synchronously write as we are taking permissions away.
   19423         if (writeInstallPermissions) {
   19424             mSettings.writeLPr();
   19425         }
   19426     }
   19427 
   19428     /**
   19429      * Remove entries from the keystore daemon. Will only remove it if the
   19430      * {@code appId} is valid.
   19431      */
   19432     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
   19433         if (appId < 0) {
   19434             return;
   19435         }
   19436 
   19437         final KeyStore keyStore = KeyStore.getInstance();
   19438         if (keyStore != null) {
   19439             if (userId == UserHandle.USER_ALL) {
   19440                 for (final int individual : sUserManager.getUserIds()) {
   19441                     keyStore.clearUid(UserHandle.getUid(individual, appId));
   19442                 }
   19443             } else {
   19444                 keyStore.clearUid(UserHandle.getUid(userId, appId));
   19445             }
   19446         } else {
   19447             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
   19448         }
   19449     }
   19450 
   19451     @Override
   19452     public void deleteApplicationCacheFiles(final String packageName,
   19453             final IPackageDataObserver observer) {
   19454         final int userId = UserHandle.getCallingUserId();
   19455         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
   19456     }
   19457 
   19458     @Override
   19459     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
   19460             final IPackageDataObserver observer) {
   19461         final int callingUid = Binder.getCallingUid();
   19462         if (mContext.checkCallingOrSelfPermission(
   19463                 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
   19464                 != PackageManager.PERMISSION_GRANTED) {
   19465             // If the caller has the old delete cache permission, silently ignore.  Else throw.
   19466             if (mContext.checkCallingOrSelfPermission(
   19467                     android.Manifest.permission.DELETE_CACHE_FILES)
   19468                     == PackageManager.PERMISSION_GRANTED) {
   19469                 Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
   19470                         android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
   19471                         ", silently ignoring");
   19472                 return;
   19473             }
   19474             mContext.enforceCallingOrSelfPermission(
   19475                     android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
   19476         }
   19477         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   19478                 /* requireFullPermission= */ true, /* checkShell= */ false,
   19479                 "delete application cache files");
   19480         final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
   19481                 android.Manifest.permission.ACCESS_INSTANT_APPS);
   19482 
   19483         final PackageParser.Package pkg;
   19484         synchronized (mPackages) {
   19485             pkg = mPackages.get(packageName);
   19486         }
   19487 
   19488         // Queue up an async operation since the package deletion may take a little while.
   19489         mHandler.post(new Runnable() {
   19490             public void run() {
   19491                 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
   19492                 boolean doClearData = true;
   19493                 if (ps != null) {
   19494                     final boolean targetIsInstantApp =
   19495                             ps.getInstantApp(UserHandle.getUserId(callingUid));
   19496                     doClearData = !targetIsInstantApp
   19497                             || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
   19498                 }
   19499                 if (doClearData) {
   19500                     synchronized (mInstallLock) {
   19501                         final int flags = StorageManager.FLAG_STORAGE_DE
   19502                                 | StorageManager.FLAG_STORAGE_CE;
   19503                         // We're only clearing cache files, so we don't care if the
   19504                         // app is unfrozen and still able to run
   19505                         clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
   19506                         clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   19507                     }
   19508                     clearExternalStorageDataSync(packageName, userId, false);
   19509                 }
   19510                 if (observer != null) {
   19511                     try {
   19512                         observer.onRemoveCompleted(packageName, true);
   19513                     } catch (RemoteException e) {
   19514                         Log.i(TAG, "Observer no longer exists.");
   19515                     }
   19516                 }
   19517             }
   19518         });
   19519     }
   19520 
   19521     @Override
   19522     public void getPackageSizeInfo(final String packageName, int userHandle,
   19523             final IPackageStatsObserver observer) {
   19524         throw new UnsupportedOperationException(
   19525                 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
   19526     }
   19527 
   19528     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
   19529         final PackageSetting ps;
   19530         synchronized (mPackages) {
   19531             ps = mSettings.mPackages.get(packageName);
   19532             if (ps == null) {
   19533                 Slog.w(TAG, "Failed to find settings for " + packageName);
   19534                 return false;
   19535             }
   19536         }
   19537 
   19538         final String[] packageNames = { packageName };
   19539         final long[] ceDataInodes = { ps.getCeDataInode(userId) };
   19540         final String[] codePaths = { ps.codePathString };
   19541 
   19542         try {
   19543             mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
   19544                     ps.appId, ceDataInodes, codePaths, stats);
   19545 
   19546             // For now, ignore code size of packages on system partition
   19547             if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
   19548                 stats.codeSize = 0;
   19549             }
   19550 
   19551             // External clients expect these to be tracked separately
   19552             stats.dataSize -= stats.cacheSize;
   19553 
   19554         } catch (InstallerException e) {
   19555             Slog.w(TAG, String.valueOf(e));
   19556             return false;
   19557         }
   19558 
   19559         return true;
   19560     }
   19561 
   19562     private int getUidTargetSdkVersionLockedLPr(int uid) {
   19563         Object obj = mSettings.getUserIdLPr(uid);
   19564         if (obj instanceof SharedUserSetting) {
   19565             final SharedUserSetting sus = (SharedUserSetting) obj;
   19566             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
   19567             final Iterator<PackageSetting> it = sus.packages.iterator();
   19568             while (it.hasNext()) {
   19569                 final PackageSetting ps = it.next();
   19570                 if (ps.pkg != null) {
   19571                     int v = ps.pkg.applicationInfo.targetSdkVersion;
   19572                     if (v < vers) vers = v;
   19573                 }
   19574             }
   19575             return vers;
   19576         } else if (obj instanceof PackageSetting) {
   19577             final PackageSetting ps = (PackageSetting) obj;
   19578             if (ps.pkg != null) {
   19579                 return ps.pkg.applicationInfo.targetSdkVersion;
   19580             }
   19581         }
   19582         return Build.VERSION_CODES.CUR_DEVELOPMENT;
   19583     }
   19584 
   19585     private int getPackageTargetSdkVersionLockedLPr(String packageName) {
   19586         final PackageParser.Package p = mPackages.get(packageName);
   19587         if (p != null) {
   19588             return p.applicationInfo.targetSdkVersion;
   19589         }
   19590         return Build.VERSION_CODES.CUR_DEVELOPMENT;
   19591     }
   19592 
   19593     @Override
   19594     public void addPreferredActivity(IntentFilter filter, int match,
   19595             ComponentName[] set, ComponentName activity, int userId) {
   19596         addPreferredActivityInternal(filter, match, set, activity, true, userId,
   19597                 "Adding preferred");
   19598     }
   19599 
   19600     private void addPreferredActivityInternal(IntentFilter filter, int match,
   19601             ComponentName[] set, ComponentName activity, boolean always, int userId,
   19602             String opname) {
   19603         // writer
   19604         int callingUid = Binder.getCallingUid();
   19605         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   19606                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
   19607         if (filter.countActions() == 0) {
   19608             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
   19609             return;
   19610         }
   19611         synchronized (mPackages) {
   19612             if (mContext.checkCallingOrSelfPermission(
   19613                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
   19614                     != PackageManager.PERMISSION_GRANTED) {
   19615                 if (getUidTargetSdkVersionLockedLPr(callingUid)
   19616                         < Build.VERSION_CODES.FROYO) {
   19617                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
   19618                             + callingUid);
   19619                     return;
   19620                 }
   19621                 mContext.enforceCallingOrSelfPermission(
   19622                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   19623             }
   19624 
   19625             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
   19626             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
   19627                     + userId + ":");
   19628             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   19629             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
   19630             scheduleWritePackageRestrictionsLocked(userId);
   19631             postPreferredActivityChangedBroadcast(userId);
   19632         }
   19633     }
   19634 
   19635     private void postPreferredActivityChangedBroadcast(int userId) {
   19636         mHandler.post(() -> {
   19637             final IActivityManager am = ActivityManager.getService();
   19638             if (am == null) {
   19639                 return;
   19640             }
   19641 
   19642             final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
   19643             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
   19644             try {
   19645                 am.broadcastIntent(null, intent, null, null,
   19646                         0, null, null, null, android.app.AppOpsManager.OP_NONE,
   19647                         null, false, false, userId);
   19648             } catch (RemoteException e) {
   19649             }
   19650         });
   19651     }
   19652 
   19653     @Override
   19654     public void replacePreferredActivity(IntentFilter filter, int match,
   19655             ComponentName[] set, ComponentName activity, int userId) {
   19656         if (filter.countActions() != 1) {
   19657             throw new IllegalArgumentException(
   19658                     "replacePreferredActivity expects filter to have only 1 action.");
   19659         }
   19660         if (filter.countDataAuthorities() != 0
   19661                 || filter.countDataPaths() != 0
   19662                 || filter.countDataSchemes() > 1
   19663                 || filter.countDataTypes() != 0) {
   19664             throw new IllegalArgumentException(
   19665                     "replacePreferredActivity expects filter to have no data authorities, " +
   19666                     "paths, or types; and at most one scheme.");
   19667         }
   19668 
   19669         final int callingUid = Binder.getCallingUid();
   19670         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   19671                 true /* requireFullPermission */, false /* checkShell */,
   19672                 "replace preferred activity");
   19673         synchronized (mPackages) {
   19674             if (mContext.checkCallingOrSelfPermission(
   19675                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
   19676                     != PackageManager.PERMISSION_GRANTED) {
   19677                 if (getUidTargetSdkVersionLockedLPr(callingUid)
   19678                         < Build.VERSION_CODES.FROYO) {
   19679                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
   19680                             + Binder.getCallingUid());
   19681                     return;
   19682                 }
   19683                 mContext.enforceCallingOrSelfPermission(
   19684                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   19685             }
   19686 
   19687             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   19688             if (pir != null) {
   19689                 // Get all of the existing entries that exactly match this filter.
   19690                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
   19691                 if (existing != null && existing.size() == 1) {
   19692                     PreferredActivity cur = existing.get(0);
   19693                     if (DEBUG_PREFERRED) {
   19694                         Slog.i(TAG, "Checking replace of preferred:");
   19695                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   19696                         if (!cur.mPref.mAlways) {
   19697                             Slog.i(TAG, "  -- CUR; not mAlways!");
   19698                         } else {
   19699                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
   19700                             Slog.i(TAG, "  -- CUR: mSet="
   19701                                     + Arrays.toString(cur.mPref.mSetComponents));
   19702                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
   19703                             Slog.i(TAG, "  -- NEW: mMatch="
   19704                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
   19705                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
   19706                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
   19707                         }
   19708                     }
   19709                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
   19710                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
   19711                             && cur.mPref.sameSet(set)) {
   19712                         // Setting the preferred activity to what it happens to be already
   19713                         if (DEBUG_PREFERRED) {
   19714                             Slog.i(TAG, "Replacing with same preferred activity "
   19715                                     + cur.mPref.mShortComponent + " for user "
   19716                                     + userId + ":");
   19717                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   19718                         }
   19719                         return;
   19720                     }
   19721                 }
   19722 
   19723                 if (existing != null) {
   19724                     if (DEBUG_PREFERRED) {
   19725                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
   19726                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   19727                     }
   19728                     for (int i = 0; i < existing.size(); i++) {
   19729                         PreferredActivity pa = existing.get(i);
   19730                         if (DEBUG_PREFERRED) {
   19731                             Slog.i(TAG, "Removing existing preferred activity "
   19732                                     + pa.mPref.mComponent + ":");
   19733                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
   19734                         }
   19735                         pir.removeFilter(pa);
   19736                     }
   19737                 }
   19738             }
   19739             addPreferredActivityInternal(filter, match, set, activity, true, userId,
   19740                     "Replacing preferred");
   19741         }
   19742     }
   19743 
   19744     @Override
   19745     public void clearPackagePreferredActivities(String packageName) {
   19746         final int callingUid = Binder.getCallingUid();
   19747         if (getInstantAppPackageName(callingUid) != null) {
   19748             return;
   19749         }
   19750         // writer
   19751         synchronized (mPackages) {
   19752             PackageParser.Package pkg = mPackages.get(packageName);
   19753             if (pkg == null || pkg.applicationInfo.uid != callingUid) {
   19754                 if (mContext.checkCallingOrSelfPermission(
   19755                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
   19756                         != PackageManager.PERMISSION_GRANTED) {
   19757                     if (getUidTargetSdkVersionLockedLPr(callingUid)
   19758                             < Build.VERSION_CODES.FROYO) {
   19759                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
   19760                                 + callingUid);
   19761                         return;
   19762                     }
   19763                     mContext.enforceCallingOrSelfPermission(
   19764                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   19765                 }
   19766             }
   19767             final PackageSetting ps = mSettings.getPackageLPr(packageName);
   19768             if (ps != null
   19769                     && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   19770                 return;
   19771             }
   19772             int user = UserHandle.getCallingUserId();
   19773             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
   19774                 scheduleWritePackageRestrictionsLocked(user);
   19775             }
   19776         }
   19777     }
   19778 
   19779     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
   19780     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
   19781         ArrayList<PreferredActivity> removed = null;
   19782         boolean changed = false;
   19783         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
   19784             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
   19785             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
   19786             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
   19787                 continue;
   19788             }
   19789             Iterator<PreferredActivity> it = pir.filterIterator();
   19790             while (it.hasNext()) {
   19791                 PreferredActivity pa = it.next();
   19792                 // Mark entry for removal only if it matches the package name
   19793                 // and the entry is of type "always".
   19794                 if (packageName == null ||
   19795                         (pa.mPref.mComponent.getPackageName().equals(packageName)
   19796                                 && pa.mPref.mAlways)) {
   19797                     if (removed == null) {
   19798                         removed = new ArrayList<PreferredActivity>();
   19799                     }
   19800                     removed.add(pa);
   19801                 }
   19802             }
   19803             if (removed != null) {
   19804                 for (int j=0; j<removed.size(); j++) {
   19805                     PreferredActivity pa = removed.get(j);
   19806                     pir.removeFilter(pa);
   19807                 }
   19808                 changed = true;
   19809             }
   19810         }
   19811         if (changed) {
   19812             postPreferredActivityChangedBroadcast(userId);
   19813         }
   19814         return changed;
   19815     }
   19816 
   19817     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
   19818     private void clearIntentFilterVerificationsLPw(int userId) {
   19819         final int packageCount = mPackages.size();
   19820         for (int i = 0; i < packageCount; i++) {
   19821             PackageParser.Package pkg = mPackages.valueAt(i);
   19822             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
   19823         }
   19824     }
   19825 
   19826     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
   19827     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
   19828         if (userId == UserHandle.USER_ALL) {
   19829             if (mSettings.removeIntentFilterVerificationLPw(packageName,
   19830                     sUserManager.getUserIds())) {
   19831                 for (int oneUserId : sUserManager.getUserIds()) {
   19832                     scheduleWritePackageRestrictionsLocked(oneUserId);
   19833                 }
   19834             }
   19835         } else {
   19836             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
   19837                 scheduleWritePackageRestrictionsLocked(userId);
   19838             }
   19839         }
   19840     }
   19841 
   19842     /** Clears state for all users, and touches intent filter verification policy */
   19843     void clearDefaultBrowserIfNeeded(String packageName) {
   19844         for (int oneUserId : sUserManager.getUserIds()) {
   19845             clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
   19846         }
   19847     }
   19848 
   19849     private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
   19850         final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
   19851         if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
   19852             if (packageName.equals(defaultBrowserPackageName)) {
   19853                 setDefaultBrowserPackageName(null, userId);
   19854             }
   19855         }
   19856     }
   19857 
   19858     @Override
   19859     public void resetApplicationPreferences(int userId) {
   19860         mContext.enforceCallingOrSelfPermission(
   19861                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   19862         final long identity = Binder.clearCallingIdentity();
   19863         // writer
   19864         try {
   19865             synchronized (mPackages) {
   19866                 clearPackagePreferredActivitiesLPw(null, userId);
   19867                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
   19868                 // TODO: We have to reset the default SMS and Phone. This requires
   19869                 // significant refactoring to keep all default apps in the package
   19870                 // manager (cleaner but more work) or have the services provide
   19871                 // callbacks to the package manager to request a default app reset.
   19872                 applyFactoryDefaultBrowserLPw(userId);
   19873                 clearIntentFilterVerificationsLPw(userId);
   19874                 primeDomainVerificationsLPw(userId);
   19875                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
   19876                 scheduleWritePackageRestrictionsLocked(userId);
   19877             }
   19878             resetNetworkPolicies(userId);
   19879         } finally {
   19880             Binder.restoreCallingIdentity(identity);
   19881         }
   19882     }
   19883 
   19884     @Override
   19885     public int getPreferredActivities(List<IntentFilter> outFilters,
   19886             List<ComponentName> outActivities, String packageName) {
   19887         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   19888             return 0;
   19889         }
   19890         int num = 0;
   19891         final int userId = UserHandle.getCallingUserId();
   19892         // reader
   19893         synchronized (mPackages) {
   19894             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   19895             if (pir != null) {
   19896                 final Iterator<PreferredActivity> it = pir.filterIterator();
   19897                 while (it.hasNext()) {
   19898                     final PreferredActivity pa = it.next();
   19899                     if (packageName == null
   19900                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
   19901                                     && pa.mPref.mAlways)) {
   19902                         if (outFilters != null) {
   19903                             outFilters.add(new IntentFilter(pa));
   19904                         }
   19905                         if (outActivities != null) {
   19906                             outActivities.add(pa.mPref.mComponent);
   19907                         }
   19908                     }
   19909                 }
   19910             }
   19911         }
   19912 
   19913         return num;
   19914     }
   19915 
   19916     @Override
   19917     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
   19918             int userId) {
   19919         int callingUid = Binder.getCallingUid();
   19920         if (callingUid != Process.SYSTEM_UID) {
   19921             throw new SecurityException(
   19922                     "addPersistentPreferredActivity can only be run by the system");
   19923         }
   19924         if (filter.countActions() == 0) {
   19925             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
   19926             return;
   19927         }
   19928         synchronized (mPackages) {
   19929             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
   19930                     ":");
   19931             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   19932             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
   19933                     new PersistentPreferredActivity(filter, activity));
   19934             scheduleWritePackageRestrictionsLocked(userId);
   19935             postPreferredActivityChangedBroadcast(userId);
   19936         }
   19937     }
   19938 
   19939     @Override
   19940     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
   19941         int callingUid = Binder.getCallingUid();
   19942         if (callingUid != Process.SYSTEM_UID) {
   19943             throw new SecurityException(
   19944                     "clearPackagePersistentPreferredActivities can only be run by the system");
   19945         }
   19946         ArrayList<PersistentPreferredActivity> removed = null;
   19947         boolean changed = false;
   19948         synchronized (mPackages) {
   19949             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
   19950                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
   19951                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
   19952                         .valueAt(i);
   19953                 if (userId != thisUserId) {
   19954                     continue;
   19955                 }
   19956                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
   19957                 while (it.hasNext()) {
   19958                     PersistentPreferredActivity ppa = it.next();
   19959                     // Mark entry for removal only if it matches the package name.
   19960                     if (ppa.mComponent.getPackageName().equals(packageName)) {
   19961                         if (removed == null) {
   19962                             removed = new ArrayList<PersistentPreferredActivity>();
   19963                         }
   19964                         removed.add(ppa);
   19965                     }
   19966                 }
   19967                 if (removed != null) {
   19968                     for (int j=0; j<removed.size(); j++) {
   19969                         PersistentPreferredActivity ppa = removed.get(j);
   19970                         ppir.removeFilter(ppa);
   19971                     }
   19972                     changed = true;
   19973                 }
   19974             }
   19975 
   19976             if (changed) {
   19977                 scheduleWritePackageRestrictionsLocked(userId);
   19978                 postPreferredActivityChangedBroadcast(userId);
   19979             }
   19980         }
   19981     }
   19982 
   19983     /**
   19984      * Common machinery for picking apart a restored XML blob and passing
   19985      * it to a caller-supplied functor to be applied to the running system.
   19986      */
   19987     private void restoreFromXml(XmlPullParser parser, int userId,
   19988             String expectedStartTag, BlobXmlRestorer functor)
   19989             throws IOException, XmlPullParserException {
   19990         int type;
   19991         while ((type = parser.next()) != XmlPullParser.START_TAG
   19992                 && type != XmlPullParser.END_DOCUMENT) {
   19993         }
   19994         if (type != XmlPullParser.START_TAG) {
   19995             // oops didn't find a start tag?!
   19996             if (DEBUG_BACKUP) {
   19997                 Slog.e(TAG, "Didn't find start tag during restore");
   19998             }
   19999             return;
   20000         }
   20001 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
   20002         // this is supposed to be TAG_PREFERRED_BACKUP
   20003         if (!expectedStartTag.equals(parser.getName())) {
   20004             if (DEBUG_BACKUP) {
   20005                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
   20006             }
   20007             return;
   20008         }
   20009 
   20010         // skip interfering stuff, then we're aligned with the backing implementation
   20011         while ((type = parser.next()) == XmlPullParser.TEXT) { }
   20012 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
   20013         functor.apply(parser, userId);
   20014     }
   20015 
   20016     private interface BlobXmlRestorer {
   20017         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
   20018     }
   20019 
   20020     /**
   20021      * Non-Binder method, support for the backup/restore mechanism: write the
   20022      * full set of preferred activities in its canonical XML format.  Returns the
   20023      * XML output as a byte array, or null if there is none.
   20024      */
   20025     @Override
   20026     public byte[] getPreferredActivityBackup(int userId) {
   20027         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20028             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
   20029         }
   20030 
   20031         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
   20032         try {
   20033             final XmlSerializer serializer = new FastXmlSerializer();
   20034             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
   20035             serializer.startDocument(null, true);
   20036             serializer.startTag(null, TAG_PREFERRED_BACKUP);
   20037 
   20038             synchronized (mPackages) {
   20039                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
   20040             }
   20041 
   20042             serializer.endTag(null, TAG_PREFERRED_BACKUP);
   20043             serializer.endDocument();
   20044             serializer.flush();
   20045         } catch (Exception e) {
   20046             if (DEBUG_BACKUP) {
   20047                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
   20048             }
   20049             return null;
   20050         }
   20051 
   20052         return dataStream.toByteArray();
   20053     }
   20054 
   20055     @Override
   20056     public void restorePreferredActivities(byte[] backup, int userId) {
   20057         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20058             throw new SecurityException("Only the system may call restorePreferredActivities()");
   20059         }
   20060 
   20061         try {
   20062             final XmlPullParser parser = Xml.newPullParser();
   20063             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
   20064             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
   20065                     new BlobXmlRestorer() {
   20066                         @Override
   20067                         public void apply(XmlPullParser parser, int userId)
   20068                                 throws XmlPullParserException, IOException {
   20069                             synchronized (mPackages) {
   20070                                 mSettings.readPreferredActivitiesLPw(parser, userId);
   20071                             }
   20072                         }
   20073                     } );
   20074         } catch (Exception e) {
   20075             if (DEBUG_BACKUP) {
   20076                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
   20077             }
   20078         }
   20079     }
   20080 
   20081     /**
   20082      * Non-Binder method, support for the backup/restore mechanism: write the
   20083      * default browser (etc) settings in its canonical XML format.  Returns the default
   20084      * browser XML representation as a byte array, or null if there is none.
   20085      */
   20086     @Override
   20087     public byte[] getDefaultAppsBackup(int userId) {
   20088         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20089             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
   20090         }
   20091 
   20092         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
   20093         try {
   20094             final XmlSerializer serializer = new FastXmlSerializer();
   20095             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
   20096             serializer.startDocument(null, true);
   20097             serializer.startTag(null, TAG_DEFAULT_APPS);
   20098 
   20099             synchronized (mPackages) {
   20100                 mSettings.writeDefaultAppsLPr(serializer, userId);
   20101             }
   20102 
   20103             serializer.endTag(null, TAG_DEFAULT_APPS);
   20104             serializer.endDocument();
   20105             serializer.flush();
   20106         } catch (Exception e) {
   20107             if (DEBUG_BACKUP) {
   20108                 Slog.e(TAG, "Unable to write default apps for backup", e);
   20109             }
   20110             return null;
   20111         }
   20112 
   20113         return dataStream.toByteArray();
   20114     }
   20115 
   20116     @Override
   20117     public void restoreDefaultApps(byte[] backup, int userId) {
   20118         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20119             throw new SecurityException("Only the system may call restoreDefaultApps()");
   20120         }
   20121 
   20122         try {
   20123             final XmlPullParser parser = Xml.newPullParser();
   20124             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
   20125             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
   20126                     new BlobXmlRestorer() {
   20127                         @Override
   20128                         public void apply(XmlPullParser parser, int userId)
   20129                                 throws XmlPullParserException, IOException {
   20130                             synchronized (mPackages) {
   20131                                 mSettings.readDefaultAppsLPw(parser, userId);
   20132                             }
   20133                         }
   20134                     } );
   20135         } catch (Exception e) {
   20136             if (DEBUG_BACKUP) {
   20137                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
   20138             }
   20139         }
   20140     }
   20141 
   20142     @Override
   20143     public byte[] getIntentFilterVerificationBackup(int userId) {
   20144         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20145             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
   20146         }
   20147 
   20148         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
   20149         try {
   20150             final XmlSerializer serializer = new FastXmlSerializer();
   20151             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
   20152             serializer.startDocument(null, true);
   20153             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
   20154 
   20155             synchronized (mPackages) {
   20156                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
   20157             }
   20158 
   20159             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
   20160             serializer.endDocument();
   20161             serializer.flush();
   20162         } catch (Exception e) {
   20163             if (DEBUG_BACKUP) {
   20164                 Slog.e(TAG, "Unable to write default apps for backup", e);
   20165             }
   20166             return null;
   20167         }
   20168 
   20169         return dataStream.toByteArray();
   20170     }
   20171 
   20172     @Override
   20173     public void restoreIntentFilterVerification(byte[] backup, int userId) {
   20174         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20175             throw new SecurityException("Only the system may call restorePreferredActivities()");
   20176         }
   20177 
   20178         try {
   20179             final XmlPullParser parser = Xml.newPullParser();
   20180             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
   20181             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
   20182                     new BlobXmlRestorer() {
   20183                         @Override
   20184                         public void apply(XmlPullParser parser, int userId)
   20185                                 throws XmlPullParserException, IOException {
   20186                             synchronized (mPackages) {
   20187                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
   20188                                 mSettings.writeLPr();
   20189                             }
   20190                         }
   20191                     } );
   20192         } catch (Exception e) {
   20193             if (DEBUG_BACKUP) {
   20194                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
   20195             }
   20196         }
   20197     }
   20198 
   20199     @Override
   20200     public byte[] getPermissionGrantBackup(int userId) {
   20201         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20202             throw new SecurityException("Only the system may call getPermissionGrantBackup()");
   20203         }
   20204 
   20205         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
   20206         try {
   20207             final XmlSerializer serializer = new FastXmlSerializer();
   20208             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
   20209             serializer.startDocument(null, true);
   20210             serializer.startTag(null, TAG_PERMISSION_BACKUP);
   20211 
   20212             synchronized (mPackages) {
   20213                 serializeRuntimePermissionGrantsLPr(serializer, userId);
   20214             }
   20215 
   20216             serializer.endTag(null, TAG_PERMISSION_BACKUP);
   20217             serializer.endDocument();
   20218             serializer.flush();
   20219         } catch (Exception e) {
   20220             if (DEBUG_BACKUP) {
   20221                 Slog.e(TAG, "Unable to write default apps for backup", e);
   20222             }
   20223             return null;
   20224         }
   20225 
   20226         return dataStream.toByteArray();
   20227     }
   20228 
   20229     @Override
   20230     public void restorePermissionGrants(byte[] backup, int userId) {
   20231         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
   20232             throw new SecurityException("Only the system may call restorePermissionGrants()");
   20233         }
   20234 
   20235         try {
   20236             final XmlPullParser parser = Xml.newPullParser();
   20237             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
   20238             restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
   20239                     new BlobXmlRestorer() {
   20240                         @Override
   20241                         public void apply(XmlPullParser parser, int userId)
   20242                                 throws XmlPullParserException, IOException {
   20243                             synchronized (mPackages) {
   20244                                 processRestoredPermissionGrantsLPr(parser, userId);
   20245                             }
   20246                         }
   20247                     } );
   20248         } catch (Exception e) {
   20249             if (DEBUG_BACKUP) {
   20250                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
   20251             }
   20252         }
   20253     }
   20254 
   20255     private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
   20256             throws IOException {
   20257         serializer.startTag(null, TAG_ALL_GRANTS);
   20258 
   20259         final int N = mSettings.mPackages.size();
   20260         for (int i = 0; i < N; i++) {
   20261             final PackageSetting ps = mSettings.mPackages.valueAt(i);
   20262             boolean pkgGrantsKnown = false;
   20263 
   20264             PermissionsState packagePerms = ps.getPermissionsState();
   20265 
   20266             for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
   20267                 final int grantFlags = state.getFlags();
   20268                 // only look at grants that are not system/policy fixed
   20269                 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
   20270                     final boolean isGranted = state.isGranted();
   20271                     // And only back up the user-twiddled state bits
   20272                     if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
   20273                         final String packageName = mSettings.mPackages.keyAt(i);
   20274                         if (!pkgGrantsKnown) {
   20275                             serializer.startTag(null, TAG_GRANT);
   20276                             serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
   20277                             pkgGrantsKnown = true;
   20278                         }
   20279 
   20280                         final boolean userSet =
   20281                                 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
   20282                         final boolean userFixed =
   20283                                 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
   20284                         final boolean revoke =
   20285                                 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
   20286 
   20287                         serializer.startTag(null, TAG_PERMISSION);
   20288                         serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
   20289                         if (isGranted) {
   20290                             serializer.attribute(null, ATTR_IS_GRANTED, "true");
   20291                         }
   20292                         if (userSet) {
   20293                             serializer.attribute(null, ATTR_USER_SET, "true");
   20294                         }
   20295                         if (userFixed) {
   20296                             serializer.attribute(null, ATTR_USER_FIXED, "true");
   20297                         }
   20298                         if (revoke) {
   20299                             serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
   20300                         }
   20301                         serializer.endTag(null, TAG_PERMISSION);
   20302                     }
   20303                 }
   20304             }
   20305 
   20306             if (pkgGrantsKnown) {
   20307                 serializer.endTag(null, TAG_GRANT);
   20308             }
   20309         }
   20310 
   20311         serializer.endTag(null, TAG_ALL_GRANTS);
   20312     }
   20313 
   20314     private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
   20315             throws XmlPullParserException, IOException {
   20316         String pkgName = null;
   20317         int outerDepth = parser.getDepth();
   20318         int type;
   20319         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   20320                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   20321             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   20322                 continue;
   20323             }
   20324 
   20325             final String tagName = parser.getName();
   20326             if (tagName.equals(TAG_GRANT)) {
   20327                 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
   20328                 if (DEBUG_BACKUP) {
   20329                     Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
   20330                 }
   20331             } else if (tagName.equals(TAG_PERMISSION)) {
   20332 
   20333                 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
   20334                 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
   20335 
   20336                 int newFlagSet = 0;
   20337                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
   20338                     newFlagSet |= FLAG_PERMISSION_USER_SET;
   20339                 }
   20340                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
   20341                     newFlagSet |= FLAG_PERMISSION_USER_FIXED;
   20342                 }
   20343                 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
   20344                     newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
   20345                 }
   20346                 if (DEBUG_BACKUP) {
   20347                     Slog.v(TAG, "  + Restoring grant:"
   20348                             + " pkg=" + pkgName
   20349                             + " perm=" + permName
   20350                             + " granted=" + isGranted
   20351                             + " bits=0x" + Integer.toHexString(newFlagSet));
   20352                 }
   20353                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
   20354                 if (ps != null) {
   20355                     // Already installed so we apply the grant immediately
   20356                     if (DEBUG_BACKUP) {
   20357                         Slog.v(TAG, "        + already installed; applying");
   20358                     }
   20359                     PermissionsState perms = ps.getPermissionsState();
   20360                     BasePermission bp =
   20361                             (BasePermission) mPermissionManager.getPermissionTEMP(permName);
   20362                     if (bp != null) {
   20363                         if (isGranted) {
   20364                             perms.grantRuntimePermission(bp, userId);
   20365                         }
   20366                         if (newFlagSet != 0) {
   20367                             perms.updatePermissionFlags(
   20368                                     bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
   20369                         }
   20370                     }
   20371                 } else {
   20372                     // Need to wait for post-restore install to apply the grant
   20373                     if (DEBUG_BACKUP) {
   20374                         Slog.v(TAG, "        - not yet installed; saving for later");
   20375                     }
   20376                     mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
   20377                             isGranted, newFlagSet, userId);
   20378                 }
   20379             } else {
   20380                 PackageManagerService.reportSettingsProblem(Log.WARN,
   20381                         "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
   20382                 XmlUtils.skipCurrentTag(parser);
   20383             }
   20384         }
   20385 
   20386         scheduleWriteSettingsLocked();
   20387         mSettings.writeRuntimePermissionsForUserLPr(userId, false);
   20388     }
   20389 
   20390     @Override
   20391     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
   20392             int sourceUserId, int targetUserId, int flags) {
   20393         mContext.enforceCallingOrSelfPermission(
   20394                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   20395         int callingUid = Binder.getCallingUid();
   20396         enforceOwnerRights(ownerPackage, callingUid);
   20397         PackageManagerServiceUtils.enforceShellRestriction(
   20398                 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
   20399         if (intentFilter.countActions() == 0) {
   20400             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
   20401             return;
   20402         }
   20403         synchronized (mPackages) {
   20404             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
   20405                     ownerPackage, targetUserId, flags);
   20406             CrossProfileIntentResolver resolver =
   20407                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
   20408             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
   20409             // We have all those whose filter is equal. Now checking if the rest is equal as well.
   20410             if (existing != null) {
   20411                 int size = existing.size();
   20412                 for (int i = 0; i < size; i++) {
   20413                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
   20414                         return;
   20415                     }
   20416                 }
   20417             }
   20418             resolver.addFilter(newFilter);
   20419             scheduleWritePackageRestrictionsLocked(sourceUserId);
   20420         }
   20421     }
   20422 
   20423     @Override
   20424     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
   20425         mContext.enforceCallingOrSelfPermission(
   20426                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   20427         final int callingUid = Binder.getCallingUid();
   20428         enforceOwnerRights(ownerPackage, callingUid);
   20429         PackageManagerServiceUtils.enforceShellRestriction(
   20430                 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
   20431         synchronized (mPackages) {
   20432             CrossProfileIntentResolver resolver =
   20433                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
   20434             ArraySet<CrossProfileIntentFilter> set =
   20435                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
   20436             for (CrossProfileIntentFilter filter : set) {
   20437                 if (filter.getOwnerPackage().equals(ownerPackage)) {
   20438                     resolver.removeFilter(filter);
   20439                 }
   20440             }
   20441             scheduleWritePackageRestrictionsLocked(sourceUserId);
   20442         }
   20443     }
   20444 
   20445     // Enforcing that callingUid is owning pkg on userId
   20446     private void enforceOwnerRights(String pkg, int callingUid) {
   20447         // The system owns everything.
   20448         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
   20449             return;
   20450         }
   20451         final int callingUserId = UserHandle.getUserId(callingUid);
   20452         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
   20453         if (pi == null) {
   20454             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
   20455                     + callingUserId);
   20456         }
   20457         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
   20458             throw new SecurityException("Calling uid " + callingUid
   20459                     + " does not own package " + pkg);
   20460         }
   20461     }
   20462 
   20463     @Override
   20464     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
   20465         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   20466             return null;
   20467         }
   20468         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
   20469     }
   20470 
   20471     public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
   20472         UserManagerService ums = UserManagerService.getInstance();
   20473         if (ums != null) {
   20474             final UserInfo parent = ums.getProfileParent(userId);
   20475             final int launcherUid = (parent != null) ? parent.id : userId;
   20476             final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
   20477             if (launcherComponent != null) {
   20478                 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
   20479                         .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
   20480                         .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
   20481                         .setPackage(launcherComponent.getPackageName());
   20482                 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
   20483             }
   20484         }
   20485     }
   20486 
   20487     /**
   20488      * Report the 'Home' activity which is currently set as "always use this one". If non is set
   20489      * then reports the most likely home activity or null if there are more than one.
   20490      */
   20491     private ComponentName getDefaultHomeActivity(int userId) {
   20492         List<ResolveInfo> allHomeCandidates = new ArrayList<>();
   20493         ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
   20494         if (cn != null) {
   20495             return cn;
   20496         }
   20497 
   20498         // Find the launcher with the highest priority and return that component if there are no
   20499         // other home activity with the same priority.
   20500         int lastPriority = Integer.MIN_VALUE;
   20501         ComponentName lastComponent = null;
   20502         final int size = allHomeCandidates.size();
   20503         for (int i = 0; i < size; i++) {
   20504             final ResolveInfo ri = allHomeCandidates.get(i);
   20505             if (ri.priority > lastPriority) {
   20506                 lastComponent = ri.activityInfo.getComponentName();
   20507                 lastPriority = ri.priority;
   20508             } else if (ri.priority == lastPriority) {
   20509                 // Two components found with same priority.
   20510                 lastComponent = null;
   20511             }
   20512         }
   20513         return lastComponent;
   20514     }
   20515 
   20516     private Intent getHomeIntent() {
   20517         Intent intent = new Intent(Intent.ACTION_MAIN);
   20518         intent.addCategory(Intent.CATEGORY_HOME);
   20519         intent.addCategory(Intent.CATEGORY_DEFAULT);
   20520         return intent;
   20521     }
   20522 
   20523     private IntentFilter getHomeFilter() {
   20524         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
   20525         filter.addCategory(Intent.CATEGORY_HOME);
   20526         filter.addCategory(Intent.CATEGORY_DEFAULT);
   20527         return filter;
   20528     }
   20529 
   20530     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
   20531             int userId) {
   20532         Intent intent  = getHomeIntent();
   20533         List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
   20534                 PackageManager.GET_META_DATA, userId);
   20535         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
   20536                 true, false, false, userId);
   20537 
   20538         allHomeCandidates.clear();
   20539         if (list != null) {
   20540             for (ResolveInfo ri : list) {
   20541                 allHomeCandidates.add(ri);
   20542             }
   20543         }
   20544         return (preferred == null || preferred.activityInfo == null)
   20545                 ? null
   20546                 : new ComponentName(preferred.activityInfo.packageName,
   20547                         preferred.activityInfo.name);
   20548     }
   20549 
   20550     @Override
   20551     public void setHomeActivity(ComponentName comp, int userId) {
   20552         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   20553             return;
   20554         }
   20555         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
   20556         getHomeActivitiesAsUser(homeActivities, userId);
   20557 
   20558         boolean found = false;
   20559 
   20560         final int size = homeActivities.size();
   20561         final ComponentName[] set = new ComponentName[size];
   20562         for (int i = 0; i < size; i++) {
   20563             final ResolveInfo candidate = homeActivities.get(i);
   20564             final ActivityInfo info = candidate.activityInfo;
   20565             final ComponentName activityName = new ComponentName(info.packageName, info.name);
   20566             set[i] = activityName;
   20567             if (!found && activityName.equals(comp)) {
   20568                 found = true;
   20569             }
   20570         }
   20571         if (!found) {
   20572             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
   20573                     + userId);
   20574         }
   20575         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
   20576                 set, comp, userId);
   20577     }
   20578 
   20579     private @Nullable String getSetupWizardPackageName() {
   20580         final Intent intent = new Intent(Intent.ACTION_MAIN);
   20581         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
   20582 
   20583         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
   20584                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
   20585                         | MATCH_DISABLED_COMPONENTS,
   20586                 UserHandle.myUserId());
   20587         if (matches.size() == 1) {
   20588             return matches.get(0).getComponentInfo().packageName;
   20589         } else {
   20590             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
   20591                     + ": matches=" + matches);
   20592             return null;
   20593         }
   20594     }
   20595 
   20596     private @Nullable String getStorageManagerPackageName() {
   20597         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
   20598 
   20599         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
   20600                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
   20601                         | MATCH_DISABLED_COMPONENTS,
   20602                 UserHandle.myUserId());
   20603         if (matches.size() == 1) {
   20604             return matches.get(0).getComponentInfo().packageName;
   20605         } else {
   20606             Slog.e(TAG, "There should probably be exactly one storage manager; found "
   20607                     + matches.size() + ": matches=" + matches);
   20608             return null;
   20609         }
   20610     }
   20611 
   20612     @Override
   20613     public String getSystemTextClassifierPackageName() {
   20614         return mContext.getString(R.string.config_defaultTextClassifierPackage);
   20615     }
   20616 
   20617     @Override
   20618     public void setApplicationEnabledSetting(String appPackageName,
   20619             int newState, int flags, int userId, String callingPackage) {
   20620         if (!sUserManager.exists(userId)) return;
   20621         if (callingPackage == null) {
   20622             callingPackage = Integer.toString(Binder.getCallingUid());
   20623         }
   20624         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
   20625     }
   20626 
   20627     @Override
   20628     public void setUpdateAvailable(String packageName, boolean updateAvailable) {
   20629         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
   20630         synchronized (mPackages) {
   20631             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
   20632             if (pkgSetting != null) {
   20633                 pkgSetting.setUpdateAvailable(updateAvailable);
   20634             }
   20635         }
   20636     }
   20637 
   20638     @Override
   20639     public void setComponentEnabledSetting(ComponentName componentName,
   20640             int newState, int flags, int userId) {
   20641         if (!sUserManager.exists(userId)) return;
   20642         setEnabledSetting(componentName.getPackageName(),
   20643                 componentName.getClassName(), newState, flags, userId, null);
   20644     }
   20645 
   20646     private void setEnabledSetting(final String packageName, String className, int newState,
   20647             final int flags, int userId, String callingPackage) {
   20648         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
   20649               || newState == COMPONENT_ENABLED_STATE_ENABLED
   20650               || newState == COMPONENT_ENABLED_STATE_DISABLED
   20651               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
   20652               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
   20653             throw new IllegalArgumentException("Invalid new component state: "
   20654                     + newState);
   20655         }
   20656         PackageSetting pkgSetting;
   20657         final int callingUid = Binder.getCallingUid();
   20658         final int permission;
   20659         if (callingUid == Process.SYSTEM_UID) {
   20660             permission = PackageManager.PERMISSION_GRANTED;
   20661         } else {
   20662             permission = mContext.checkCallingOrSelfPermission(
   20663                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
   20664         }
   20665         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   20666                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
   20667         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
   20668         boolean sendNow = false;
   20669         boolean isApp = (className == null);
   20670         final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
   20671         String componentName = isApp ? packageName : className;
   20672         int packageUid = -1;
   20673         ArrayList<String> components;
   20674 
   20675         // reader
   20676         synchronized (mPackages) {
   20677             pkgSetting = mSettings.mPackages.get(packageName);
   20678             if (pkgSetting == null) {
   20679                 if (!isCallerInstantApp) {
   20680                     if (className == null) {
   20681                         throw new IllegalArgumentException("Unknown package: " + packageName);
   20682                     }
   20683                     throw new IllegalArgumentException(
   20684                             "Unknown component: " + packageName + "/" + className);
   20685                 } else {
   20686                     // throw SecurityException to prevent leaking package information
   20687                     throw new SecurityException(
   20688                             "Attempt to change component state; "
   20689                             + "pid=" + Binder.getCallingPid()
   20690                             + ", uid=" + callingUid
   20691                             + (className == null
   20692                                     ? ", package=" + packageName
   20693                                     : ", component=" + packageName + "/" + className));
   20694                 }
   20695             }
   20696         }
   20697 
   20698         // Limit who can change which apps
   20699         if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
   20700             // Don't allow apps that don't have permission to modify other apps
   20701             if (!allowedByPermission
   20702                     || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
   20703                 throw new SecurityException(
   20704                         "Attempt to change component state; "
   20705                         + "pid=" + Binder.getCallingPid()
   20706                         + ", uid=" + callingUid
   20707                         + (className == null
   20708                                 ? ", package=" + packageName
   20709                                 : ", component=" + packageName + "/" + className));
   20710             }
   20711             // Don't allow changing protected packages.
   20712             if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
   20713                 throw new SecurityException("Cannot disable a protected package: " + packageName);
   20714             }
   20715         }
   20716 
   20717         synchronized (mPackages) {
   20718             if (callingUid == Process.SHELL_UID
   20719                     && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
   20720                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
   20721                 // unless it is a test package.
   20722                 int oldState = pkgSetting.getEnabled(userId);
   20723                 if (className == null
   20724                         &&
   20725                         (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
   20726                                 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
   20727                                 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
   20728                         &&
   20729                         (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
   20730                                 || newState == COMPONENT_ENABLED_STATE_DEFAULT
   20731                                 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
   20732                     // ok
   20733                 } else {
   20734                     throw new SecurityException(
   20735                             "Shell cannot change component state for " + packageName + "/"
   20736                                     + className + " to " + newState);
   20737                 }
   20738             }
   20739         }
   20740         if (className == null) {
   20741             // We're dealing with an application/package level state change
   20742             synchronized (mPackages) {
   20743                 if (pkgSetting.getEnabled(userId) == newState) {
   20744                     // Nothing to do
   20745                     return;
   20746                 }
   20747             }
   20748             // If we're enabling a system stub, there's a little more work to do.
   20749             // Prior to enabling the package, we need to decompress the APK(s) to the
   20750             // data partition and then replace the version on the system partition.
   20751             final PackageParser.Package deletedPkg = pkgSetting.pkg;
   20752             final boolean isSystemStub = deletedPkg.isStub
   20753                     && deletedPkg.isSystem();
   20754             if (isSystemStub
   20755                     && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
   20756                             || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
   20757                 final File codePath = decompressPackage(deletedPkg);
   20758                 if (codePath == null) {
   20759                     Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
   20760                     return;
   20761                 }
   20762                 // TODO remove direct parsing of the package object during internal cleanup
   20763                 // of scan package
   20764                 // We need to call parse directly here for no other reason than we need
   20765                 // the new package in order to disable the old one [we use the information
   20766                 // for some internal optimization to optionally create a new package setting
   20767                 // object on replace]. However, we can't get the package from the scan
   20768                 // because the scan modifies live structures and we need to remove the
   20769                 // old [system] package from the system before a scan can be attempted.
   20770                 // Once scan is indempotent we can remove this parse and use the package
   20771                 // object we scanned, prior to adding it to package settings.
   20772                 final PackageParser pp = new PackageParser();
   20773                 pp.setSeparateProcesses(mSeparateProcesses);
   20774                 pp.setDisplayMetrics(mMetrics);
   20775                 pp.setCallback(mPackageParserCallback);
   20776                 final PackageParser.Package tmpPkg;
   20777                 try {
   20778                     final @ParseFlags int parseFlags = mDefParseFlags
   20779                             | PackageParser.PARSE_MUST_BE_APK
   20780                             | PackageParser.PARSE_IS_SYSTEM_DIR;
   20781                     tmpPkg = pp.parsePackage(codePath, parseFlags);
   20782                 } catch (PackageParserException e) {
   20783                     Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
   20784                     return;
   20785                 }
   20786                 synchronized (mInstallLock) {
   20787                     // Disable the stub and remove any package entries
   20788                     removePackageLI(deletedPkg, true);
   20789                     synchronized (mPackages) {
   20790                         disableSystemPackageLPw(deletedPkg, tmpPkg);
   20791                     }
   20792                     final PackageParser.Package pkg;
   20793                     try (PackageFreezer freezer =
   20794                             freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
   20795                         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
   20796                                 | PackageParser.PARSE_ENFORCE_CODE;
   20797                         pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
   20798                                 0 /*currentTime*/, null /*user*/);
   20799                         prepareAppDataAfterInstallLIF(pkg);
   20800                         synchronized (mPackages) {
   20801                             try {
   20802                                 updateSharedLibrariesLPr(pkg, null);
   20803                             } catch (PackageManagerException e) {
   20804                                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
   20805                             }
   20806                             mPermissionManager.updatePermissions(
   20807                                     pkg.packageName, pkg, true, mPackages.values(),
   20808                                     mPermissionCallback);
   20809                             mSettings.writeLPr();
   20810                         }
   20811                     } catch (PackageManagerException e) {
   20812                         // Whoops! Something went wrong; try to roll back to the stub
   20813                         Slog.w(TAG, "Failed to install compressed system package:"
   20814                                 + pkgSetting.name, e);
   20815                         // Remove the failed install
   20816                         removeCodePathLI(codePath);
   20817 
   20818                         // Install the system package
   20819                         try (PackageFreezer freezer =
   20820                                 freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
   20821                             synchronized (mPackages) {
   20822                                 // NOTE: The system package always needs to be enabled; even
   20823                                 // if it's for a compressed stub. If we don't, installing the
   20824                                 // system package fails during scan [scanning checks the disabled
   20825                                 // packages]. We will reverse this later, after we've "installed"
   20826                                 // the stub.
   20827                                 // This leaves us in a fragile state; the stub should never be
   20828                                 // enabled, so, cross your fingers and hope nothing goes wrong
   20829                                 // until we can disable the package later.
   20830                                 enableSystemPackageLPw(deletedPkg);
   20831                             }
   20832                             installPackageFromSystemLIF(deletedPkg.codePath,
   20833                                     false /*isPrivileged*/, null /*allUserHandles*/,
   20834                                     null /*origUserHandles*/, null /*origPermissionsState*/,
   20835                                     true /*writeSettings*/);
   20836                         } catch (PackageManagerException pme) {
   20837                             Slog.w(TAG, "Failed to restore system package:"
   20838                                     + deletedPkg.packageName, pme);
   20839                         } finally {
   20840                             synchronized (mPackages) {
   20841                                 mSettings.disableSystemPackageLPw(
   20842                                         deletedPkg.packageName, true /*replaced*/);
   20843                                 mSettings.writeLPr();
   20844                             }
   20845                         }
   20846                         return;
   20847                     }
   20848                     clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
   20849                             | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   20850                     mDexManager.notifyPackageUpdated(pkg.packageName,
   20851                             pkg.baseCodePath, pkg.splitCodePaths);
   20852                 }
   20853             }
   20854             if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
   20855                 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
   20856                 // Don't care about who enables an app.
   20857                 callingPackage = null;
   20858             }
   20859             synchronized (mPackages) {
   20860                 pkgSetting.setEnabled(newState, userId, callingPackage);
   20861             }
   20862         } else {
   20863             synchronized (mPackages) {
   20864                 // We're dealing with a component level state change
   20865                 // First, verify that this is a valid class name.
   20866                 PackageParser.Package pkg = pkgSetting.pkg;
   20867                 if (pkg == null || !pkg.hasComponentClassName(className)) {
   20868                     if (pkg != null &&
   20869                             pkg.applicationInfo.targetSdkVersion >=
   20870                                     Build.VERSION_CODES.JELLY_BEAN) {
   20871                         throw new IllegalArgumentException("Component class " + className
   20872                                 + " does not exist in " + packageName);
   20873                     } else {
   20874                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
   20875                                 + className + " does not exist in " + packageName);
   20876                     }
   20877                 }
   20878                 switch (newState) {
   20879                     case COMPONENT_ENABLED_STATE_ENABLED:
   20880                         if (!pkgSetting.enableComponentLPw(className, userId)) {
   20881                             return;
   20882                         }
   20883                         break;
   20884                     case COMPONENT_ENABLED_STATE_DISABLED:
   20885                         if (!pkgSetting.disableComponentLPw(className, userId)) {
   20886                             return;
   20887                         }
   20888                         break;
   20889                     case COMPONENT_ENABLED_STATE_DEFAULT:
   20890                         if (!pkgSetting.restoreComponentLPw(className, userId)) {
   20891                             return;
   20892                         }
   20893                         break;
   20894                     default:
   20895                         Slog.e(TAG, "Invalid new component state: " + newState);
   20896                         return;
   20897                 }
   20898             }
   20899         }
   20900         synchronized (mPackages) {
   20901             scheduleWritePackageRestrictionsLocked(userId);
   20902             updateSequenceNumberLP(pkgSetting, new int[] { userId });
   20903             final long callingId = Binder.clearCallingIdentity();
   20904             try {
   20905                 updateInstantAppInstallerLocked(packageName);
   20906             } finally {
   20907                 Binder.restoreCallingIdentity(callingId);
   20908             }
   20909             components = mPendingBroadcasts.get(userId, packageName);
   20910             final boolean newPackage = components == null;
   20911             if (newPackage) {
   20912                 components = new ArrayList<String>();
   20913             }
   20914             if (!components.contains(componentName)) {
   20915                 components.add(componentName);
   20916             }
   20917             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
   20918                 sendNow = true;
   20919                 // Purge entry from pending broadcast list if another one exists already
   20920                 // since we are sending one right away.
   20921                 mPendingBroadcasts.remove(userId, packageName);
   20922             } else {
   20923                 if (newPackage) {
   20924                     mPendingBroadcasts.put(userId, packageName, components);
   20925                 }
   20926                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
   20927                     // Schedule a message
   20928                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
   20929                 }
   20930             }
   20931         }
   20932 
   20933         long callingId = Binder.clearCallingIdentity();
   20934         try {
   20935             if (sendNow) {
   20936                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
   20937                 sendPackageChangedBroadcast(packageName,
   20938                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
   20939             }
   20940         } finally {
   20941             Binder.restoreCallingIdentity(callingId);
   20942         }
   20943     }
   20944 
   20945     @Override
   20946     public void flushPackageRestrictionsAsUser(int userId) {
   20947         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   20948             return;
   20949         }
   20950         if (!sUserManager.exists(userId)) {
   20951             return;
   20952         }
   20953         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
   20954                 false /* checkShell */, "flushPackageRestrictions");
   20955         synchronized (mPackages) {
   20956             mSettings.writePackageRestrictionsLPr(userId);
   20957             mDirtyUsers.remove(userId);
   20958             if (mDirtyUsers.isEmpty()) {
   20959                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   20960             }
   20961         }
   20962     }
   20963 
   20964     private void sendPackageChangedBroadcast(String packageName,
   20965             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
   20966         if (DEBUG_INSTALL)
   20967             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
   20968                     + componentNames);
   20969         Bundle extras = new Bundle(4);
   20970         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
   20971         String nameList[] = new String[componentNames.size()];
   20972         componentNames.toArray(nameList);
   20973         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
   20974         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
   20975         extras.putInt(Intent.EXTRA_UID, packageUid);
   20976         // If this is not reporting a change of the overall package, then only send it
   20977         // to registered receivers.  We don't want to launch a swath of apps for every
   20978         // little component state change.
   20979         final int flags = !componentNames.contains(packageName)
   20980                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
   20981         final int userId = UserHandle.getUserId(packageUid);
   20982         final boolean isInstantApp = isInstantApp(packageName, userId);
   20983         final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
   20984         final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
   20985         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
   20986                 userIds, instantUserIds);
   20987     }
   20988 
   20989     @Override
   20990     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
   20991         if (!sUserManager.exists(userId)) return;
   20992         final int callingUid = Binder.getCallingUid();
   20993         if (getInstantAppPackageName(callingUid) != null) {
   20994             return;
   20995         }
   20996         final int permission = mContext.checkCallingOrSelfPermission(
   20997                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
   20998         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
   20999         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   21000                 true /* requireFullPermission */, true /* checkShell */, "stop package");
   21001         // writer
   21002         synchronized (mPackages) {
   21003             final PackageSetting ps = mSettings.mPackages.get(packageName);
   21004             if (!filterAppAccessLPr(ps, callingUid, userId)
   21005                     && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
   21006                             allowedByPermission, callingUid, userId)) {
   21007                 scheduleWritePackageRestrictionsLocked(userId);
   21008             }
   21009         }
   21010     }
   21011 
   21012     @Override
   21013     public String getInstallerPackageName(String packageName) {
   21014         final int callingUid = Binder.getCallingUid();
   21015         synchronized (mPackages) {
   21016             final PackageSetting ps = mSettings.mPackages.get(packageName);
   21017             if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
   21018                 return null;
   21019             }
   21020             return mSettings.getInstallerPackageNameLPr(packageName);
   21021         }
   21022     }
   21023 
   21024     public boolean isOrphaned(String packageName) {
   21025         // reader
   21026         synchronized (mPackages) {
   21027             return mSettings.isOrphaned(packageName);
   21028         }
   21029     }
   21030 
   21031     @Override
   21032     public int getApplicationEnabledSetting(String packageName, int userId) {
   21033         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
   21034         int callingUid = Binder.getCallingUid();
   21035         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   21036                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
   21037         // reader
   21038         synchronized (mPackages) {
   21039             if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
   21040                 return COMPONENT_ENABLED_STATE_DISABLED;
   21041             }
   21042             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
   21043         }
   21044     }
   21045 
   21046     @Override
   21047     public int getComponentEnabledSetting(ComponentName component, int userId) {
   21048         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
   21049         int callingUid = Binder.getCallingUid();
   21050         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   21051                 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
   21052         synchronized (mPackages) {
   21053             if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
   21054                     component, TYPE_UNKNOWN, userId)) {
   21055                 return COMPONENT_ENABLED_STATE_DISABLED;
   21056             }
   21057             return mSettings.getComponentEnabledSettingLPr(component, userId);
   21058         }
   21059     }
   21060 
   21061     @Override
   21062     public void enterSafeMode() {
   21063         enforceSystemOrRoot("Only the system can request entering safe mode");
   21064 
   21065         if (!mSystemReady) {
   21066             mSafeMode = true;
   21067         }
   21068     }
   21069 
   21070     @Override
   21071     public void systemReady() {
   21072         enforceSystemOrRoot("Only the system can claim the system is ready");
   21073 
   21074         mSystemReady = true;
   21075         final ContentResolver resolver = mContext.getContentResolver();
   21076         ContentObserver co = new ContentObserver(mHandler) {
   21077             @Override
   21078             public void onChange(boolean selfChange) {
   21079                 mWebInstantAppsDisabled =
   21080                         (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
   21081                                 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
   21082             }
   21083         };
   21084         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
   21085                         .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
   21086                 false, co, UserHandle.USER_SYSTEM);
   21087         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
   21088                         .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
   21089         co.onChange(true);
   21090 
   21091         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
   21092         // disabled after already being started.
   21093         CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
   21094                 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
   21095 
   21096         // Read the compatibilty setting when the system is ready.
   21097         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
   21098                 mContext.getContentResolver(),
   21099                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
   21100         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
   21101         if (DEBUG_SETTINGS) {
   21102             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
   21103         }
   21104 
   21105         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
   21106 
   21107         synchronized (mPackages) {
   21108             // Verify that all of the preferred activity components actually
   21109             // exist.  It is possible for applications to be updated and at
   21110             // that point remove a previously declared activity component that
   21111             // had been set as a preferred activity.  We try to clean this up
   21112             // the next time we encounter that preferred activity, but it is
   21113             // possible for the user flow to never be able to return to that
   21114             // situation so here we do a sanity check to make sure we haven't
   21115             // left any junk around.
   21116             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
   21117             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
   21118                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
   21119                 removed.clear();
   21120                 for (PreferredActivity pa : pir.filterSet()) {
   21121                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
   21122                         removed.add(pa);
   21123                     }
   21124                 }
   21125                 if (removed.size() > 0) {
   21126                     for (int r=0; r<removed.size(); r++) {
   21127                         PreferredActivity pa = removed.get(r);
   21128                         Slog.w(TAG, "Removing dangling preferred activity: "
   21129                                 + pa.mPref.mComponent);
   21130                         pir.removeFilter(pa);
   21131                     }
   21132                     mSettings.writePackageRestrictionsLPr(
   21133                             mSettings.mPreferredActivities.keyAt(i));
   21134                 }
   21135             }
   21136 
   21137             for (int userId : UserManagerService.getInstance().getUserIds()) {
   21138                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
   21139                     grantPermissionsUserIds = ArrayUtils.appendInt(
   21140                             grantPermissionsUserIds, userId);
   21141                 }
   21142             }
   21143         }
   21144         sUserManager.systemReady();
   21145         // If we upgraded grant all default permissions before kicking off.
   21146         for (int userId : grantPermissionsUserIds) {
   21147             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
   21148         }
   21149 
   21150         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
   21151             // If we did not grant default permissions, we preload from this the
   21152             // default permission exceptions lazily to ensure we don't hit the
   21153             // disk on a new user creation.
   21154             mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
   21155         }
   21156 
   21157         // Now that we've scanned all packages, and granted any default
   21158         // permissions, ensure permissions are updated. Beware of dragons if you
   21159         // try optimizing this.
   21160         synchronized (mPackages) {
   21161             mPermissionManager.updateAllPermissions(
   21162                     StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
   21163                     mPermissionCallback);
   21164         }
   21165 
   21166         // Kick off any messages waiting for system ready
   21167         if (mPostSystemReadyMessages != null) {
   21168             for (Message msg : mPostSystemReadyMessages) {
   21169                 msg.sendToTarget();
   21170             }
   21171             mPostSystemReadyMessages = null;
   21172         }
   21173 
   21174         // Watch for external volumes that come and go over time
   21175         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   21176         storage.registerListener(mStorageListener);
   21177 
   21178         mInstallerService.systemReady();
   21179         mDexManager.systemReady();
   21180         mPackageDexOptimizer.systemReady();
   21181 
   21182         StorageManagerInternal StorageManagerInternal = LocalServices.getService(
   21183                 StorageManagerInternal.class);
   21184         StorageManagerInternal.addExternalStoragePolicy(
   21185                 new StorageManagerInternal.ExternalStorageMountPolicy() {
   21186             @Override
   21187             public int getMountMode(int uid, String packageName) {
   21188                 if (Process.isIsolated(uid)) {
   21189                     return Zygote.MOUNT_EXTERNAL_NONE;
   21190                 }
   21191                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
   21192                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
   21193                 }
   21194                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
   21195                     return Zygote.MOUNT_EXTERNAL_READ;
   21196                 }
   21197                 return Zygote.MOUNT_EXTERNAL_WRITE;
   21198             }
   21199 
   21200             @Override
   21201             public boolean hasExternalStorage(int uid, String packageName) {
   21202                 return true;
   21203             }
   21204         });
   21205 
   21206         // Now that we're mostly running, clean up stale users and apps
   21207         sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
   21208         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
   21209 
   21210         mPermissionManager.systemReady();
   21211 
   21212         if (mInstantAppResolverConnection != null) {
   21213             mContext.registerReceiver(new BroadcastReceiver() {
   21214                 @Override
   21215                 public void onReceive(Context context, Intent intent) {
   21216                     mInstantAppResolverConnection.optimisticBind();
   21217                     mContext.unregisterReceiver(this);
   21218                 }
   21219             }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
   21220         }
   21221     }
   21222 
   21223     public void waitForAppDataPrepared() {
   21224         if (mPrepareAppDataFuture == null) {
   21225             return;
   21226         }
   21227         ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
   21228         mPrepareAppDataFuture = null;
   21229     }
   21230 
   21231     @Override
   21232     public boolean isSafeMode() {
   21233         // allow instant applications
   21234         return mSafeMode;
   21235     }
   21236 
   21237     @Override
   21238     public boolean hasSystemUidErrors() {
   21239         // allow instant applications
   21240         return mHasSystemUidErrors;
   21241     }
   21242 
   21243     static String arrayToString(int[] array) {
   21244         StringBuffer buf = new StringBuffer(128);
   21245         buf.append('[');
   21246         if (array != null) {
   21247             for (int i=0; i<array.length; i++) {
   21248                 if (i > 0) buf.append(", ");
   21249                 buf.append(array[i]);
   21250             }
   21251         }
   21252         buf.append(']');
   21253         return buf.toString();
   21254     }
   21255 
   21256     @Override
   21257     public void onShellCommand(FileDescriptor in, FileDescriptor out,
   21258             FileDescriptor err, String[] args, ShellCallback callback,
   21259             ResultReceiver resultReceiver) {
   21260         (new PackageManagerShellCommand(this)).exec(
   21261                 this, in, out, err, args, callback, resultReceiver);
   21262     }
   21263 
   21264     @Override
   21265     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   21266         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
   21267 
   21268         DumpState dumpState = new DumpState();
   21269         boolean fullPreferred = false;
   21270         boolean checkin = false;
   21271 
   21272         String packageName = null;
   21273         ArraySet<String> permissionNames = null;
   21274 
   21275         int opti = 0;
   21276         while (opti < args.length) {
   21277             String opt = args[opti];
   21278             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
   21279                 break;
   21280             }
   21281             opti++;
   21282 
   21283             if ("-a".equals(opt)) {
   21284                 // Right now we only know how to print all.
   21285             } else if ("-h".equals(opt)) {
   21286                 pw.println("Package manager dump options:");
   21287                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
   21288                 pw.println("    --checkin: dump for a checkin");
   21289                 pw.println("    -f: print details of intent filters");
   21290                 pw.println("    -h: print this help");
   21291                 pw.println("  cmd may be one of:");
   21292                 pw.println("    l[ibraries]: list known shared libraries");
   21293                 pw.println("    f[eatures]: list device features");
   21294                 pw.println("    k[eysets]: print known keysets");
   21295                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
   21296                 pw.println("    perm[issions]: dump permissions");
   21297                 pw.println("    permission [name ...]: dump declaration and use of given permission");
   21298                 pw.println("    pref[erred]: print preferred package settings");
   21299                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
   21300                 pw.println("    prov[iders]: dump content providers");
   21301                 pw.println("    p[ackages]: dump installed packages");
   21302                 pw.println("    s[hared-users]: dump shared user IDs");
   21303                 pw.println("    m[essages]: print collected runtime messages");
   21304                 pw.println("    v[erifiers]: print package verifier info");
   21305                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
   21306                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
   21307                 pw.println("    version: print database version info");
   21308                 pw.println("    write: write current settings now");
   21309                 pw.println("    installs: details about install sessions");
   21310                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
   21311                 pw.println("    dexopt: dump dexopt state");
   21312                 pw.println("    compiler-stats: dump compiler statistics");
   21313                 pw.println("    service-permissions: dump permissions required by services");
   21314                 pw.println("    <package.name>: info about given package");
   21315                 return;
   21316             } else if ("--checkin".equals(opt)) {
   21317                 checkin = true;
   21318             } else if ("-f".equals(opt)) {
   21319                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
   21320             } else if ("--proto".equals(opt)) {
   21321                 dumpProto(fd);
   21322                 return;
   21323             } else {
   21324                 pw.println("Unknown argument: " + opt + "; use -h for help");
   21325             }
   21326         }
   21327 
   21328         // Is the caller requesting to dump a particular piece of data?
   21329         if (opti < args.length) {
   21330             String cmd = args[opti];
   21331             opti++;
   21332             // Is this a package name?
   21333             if ("android".equals(cmd) || cmd.contains(".")) {
   21334                 packageName = cmd;
   21335                 // When dumping a single package, we always dump all of its
   21336                 // filter information since the amount of data will be reasonable.
   21337                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
   21338             } else if ("check-permission".equals(cmd)) {
   21339                 if (opti >= args.length) {
   21340                     pw.println("Error: check-permission missing permission argument");
   21341                     return;
   21342                 }
   21343                 String perm = args[opti];
   21344                 opti++;
   21345                 if (opti >= args.length) {
   21346                     pw.println("Error: check-permission missing package argument");
   21347                     return;
   21348                 }
   21349 
   21350                 String pkg = args[opti];
   21351                 opti++;
   21352                 int user = UserHandle.getUserId(Binder.getCallingUid());
   21353                 if (opti < args.length) {
   21354                     try {
   21355                         user = Integer.parseInt(args[opti]);
   21356                     } catch (NumberFormatException e) {
   21357                         pw.println("Error: check-permission user argument is not a number: "
   21358                                 + args[opti]);
   21359                         return;
   21360                     }
   21361                 }
   21362 
   21363                 // Normalize package name to handle renamed packages and static libs
   21364                 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
   21365 
   21366                 pw.println(checkPermission(perm, pkg, user));
   21367                 return;
   21368             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
   21369                 dumpState.setDump(DumpState.DUMP_LIBS);
   21370             } else if ("f".equals(cmd) || "features".equals(cmd)) {
   21371                 dumpState.setDump(DumpState.DUMP_FEATURES);
   21372             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
   21373                 if (opti >= args.length) {
   21374                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
   21375                             | DumpState.DUMP_SERVICE_RESOLVERS
   21376                             | DumpState.DUMP_RECEIVER_RESOLVERS
   21377                             | DumpState.DUMP_CONTENT_RESOLVERS);
   21378                 } else {
   21379                     while (opti < args.length) {
   21380                         String name = args[opti];
   21381                         if ("a".equals(name) || "activity".equals(name)) {
   21382                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
   21383                         } else if ("s".equals(name) || "service".equals(name)) {
   21384                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
   21385                         } else if ("r".equals(name) || "receiver".equals(name)) {
   21386                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
   21387                         } else if ("c".equals(name) || "content".equals(name)) {
   21388                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
   21389                         } else {
   21390                             pw.println("Error: unknown resolver table type: " + name);
   21391                             return;
   21392                         }
   21393                         opti++;
   21394                     }
   21395                 }
   21396             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
   21397                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
   21398             } else if ("permission".equals(cmd)) {
   21399                 if (opti >= args.length) {
   21400                     pw.println("Error: permission requires permission name");
   21401                     return;
   21402                 }
   21403                 permissionNames = new ArraySet<>();
   21404                 while (opti < args.length) {
   21405                     permissionNames.add(args[opti]);
   21406                     opti++;
   21407                 }
   21408                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
   21409                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
   21410             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
   21411                 dumpState.setDump(DumpState.DUMP_PREFERRED);
   21412             } else if ("preferred-xml".equals(cmd)) {
   21413                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
   21414                 if (opti < args.length && "--full".equals(args[opti])) {
   21415                     fullPreferred = true;
   21416                     opti++;
   21417                 }
   21418             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
   21419                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
   21420             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
   21421                 dumpState.setDump(DumpState.DUMP_PACKAGES);
   21422             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
   21423                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
   21424             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
   21425                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
   21426             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
   21427                 dumpState.setDump(DumpState.DUMP_MESSAGES);
   21428             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
   21429                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
   21430             } else if ("i".equals(cmd) || "ifv".equals(cmd)
   21431                     || "intent-filter-verifiers".equals(cmd)) {
   21432                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
   21433             } else if ("version".equals(cmd)) {
   21434                 dumpState.setDump(DumpState.DUMP_VERSION);
   21435             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
   21436                 dumpState.setDump(DumpState.DUMP_KEYSETS);
   21437             } else if ("installs".equals(cmd)) {
   21438                 dumpState.setDump(DumpState.DUMP_INSTALLS);
   21439             } else if ("frozen".equals(cmd)) {
   21440                 dumpState.setDump(DumpState.DUMP_FROZEN);
   21441             } else if ("volumes".equals(cmd)) {
   21442                 dumpState.setDump(DumpState.DUMP_VOLUMES);
   21443             } else if ("dexopt".equals(cmd)) {
   21444                 dumpState.setDump(DumpState.DUMP_DEXOPT);
   21445             } else if ("compiler-stats".equals(cmd)) {
   21446                 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
   21447             } else if ("changes".equals(cmd)) {
   21448                 dumpState.setDump(DumpState.DUMP_CHANGES);
   21449             } else if ("service-permissions".equals(cmd)) {
   21450                 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
   21451             } else if ("write".equals(cmd)) {
   21452                 synchronized (mPackages) {
   21453                     mSettings.writeLPr();
   21454                     pw.println("Settings written.");
   21455                     return;
   21456                 }
   21457             }
   21458         }
   21459 
   21460         if (checkin) {
   21461             pw.println("vers,1");
   21462         }
   21463 
   21464         // reader
   21465         synchronized (mPackages) {
   21466             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
   21467                 if (!checkin) {
   21468                     if (dumpState.onTitlePrinted())
   21469                         pw.println();
   21470                     pw.println("Database versions:");
   21471                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
   21472                 }
   21473             }
   21474 
   21475             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
   21476                 if (!checkin) {
   21477                     if (dumpState.onTitlePrinted())
   21478                         pw.println();
   21479                     pw.println("Verifiers:");
   21480                     pw.print("  Required: ");
   21481                     pw.print(mRequiredVerifierPackage);
   21482                     pw.print(" (uid=");
   21483                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
   21484                             UserHandle.USER_SYSTEM));
   21485                     pw.println(")");
   21486                 } else if (mRequiredVerifierPackage != null) {
   21487                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
   21488                     pw.print(",");
   21489                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
   21490                             UserHandle.USER_SYSTEM));
   21491                 }
   21492             }
   21493 
   21494             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
   21495                     packageName == null) {
   21496                 if (mIntentFilterVerifierComponent != null) {
   21497                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
   21498                     if (!checkin) {
   21499                         if (dumpState.onTitlePrinted())
   21500                             pw.println();
   21501                         pw.println("Intent Filter Verifier:");
   21502                         pw.print("  Using: ");
   21503                         pw.print(verifierPackageName);
   21504                         pw.print(" (uid=");
   21505                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
   21506                                 UserHandle.USER_SYSTEM));
   21507                         pw.println(")");
   21508                     } else if (verifierPackageName != null) {
   21509                         pw.print("ifv,"); pw.print(verifierPackageName);
   21510                         pw.print(",");
   21511                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
   21512                                 UserHandle.USER_SYSTEM));
   21513                     }
   21514                 } else {
   21515                     pw.println();
   21516                     pw.println("No Intent Filter Verifier available!");
   21517                 }
   21518             }
   21519 
   21520             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
   21521                 boolean printedHeader = false;
   21522                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
   21523                 while (it.hasNext()) {
   21524                     String libName = it.next();
   21525                     LongSparseArray<SharedLibraryEntry> versionedLib
   21526                             = mSharedLibraries.get(libName);
   21527                     if (versionedLib == null) {
   21528                         continue;
   21529                     }
   21530                     final int versionCount = versionedLib.size();
   21531                     for (int i = 0; i < versionCount; i++) {
   21532                         SharedLibraryEntry libEntry = versionedLib.valueAt(i);
   21533                         if (!checkin) {
   21534                             if (!printedHeader) {
   21535                                 if (dumpState.onTitlePrinted())
   21536                                     pw.println();
   21537                                 pw.println("Libraries:");
   21538                                 printedHeader = true;
   21539                             }
   21540                             pw.print("  ");
   21541                         } else {
   21542                             pw.print("lib,");
   21543                         }
   21544                         pw.print(libEntry.info.getName());
   21545                         if (libEntry.info.isStatic()) {
   21546                             pw.print(" version=" + libEntry.info.getLongVersion());
   21547                         }
   21548                         if (!checkin) {
   21549                             pw.print(" -> ");
   21550                         }
   21551                         if (libEntry.path != null) {
   21552                             pw.print(" (jar) ");
   21553                             pw.print(libEntry.path);
   21554                         } else {
   21555                             pw.print(" (apk) ");
   21556                             pw.print(libEntry.apk);
   21557                         }
   21558                         pw.println();
   21559                     }
   21560                 }
   21561             }
   21562 
   21563             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
   21564                 if (dumpState.onTitlePrinted())
   21565                     pw.println();
   21566                 if (!checkin) {
   21567                     pw.println("Features:");
   21568                 }
   21569 
   21570                 synchronized (mAvailableFeatures) {
   21571                     for (FeatureInfo feat : mAvailableFeatures.values()) {
   21572                         if (checkin) {
   21573                             pw.print("feat,");
   21574                             pw.print(feat.name);
   21575                             pw.print(",");
   21576                             pw.println(feat.version);
   21577                         } else {
   21578                             pw.print("  ");
   21579                             pw.print(feat.name);
   21580                             if (feat.version > 0) {
   21581                                 pw.print(" version=");
   21582                                 pw.print(feat.version);
   21583                             }
   21584                             pw.println();
   21585                         }
   21586                     }
   21587                 }
   21588             }
   21589 
   21590             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
   21591                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
   21592                         : "Activity Resolver Table:", "  ", packageName,
   21593                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
   21594                     dumpState.setTitlePrinted(true);
   21595                 }
   21596             }
   21597             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
   21598                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
   21599                         : "Receiver Resolver Table:", "  ", packageName,
   21600                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
   21601                     dumpState.setTitlePrinted(true);
   21602                 }
   21603             }
   21604             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
   21605                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
   21606                         : "Service Resolver Table:", "  ", packageName,
   21607                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
   21608                     dumpState.setTitlePrinted(true);
   21609                 }
   21610             }
   21611             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
   21612                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
   21613                         : "Provider Resolver Table:", "  ", packageName,
   21614                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
   21615                     dumpState.setTitlePrinted(true);
   21616                 }
   21617             }
   21618 
   21619             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
   21620                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
   21621                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
   21622                     int user = mSettings.mPreferredActivities.keyAt(i);
   21623                     if (pir.dump(pw,
   21624                             dumpState.getTitlePrinted()
   21625                                 ? "\nPreferred Activities User " + user + ":"
   21626                                 : "Preferred Activities User " + user + ":", "  ",
   21627                             packageName, true, false)) {
   21628                         dumpState.setTitlePrinted(true);
   21629                     }
   21630                 }
   21631             }
   21632 
   21633             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
   21634                 pw.flush();
   21635                 FileOutputStream fout = new FileOutputStream(fd);
   21636                 BufferedOutputStream str = new BufferedOutputStream(fout);
   21637                 XmlSerializer serializer = new FastXmlSerializer();
   21638                 try {
   21639                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
   21640                     serializer.startDocument(null, true);
   21641                     serializer.setFeature(
   21642                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
   21643                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
   21644                     serializer.endDocument();
   21645                     serializer.flush();
   21646                 } catch (IllegalArgumentException e) {
   21647                     pw.println("Failed writing: " + e);
   21648                 } catch (IllegalStateException e) {
   21649                     pw.println("Failed writing: " + e);
   21650                 } catch (IOException e) {
   21651                     pw.println("Failed writing: " + e);
   21652                 }
   21653             }
   21654 
   21655             if (!checkin
   21656                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
   21657                     && packageName == null) {
   21658                 pw.println();
   21659                 int count = mSettings.mPackages.size();
   21660                 if (count == 0) {
   21661                     pw.println("No applications!");
   21662                     pw.println();
   21663                 } else {
   21664                     final String prefix = "  ";
   21665                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
   21666                     if (allPackageSettings.size() == 0) {
   21667                         pw.println("No domain preferred apps!");
   21668                         pw.println();
   21669                     } else {
   21670                         pw.println("App verification status:");
   21671                         pw.println();
   21672                         count = 0;
   21673                         for (PackageSetting ps : allPackageSettings) {
   21674                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
   21675                             if (ivi == null || ivi.getPackageName() == null) continue;
   21676                             pw.println(prefix + "Package: " + ivi.getPackageName());
   21677                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
   21678                             pw.println(prefix + "Status:  " + ivi.getStatusString());
   21679                             pw.println();
   21680                             count++;
   21681                         }
   21682                         if (count == 0) {
   21683                             pw.println(prefix + "No app verification established.");
   21684                             pw.println();
   21685                         }
   21686                         for (int userId : sUserManager.getUserIds()) {
   21687                             pw.println("App linkages for user " + userId + ":");
   21688                             pw.println();
   21689                             count = 0;
   21690                             for (PackageSetting ps : allPackageSettings) {
   21691                                 final long status = ps.getDomainVerificationStatusForUser(userId);
   21692                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
   21693                                         && !DEBUG_DOMAIN_VERIFICATION) {
   21694                                     continue;
   21695                                 }
   21696                                 pw.println(prefix + "Package: " + ps.name);
   21697                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
   21698                                 String statusStr = IntentFilterVerificationInfo.
   21699                                         getStatusStringFromValue(status);
   21700                                 pw.println(prefix + "Status:  " + statusStr);
   21701                                 pw.println();
   21702                                 count++;
   21703                             }
   21704                             if (count == 0) {
   21705                                 pw.println(prefix + "No configured app linkages.");
   21706                                 pw.println();
   21707                             }
   21708                         }
   21709                     }
   21710                 }
   21711             }
   21712 
   21713             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
   21714                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
   21715             }
   21716 
   21717             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
   21718                 boolean printedSomething = false;
   21719                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
   21720                     if (packageName != null && !packageName.equals(p.info.packageName)) {
   21721                         continue;
   21722                     }
   21723                     if (!printedSomething) {
   21724                         if (dumpState.onTitlePrinted())
   21725                             pw.println();
   21726                         pw.println("Registered ContentProviders:");
   21727                         printedSomething = true;
   21728                     }
   21729                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
   21730                     pw.print("    "); pw.println(p.toString());
   21731                 }
   21732                 printedSomething = false;
   21733                 for (Map.Entry<String, PackageParser.Provider> entry :
   21734                         mProvidersByAuthority.entrySet()) {
   21735                     PackageParser.Provider p = entry.getValue();
   21736                     if (packageName != null && !packageName.equals(p.info.packageName)) {
   21737                         continue;
   21738                     }
   21739                     if (!printedSomething) {
   21740                         if (dumpState.onTitlePrinted())
   21741                             pw.println();
   21742                         pw.println("ContentProvider Authorities:");
   21743                         printedSomething = true;
   21744                     }
   21745                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
   21746                     pw.print("    "); pw.println(p.toString());
   21747                     if (p.info != null && p.info.applicationInfo != null) {
   21748                         final String appInfo = p.info.applicationInfo.toString();
   21749                         pw.print("      applicationInfo="); pw.println(appInfo);
   21750                     }
   21751                 }
   21752             }
   21753 
   21754             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
   21755                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
   21756             }
   21757 
   21758             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
   21759                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
   21760             }
   21761 
   21762             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
   21763                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
   21764             }
   21765 
   21766             if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
   21767                 if (dumpState.onTitlePrinted()) pw.println();
   21768                 pw.println("Package Changes:");
   21769                 pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
   21770                 final int K = mChangedPackages.size();
   21771                 for (int i = 0; i < K; i++) {
   21772                     final SparseArray<String> changes = mChangedPackages.valueAt(i);
   21773                     pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
   21774                     final int N = changes.size();
   21775                     if (N == 0) {
   21776                         pw.print("    "); pw.println("No packages changed");
   21777                     } else {
   21778                         for (int j = 0; j < N; j++) {
   21779                             final String pkgName = changes.valueAt(j);
   21780                             final int sequenceNumber = changes.keyAt(j);
   21781                             pw.print("    ");
   21782                             pw.print("seq=");
   21783                             pw.print(sequenceNumber);
   21784                             pw.print(", package=");
   21785                             pw.println(pkgName);
   21786                         }
   21787                     }
   21788                 }
   21789             }
   21790 
   21791             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
   21792                 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
   21793             }
   21794 
   21795             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
   21796                 // XXX should handle packageName != null by dumping only install data that
   21797                 // the given package is involved with.
   21798                 if (dumpState.onTitlePrinted()) pw.println();
   21799 
   21800                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
   21801                 ipw.println();
   21802                 ipw.println("Frozen packages:");
   21803                 ipw.increaseIndent();
   21804                 if (mFrozenPackages.size() == 0) {
   21805                     ipw.println("(none)");
   21806                 } else {
   21807                     for (int i = 0; i < mFrozenPackages.size(); i++) {
   21808                         ipw.println(mFrozenPackages.valueAt(i));
   21809                     }
   21810                 }
   21811                 ipw.decreaseIndent();
   21812             }
   21813 
   21814             if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
   21815                 if (dumpState.onTitlePrinted()) pw.println();
   21816 
   21817                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
   21818                 ipw.println();
   21819                 ipw.println("Loaded volumes:");
   21820                 ipw.increaseIndent();
   21821                 if (mLoadedVolumes.size() == 0) {
   21822                     ipw.println("(none)");
   21823                 } else {
   21824                     for (int i = 0; i < mLoadedVolumes.size(); i++) {
   21825                         ipw.println(mLoadedVolumes.valueAt(i));
   21826                     }
   21827                 }
   21828                 ipw.decreaseIndent();
   21829             }
   21830 
   21831             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
   21832                     && packageName == null) {
   21833                 if (dumpState.onTitlePrinted()) pw.println();
   21834                 pw.println("Service permissions:");
   21835 
   21836                 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
   21837                 while (filterIterator.hasNext()) {
   21838                     final ServiceIntentInfo info = filterIterator.next();
   21839                     final ServiceInfo serviceInfo = info.service.info;
   21840                     final String permission = serviceInfo.permission;
   21841                     if (permission != null) {
   21842                         pw.print("    ");
   21843                         pw.print(serviceInfo.getComponentName().flattenToShortString());
   21844                         pw.print(": ");
   21845                         pw.println(permission);
   21846                     }
   21847                 }
   21848             }
   21849 
   21850             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
   21851                 if (dumpState.onTitlePrinted()) pw.println();
   21852                 dumpDexoptStateLPr(pw, packageName);
   21853             }
   21854 
   21855             if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
   21856                 if (dumpState.onTitlePrinted()) pw.println();
   21857                 dumpCompilerStatsLPr(pw, packageName);
   21858             }
   21859 
   21860             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
   21861                 if (dumpState.onTitlePrinted()) pw.println();
   21862                 mSettings.dumpReadMessagesLPr(pw, dumpState);
   21863 
   21864                 pw.println();
   21865                 pw.println("Package warning messages:");
   21866                 dumpCriticalInfo(pw, null);
   21867             }
   21868 
   21869             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
   21870                 dumpCriticalInfo(pw, "msg,");
   21871             }
   21872         }
   21873 
   21874         // PackageInstaller should be called outside of mPackages lock
   21875         if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
   21876             // XXX should handle packageName != null by dumping only install data that
   21877             // the given package is involved with.
   21878             if (dumpState.onTitlePrinted()) pw.println();
   21879             mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
   21880         }
   21881     }
   21882 
   21883     private void dumpProto(FileDescriptor fd) {
   21884         final ProtoOutputStream proto = new ProtoOutputStream(fd);
   21885 
   21886         synchronized (mPackages) {
   21887             final long requiredVerifierPackageToken =
   21888                     proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
   21889             proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
   21890             proto.write(
   21891                     PackageServiceDumpProto.PackageShortProto.UID,
   21892                     getPackageUid(
   21893                             mRequiredVerifierPackage,
   21894                             MATCH_DEBUG_TRIAGED_MISSING,
   21895                             UserHandle.USER_SYSTEM));
   21896             proto.end(requiredVerifierPackageToken);
   21897 
   21898             if (mIntentFilterVerifierComponent != null) {
   21899                 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
   21900                 final long verifierPackageToken =
   21901                         proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
   21902                 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
   21903                 proto.write(
   21904                         PackageServiceDumpProto.PackageShortProto.UID,
   21905                         getPackageUid(
   21906                                 verifierPackageName,
   21907                                 MATCH_DEBUG_TRIAGED_MISSING,
   21908                                 UserHandle.USER_SYSTEM));
   21909                 proto.end(verifierPackageToken);
   21910             }
   21911 
   21912             dumpSharedLibrariesProto(proto);
   21913             dumpFeaturesProto(proto);
   21914             mSettings.dumpPackagesProto(proto);
   21915             mSettings.dumpSharedUsersProto(proto);
   21916             dumpCriticalInfo(proto);
   21917         }
   21918         proto.flush();
   21919     }
   21920 
   21921     private void dumpFeaturesProto(ProtoOutputStream proto) {
   21922         synchronized (mAvailableFeatures) {
   21923             final int count = mAvailableFeatures.size();
   21924             for (int i = 0; i < count; i++) {
   21925                 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
   21926             }
   21927         }
   21928     }
   21929 
   21930     private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
   21931         final int count = mSharedLibraries.size();
   21932         for (int i = 0; i < count; i++) {
   21933             final String libName = mSharedLibraries.keyAt(i);
   21934             LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
   21935             if (versionedLib == null) {
   21936                 continue;
   21937             }
   21938             final int versionCount = versionedLib.size();
   21939             for (int j = 0; j < versionCount; j++) {
   21940                 final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
   21941                 final long sharedLibraryToken =
   21942                         proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
   21943                 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
   21944                 final boolean isJar = (libEntry.path != null);
   21945                 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
   21946                 if (isJar) {
   21947                     proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
   21948                 } else {
   21949                     proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
   21950                 }
   21951                 proto.end(sharedLibraryToken);
   21952             }
   21953         }
   21954     }
   21955 
   21956     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
   21957         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
   21958         ipw.println();
   21959         ipw.println("Dexopt state:");
   21960         ipw.increaseIndent();
   21961         Collection<PackageParser.Package> packages = null;
   21962         if (packageName != null) {
   21963             PackageParser.Package targetPackage = mPackages.get(packageName);
   21964             if (targetPackage != null) {
   21965                 packages = Collections.singletonList(targetPackage);
   21966             } else {
   21967                 ipw.println("Unable to find package: " + packageName);
   21968                 return;
   21969             }
   21970         } else {
   21971             packages = mPackages.values();
   21972         }
   21973 
   21974         for (PackageParser.Package pkg : packages) {
   21975             ipw.println("[" + pkg.packageName + "]");
   21976             ipw.increaseIndent();
   21977             mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
   21978                     mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
   21979             ipw.decreaseIndent();
   21980         }
   21981     }
   21982 
   21983     private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
   21984         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
   21985         ipw.println();
   21986         ipw.println("Compiler stats:");
   21987         ipw.increaseIndent();
   21988         Collection<PackageParser.Package> packages = null;
   21989         if (packageName != null) {
   21990             PackageParser.Package targetPackage = mPackages.get(packageName);
   21991             if (targetPackage != null) {
   21992                 packages = Collections.singletonList(targetPackage);
   21993             } else {
   21994                 ipw.println("Unable to find package: " + packageName);
   21995                 return;
   21996             }
   21997         } else {
   21998             packages = mPackages.values();
   21999         }
   22000 
   22001         for (PackageParser.Package pkg : packages) {
   22002             ipw.println("[" + pkg.packageName + "]");
   22003             ipw.increaseIndent();
   22004 
   22005             CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
   22006             if (stats == null) {
   22007                 ipw.println("(No recorded stats)");
   22008             } else {
   22009                 stats.dump(ipw);
   22010             }
   22011             ipw.decreaseIndent();
   22012         }
   22013     }
   22014 
   22015     private String dumpDomainString(String packageName) {
   22016         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
   22017                 .getList();
   22018         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
   22019 
   22020         ArraySet<String> result = new ArraySet<>();
   22021         if (iviList.size() > 0) {
   22022             for (IntentFilterVerificationInfo ivi : iviList) {
   22023                 for (String host : ivi.getDomains()) {
   22024                     result.add(host);
   22025                 }
   22026             }
   22027         }
   22028         if (filters != null && filters.size() > 0) {
   22029             for (IntentFilter filter : filters) {
   22030                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
   22031                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
   22032                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
   22033                     result.addAll(filter.getHostsList());
   22034                 }
   22035             }
   22036         }
   22037 
   22038         StringBuilder sb = new StringBuilder(result.size() * 16);
   22039         for (String domain : result) {
   22040             if (sb.length() > 0) sb.append(" ");
   22041             sb.append(domain);
   22042         }
   22043         return sb.toString();
   22044     }
   22045 
   22046     // ------- apps on sdcard specific code -------
   22047     static final boolean DEBUG_SD_INSTALL = false;
   22048 
   22049     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
   22050 
   22051     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
   22052 
   22053     private boolean mMediaMounted = false;
   22054 
   22055     static String getEncryptKey() {
   22056         try {
   22057             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
   22058                     SD_ENCRYPTION_KEYSTORE_NAME);
   22059             if (sdEncKey == null) {
   22060                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
   22061                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
   22062                 if (sdEncKey == null) {
   22063                     Slog.e(TAG, "Failed to create encryption keys");
   22064                     return null;
   22065                 }
   22066             }
   22067             return sdEncKey;
   22068         } catch (NoSuchAlgorithmException nsae) {
   22069             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
   22070             return null;
   22071         } catch (IOException ioe) {
   22072             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
   22073             return null;
   22074         }
   22075     }
   22076 
   22077     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
   22078             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
   22079         final int size = infos.size();
   22080         final String[] packageNames = new String[size];
   22081         final int[] packageUids = new int[size];
   22082         for (int i = 0; i < size; i++) {
   22083             final ApplicationInfo info = infos.get(i);
   22084             packageNames[i] = info.packageName;
   22085             packageUids[i] = info.uid;
   22086         }
   22087         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
   22088                 finishedReceiver);
   22089     }
   22090 
   22091     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
   22092             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
   22093         sendResourcesChangedBroadcast(mediaStatus, replacing,
   22094                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
   22095     }
   22096 
   22097     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
   22098             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
   22099         int size = pkgList.length;
   22100         if (size > 0) {
   22101             // Send broadcasts here
   22102             Bundle extras = new Bundle();
   22103             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
   22104             if (uidArr != null) {
   22105                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
   22106             }
   22107             if (replacing) {
   22108                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
   22109             }
   22110             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
   22111                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
   22112             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
   22113         }
   22114     }
   22115 
   22116     private void loadPrivatePackages(final VolumeInfo vol) {
   22117         mHandler.post(new Runnable() {
   22118             @Override
   22119             public void run() {
   22120                 loadPrivatePackagesInner(vol);
   22121             }
   22122         });
   22123     }
   22124 
   22125     private void loadPrivatePackagesInner(VolumeInfo vol) {
   22126         final String volumeUuid = vol.fsUuid;
   22127         if (TextUtils.isEmpty(volumeUuid)) {
   22128             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
   22129             return;
   22130         }
   22131 
   22132         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
   22133         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
   22134         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
   22135 
   22136         final VersionInfo ver;
   22137         final List<PackageSetting> packages;
   22138         synchronized (mPackages) {
   22139             ver = mSettings.findOrCreateVersion(volumeUuid);
   22140             packages = mSettings.getVolumePackagesLPr(volumeUuid);
   22141         }
   22142 
   22143         for (PackageSetting ps : packages) {
   22144             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
   22145             synchronized (mInstallLock) {
   22146                 final PackageParser.Package pkg;
   22147                 try {
   22148                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
   22149                     loaded.add(pkg.applicationInfo);
   22150 
   22151                 } catch (PackageManagerException e) {
   22152                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
   22153                 }
   22154 
   22155                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
   22156                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
   22157                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
   22158                                     | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
   22159                 }
   22160             }
   22161         }
   22162 
   22163         // Reconcile app data for all started/unlocked users
   22164         final StorageManager sm = mContext.getSystemService(StorageManager.class);
   22165         final UserManager um = mContext.getSystemService(UserManager.class);
   22166         UserManagerInternal umInternal = getUserManagerInternal();
   22167         for (UserInfo user : um.getUsers()) {
   22168             final int flags;
   22169             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
   22170                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
   22171             } else if (umInternal.isUserRunning(user.id)) {
   22172                 flags = StorageManager.FLAG_STORAGE_DE;
   22173             } else {
   22174                 continue;
   22175             }
   22176 
   22177             try {
   22178                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
   22179                 synchronized (mInstallLock) {
   22180                     reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
   22181                 }
   22182             } catch (IllegalStateException e) {
   22183                 // Device was probably ejected, and we'll process that event momentarily
   22184                 Slog.w(TAG, "Failed to prepare storage: " + e);
   22185             }
   22186         }
   22187 
   22188         synchronized (mPackages) {
   22189             final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
   22190             if (sdkUpdated) {
   22191                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
   22192                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
   22193             }
   22194             mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
   22195                     mPermissionCallback);
   22196 
   22197             // Yay, everything is now upgraded
   22198             ver.forceCurrent();
   22199 
   22200             mSettings.writeLPr();
   22201         }
   22202 
   22203         for (PackageFreezer freezer : freezers) {
   22204             freezer.close();
   22205         }
   22206 
   22207         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
   22208         sendResourcesChangedBroadcast(true, false, loaded, null);
   22209         mLoadedVolumes.add(vol.getId());
   22210     }
   22211 
   22212     private void unloadPrivatePackages(final VolumeInfo vol) {
   22213         mHandler.post(new Runnable() {
   22214             @Override
   22215             public void run() {
   22216                 unloadPrivatePackagesInner(vol);
   22217             }
   22218         });
   22219     }
   22220 
   22221     private void unloadPrivatePackagesInner(VolumeInfo vol) {
   22222         final String volumeUuid = vol.fsUuid;
   22223         if (TextUtils.isEmpty(volumeUuid)) {
   22224             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
   22225             return;
   22226         }
   22227 
   22228         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
   22229         synchronized (mInstallLock) {
   22230         synchronized (mPackages) {
   22231             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
   22232             for (PackageSetting ps : packages) {
   22233                 if (ps.pkg == null) continue;
   22234 
   22235                 final ApplicationInfo info = ps.pkg.applicationInfo;
   22236                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
   22237                 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
   22238 
   22239                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
   22240                         "unloadPrivatePackagesInner")) {
   22241                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
   22242                             false, null)) {
   22243                         unloaded.add(info);
   22244                     } else {
   22245                         Slog.w(TAG, "Failed to unload " + ps.codePath);
   22246                     }
   22247                 }
   22248 
   22249                 // Try very hard to release any references to this package
   22250                 // so we don't risk the system server being killed due to
   22251                 // open FDs
   22252                 AttributeCache.instance().removePackage(ps.name);
   22253             }
   22254 
   22255             mSettings.writeLPr();
   22256         }
   22257         }
   22258 
   22259         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
   22260         sendResourcesChangedBroadcast(false, false, unloaded, null);
   22261         mLoadedVolumes.remove(vol.getId());
   22262 
   22263         // Try very hard to release any references to this path so we don't risk
   22264         // the system server being killed due to open FDs
   22265         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
   22266 
   22267         for (int i = 0; i < 3; i++) {
   22268             System.gc();
   22269             System.runFinalization();
   22270         }
   22271     }
   22272 
   22273     private void assertPackageKnown(String volumeUuid, String packageName)
   22274             throws PackageManagerException {
   22275         synchronized (mPackages) {
   22276             // Normalize package name to handle renamed packages
   22277             packageName = normalizePackageNameLPr(packageName);
   22278 
   22279             final PackageSetting ps = mSettings.mPackages.get(packageName);
   22280             if (ps == null) {
   22281                 throw new PackageManagerException("Package " + packageName + " is unknown");
   22282             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
   22283                 throw new PackageManagerException(
   22284                         "Package " + packageName + " found on unknown volume " + volumeUuid
   22285                                 + "; expected volume " + ps.volumeUuid);
   22286             }
   22287         }
   22288     }
   22289 
   22290     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
   22291             throws PackageManagerException {
   22292         synchronized (mPackages) {
   22293             // Normalize package name to handle renamed packages
   22294             packageName = normalizePackageNameLPr(packageName);
   22295 
   22296             final PackageSetting ps = mSettings.mPackages.get(packageName);
   22297             if (ps == null) {
   22298                 throw new PackageManagerException("Package " + packageName + " is unknown");
   22299             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
   22300                 throw new PackageManagerException(
   22301                         "Package " + packageName + " found on unknown volume " + volumeUuid
   22302                                 + "; expected volume " + ps.volumeUuid);
   22303             } else if (!ps.getInstalled(userId)) {
   22304                 throw new PackageManagerException(
   22305                         "Package " + packageName + " not installed for user " + userId);
   22306             }
   22307         }
   22308     }
   22309 
   22310     private List<String> collectAbsoluteCodePaths() {
   22311         synchronized (mPackages) {
   22312             List<String> codePaths = new ArrayList<>();
   22313             final int packageCount = mSettings.mPackages.size();
   22314             for (int i = 0; i < packageCount; i++) {
   22315                 final PackageSetting ps = mSettings.mPackages.valueAt(i);
   22316                 codePaths.add(ps.codePath.getAbsolutePath());
   22317             }
   22318             return codePaths;
   22319         }
   22320     }
   22321 
   22322     /**
   22323      * Examine all apps present on given mounted volume, and destroy apps that
   22324      * aren't expected, either due to uninstallation or reinstallation on
   22325      * another volume.
   22326      */
   22327     private void reconcileApps(String volumeUuid) {
   22328         List<String> absoluteCodePaths = collectAbsoluteCodePaths();
   22329         List<File> filesToDelete = null;
   22330 
   22331         final File[] files = FileUtils.listFilesOrEmpty(
   22332                 Environment.getDataAppDirectory(volumeUuid));
   22333         for (File file : files) {
   22334             final boolean isPackage = (isApkFile(file) || file.isDirectory())
   22335                     && !PackageInstallerService.isStageName(file.getName());
   22336             if (!isPackage) {
   22337                 // Ignore entries which are not packages
   22338                 continue;
   22339             }
   22340 
   22341             String absolutePath = file.getAbsolutePath();
   22342 
   22343             boolean pathValid = false;
   22344             final int absoluteCodePathCount = absoluteCodePaths.size();
   22345             for (int i = 0; i < absoluteCodePathCount; i++) {
   22346                 String absoluteCodePath = absoluteCodePaths.get(i);
   22347                 if (absolutePath.startsWith(absoluteCodePath)) {
   22348                     pathValid = true;
   22349                     break;
   22350                 }
   22351             }
   22352 
   22353             if (!pathValid) {
   22354                 if (filesToDelete == null) {
   22355                     filesToDelete = new ArrayList<>();
   22356                 }
   22357                 filesToDelete.add(file);
   22358             }
   22359         }
   22360 
   22361         if (filesToDelete != null) {
   22362             final int fileToDeleteCount = filesToDelete.size();
   22363             for (int i = 0; i < fileToDeleteCount; i++) {
   22364                 File fileToDelete = filesToDelete.get(i);
   22365                 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
   22366                 synchronized (mInstallLock) {
   22367                     removeCodePathLI(fileToDelete);
   22368                 }
   22369             }
   22370         }
   22371     }
   22372 
   22373     /**
   22374      * Reconcile all app data for the given user.
   22375      * <p>
   22376      * Verifies that directories exist and that ownership and labeling is
   22377      * correct for all installed apps on all mounted volumes.
   22378      */
   22379     void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
   22380         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   22381         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
   22382             final String volumeUuid = vol.getFsUuid();
   22383             synchronized (mInstallLock) {
   22384                 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
   22385             }
   22386         }
   22387     }
   22388 
   22389     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
   22390             boolean migrateAppData) {
   22391         reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
   22392     }
   22393 
   22394     /**
   22395      * Reconcile all app data on given mounted volume.
   22396      * <p>
   22397      * Destroys app data that isn't expected, either due to uninstallation or
   22398      * reinstallation on another volume.
   22399      * <p>
   22400      * Verifies that directories exist and that ownership and labeling is
   22401      * correct for all installed apps.
   22402      * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
   22403      */
   22404     private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
   22405             boolean migrateAppData, boolean onlyCoreApps) {
   22406         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
   22407                 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
   22408         List<String> result = onlyCoreApps ? new ArrayList<>() : null;
   22409 
   22410         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
   22411         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
   22412 
   22413         // First look for stale data that doesn't belong, and check if things
   22414         // have changed since we did our last restorecon
   22415         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
   22416             if (StorageManager.isFileEncryptedNativeOrEmulated()
   22417                     && !StorageManager.isUserKeyUnlocked(userId)) {
   22418                 throw new RuntimeException(
   22419                         "Yikes, someone asked us to reconcile CE storage while " + userId
   22420                                 + " was still locked; this would have caused massive data loss!");
   22421             }
   22422 
   22423             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
   22424             for (File file : files) {
   22425                 final String packageName = file.getName();
   22426                 try {
   22427                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
   22428                 } catch (PackageManagerException e) {
   22429                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
   22430                     try {
   22431                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
   22432                                 StorageManager.FLAG_STORAGE_CE, 0);
   22433                     } catch (InstallerException e2) {
   22434                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
   22435                     }
   22436                 }
   22437             }
   22438         }
   22439         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
   22440             final File[] files = FileUtils.listFilesOrEmpty(deDir);
   22441             for (File file : files) {
   22442                 final String packageName = file.getName();
   22443                 try {
   22444                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
   22445                 } catch (PackageManagerException e) {
   22446                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
   22447                     try {
   22448                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
   22449                                 StorageManager.FLAG_STORAGE_DE, 0);
   22450                     } catch (InstallerException e2) {
   22451                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
   22452                     }
   22453                 }
   22454             }
   22455         }
   22456 
   22457         // Ensure that data directories are ready to roll for all packages
   22458         // installed for this volume and user
   22459         final List<PackageSetting> packages;
   22460         synchronized (mPackages) {
   22461             packages = mSettings.getVolumePackagesLPr(volumeUuid);
   22462         }
   22463         int preparedCount = 0;
   22464         for (PackageSetting ps : packages) {
   22465             final String packageName = ps.name;
   22466             if (ps.pkg == null) {
   22467                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
   22468                 // TODO: might be due to legacy ASEC apps; we should circle back
   22469                 // and reconcile again once they're scanned
   22470                 continue;
   22471             }
   22472             // Skip non-core apps if requested
   22473             if (onlyCoreApps && !ps.pkg.coreApp) {
   22474                 result.add(packageName);
   22475                 continue;
   22476             }
   22477 
   22478             if (ps.getInstalled(userId)) {
   22479                 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
   22480                 preparedCount++;
   22481             }
   22482         }
   22483 
   22484         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
   22485         return result;
   22486     }
   22487 
   22488     /**
   22489      * Prepare app data for the given app just after it was installed or
   22490      * upgraded. This method carefully only touches users that it's installed
   22491      * for, and it forces a restorecon to handle any seinfo changes.
   22492      * <p>
   22493      * Verifies that directories exist and that ownership and labeling is
   22494      * correct for all installed apps. If there is an ownership mismatch, it
   22495      * will try recovering system apps by wiping data; third-party app data is
   22496      * left intact.
   22497      * <p>
   22498      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
   22499      */
   22500     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
   22501         final PackageSetting ps;
   22502         synchronized (mPackages) {
   22503             ps = mSettings.mPackages.get(pkg.packageName);
   22504             mSettings.writeKernelMappingLPr(ps);
   22505         }
   22506 
   22507         final UserManager um = mContext.getSystemService(UserManager.class);
   22508         UserManagerInternal umInternal = getUserManagerInternal();
   22509         for (UserInfo user : um.getUsers()) {
   22510             final int flags;
   22511             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
   22512                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
   22513             } else if (umInternal.isUserRunning(user.id)) {
   22514                 flags = StorageManager.FLAG_STORAGE_DE;
   22515             } else {
   22516                 continue;
   22517             }
   22518 
   22519             if (ps.getInstalled(user.id)) {
   22520                 // TODO: when user data is locked, mark that we're still dirty
   22521                 prepareAppDataLIF(pkg, user.id, flags);
   22522             }
   22523         }
   22524     }
   22525 
   22526     /**
   22527      * Prepare app data for the given app.
   22528      * <p>
   22529      * Verifies that directories exist and that ownership and labeling is
   22530      * correct for all installed apps. If there is an ownership mismatch, this
   22531      * will try recovering system apps by wiping data; third-party app data is
   22532      * left intact.
   22533      */
   22534     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
   22535         if (pkg == null) {
   22536             Slog.wtf(TAG, "Package was null!", new Throwable());
   22537             return;
   22538         }
   22539         prepareAppDataLeafLIF(pkg, userId, flags);
   22540         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   22541         for (int i = 0; i < childCount; i++) {
   22542             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
   22543         }
   22544     }
   22545 
   22546     private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
   22547             boolean maybeMigrateAppData) {
   22548         prepareAppDataLIF(pkg, userId, flags);
   22549 
   22550         if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
   22551             // We may have just shuffled around app data directories, so
   22552             // prepare them one more time
   22553             prepareAppDataLIF(pkg, userId, flags);
   22554         }
   22555     }
   22556 
   22557     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
   22558         if (DEBUG_APP_DATA) {
   22559             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
   22560                     + Integer.toHexString(flags));
   22561         }
   22562 
   22563         final PackageSetting ps;
   22564         synchronized (mPackages) {
   22565             ps = mSettings.mPackages.get(pkg.packageName);
   22566         }
   22567         final String volumeUuid = pkg.volumeUuid;
   22568         final String packageName = pkg.packageName;
   22569 
   22570         ApplicationInfo app = (ps == null)
   22571                 ? pkg.applicationInfo
   22572                 : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
   22573         if (app == null) {
   22574             app = pkg.applicationInfo;
   22575         }
   22576 
   22577         final int appId = UserHandle.getAppId(app.uid);
   22578 
   22579         Preconditions.checkNotNull(app.seInfo);
   22580 
   22581         final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
   22582         long ceDataInode = -1;
   22583         try {
   22584             ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
   22585                     appId, seInfo, app.targetSdkVersion);
   22586         } catch (InstallerException e) {
   22587             if (app.isSystemApp()) {
   22588                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
   22589                         + ", but trying to recover: " + e);
   22590                 destroyAppDataLeafLIF(pkg, userId, flags);
   22591                 try {
   22592                     ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
   22593                             appId, seInfo, app.targetSdkVersion);
   22594                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
   22595                 } catch (InstallerException e2) {
   22596                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
   22597                 }
   22598             } else {
   22599                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
   22600             }
   22601         }
   22602         // Prepare the application profiles only for upgrades and first boot (so that we don't
   22603         // repeat the same operation at each boot).
   22604         // We only have to cover the upgrade and first boot here because for app installs we
   22605         // prepare the profiles before invoking dexopt (in installPackageLI).
   22606         //
   22607         // We also have to cover non system users because we do not call the usual install package
   22608         // methods for them.
   22609         if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
   22610             mArtManagerService.prepareAppProfiles(pkg, userId);
   22611         }
   22612 
   22613         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
   22614             // TODO: mark this structure as dirty so we persist it!
   22615             synchronized (mPackages) {
   22616                 if (ps != null) {
   22617                     ps.setCeDataInode(ceDataInode, userId);
   22618                 }
   22619             }
   22620         }
   22621 
   22622         prepareAppDataContentsLeafLIF(pkg, userId, flags);
   22623     }
   22624 
   22625     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
   22626         if (pkg == null) {
   22627             Slog.wtf(TAG, "Package was null!", new Throwable());
   22628             return;
   22629         }
   22630         prepareAppDataContentsLeafLIF(pkg, userId, flags);
   22631         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
   22632         for (int i = 0; i < childCount; i++) {
   22633             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
   22634         }
   22635     }
   22636 
   22637     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
   22638         final String volumeUuid = pkg.volumeUuid;
   22639         final String packageName = pkg.packageName;
   22640         final ApplicationInfo app = pkg.applicationInfo;
   22641 
   22642         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
   22643             // Create a native library symlink only if we have native libraries
   22644             // and if the native libraries are 32 bit libraries. We do not provide
   22645             // this symlink for 64 bit libraries.
   22646             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
   22647                 final String nativeLibPath = app.nativeLibraryDir;
   22648                 try {
   22649                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
   22650                             nativeLibPath, userId);
   22651                 } catch (InstallerException e) {
   22652                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
   22653                 }
   22654             }
   22655         }
   22656     }
   22657 
   22658     /**
   22659      * For system apps on non-FBE devices, this method migrates any existing
   22660      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
   22661      * requested by the app.
   22662      */
   22663     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
   22664         if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
   22665                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
   22666             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
   22667                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
   22668             try {
   22669                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
   22670                         storageTarget);
   22671             } catch (InstallerException e) {
   22672                 logCriticalInfo(Log.WARN,
   22673                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
   22674             }
   22675             return true;
   22676         } else {
   22677             return false;
   22678         }
   22679     }
   22680 
   22681     public PackageFreezer freezePackage(String packageName, String killReason) {
   22682         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
   22683     }
   22684 
   22685     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
   22686         return new PackageFreezer(packageName, userId, killReason);
   22687     }
   22688 
   22689     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
   22690             String killReason) {
   22691         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
   22692     }
   22693 
   22694     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
   22695             String killReason) {
   22696         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
   22697             return new PackageFreezer();
   22698         } else {
   22699             return freezePackage(packageName, userId, killReason);
   22700         }
   22701     }
   22702 
   22703     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
   22704             String killReason) {
   22705         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
   22706     }
   22707 
   22708     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
   22709             String killReason) {
   22710         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
   22711             return new PackageFreezer();
   22712         } else {
   22713             return freezePackage(packageName, userId, killReason);
   22714         }
   22715     }
   22716 
   22717     /**
   22718      * Class that freezes and kills the given package upon creation, and
   22719      * unfreezes it upon closing. This is typically used when doing surgery on
   22720      * app code/data to prevent the app from running while you're working.
   22721      */
   22722     private class PackageFreezer implements AutoCloseable {
   22723         private final String mPackageName;
   22724         private final PackageFreezer[] mChildren;
   22725 
   22726         private final boolean mWeFroze;
   22727 
   22728         private final AtomicBoolean mClosed = new AtomicBoolean();
   22729         private final CloseGuard mCloseGuard = CloseGuard.get();
   22730 
   22731         /**
   22732          * Create and return a stub freezer that doesn't actually do anything,
   22733          * typically used when someone requested
   22734          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
   22735          * {@link PackageManager#DELETE_DONT_KILL_APP}.
   22736          */
   22737         public PackageFreezer() {
   22738             mPackageName = null;
   22739             mChildren = null;
   22740             mWeFroze = false;
   22741             mCloseGuard.open("close");
   22742         }
   22743 
   22744         public PackageFreezer(String packageName, int userId, String killReason) {
   22745             synchronized (mPackages) {
   22746                 mPackageName = packageName;
   22747                 mWeFroze = mFrozenPackages.add(mPackageName);
   22748 
   22749                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
   22750                 if (ps != null) {
   22751                     killApplication(ps.name, ps.appId, userId, killReason);
   22752                 }
   22753 
   22754                 final PackageParser.Package p = mPackages.get(packageName);
   22755                 if (p != null && p.childPackages != null) {
   22756                     final int N = p.childPackages.size();
   22757                     mChildren = new PackageFreezer[N];
   22758                     for (int i = 0; i < N; i++) {
   22759                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
   22760                                 userId, killReason);
   22761                     }
   22762                 } else {
   22763                     mChildren = null;
   22764                 }
   22765             }
   22766             mCloseGuard.open("close");
   22767         }
   22768 
   22769         @Override
   22770         protected void finalize() throws Throwable {
   22771             try {
   22772                 if (mCloseGuard != null) {
   22773                     mCloseGuard.warnIfOpen();
   22774                 }
   22775 
   22776                 close();
   22777             } finally {
   22778                 super.finalize();
   22779             }
   22780         }
   22781 
   22782         @Override
   22783         public void close() {
   22784             mCloseGuard.close();
   22785             if (mClosed.compareAndSet(false, true)) {
   22786                 synchronized (mPackages) {
   22787                     if (mWeFroze) {
   22788                         mFrozenPackages.remove(mPackageName);
   22789                     }
   22790 
   22791                     if (mChildren != null) {
   22792                         for (PackageFreezer freezer : mChildren) {
   22793                             freezer.close();
   22794                         }
   22795                     }
   22796                 }
   22797             }
   22798         }
   22799     }
   22800 
   22801     /**
   22802      * Verify that given package is currently frozen.
   22803      */
   22804     private void checkPackageFrozen(String packageName) {
   22805         synchronized (mPackages) {
   22806             if (!mFrozenPackages.contains(packageName)) {
   22807                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
   22808             }
   22809         }
   22810     }
   22811 
   22812     @Override
   22813     public int movePackage(final String packageName, final String volumeUuid) {
   22814         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
   22815 
   22816         final int callingUid = Binder.getCallingUid();
   22817         final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
   22818         final int moveId = mNextMoveId.getAndIncrement();
   22819         mHandler.post(new Runnable() {
   22820             @Override
   22821             public void run() {
   22822                 try {
   22823                     movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
   22824                 } catch (PackageManagerException e) {
   22825                     Slog.w(TAG, "Failed to move " + packageName, e);
   22826                     mMoveCallbacks.notifyStatusChanged(moveId, e.error);
   22827                 }
   22828             }
   22829         });
   22830         return moveId;
   22831     }
   22832 
   22833     private void movePackageInternal(final String packageName, final String volumeUuid,
   22834             final int moveId, final int callingUid, UserHandle user)
   22835                     throws PackageManagerException {
   22836         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   22837         final PackageManager pm = mContext.getPackageManager();
   22838 
   22839         final boolean currentAsec;
   22840         final String currentVolumeUuid;
   22841         final File codeFile;
   22842         final String installerPackageName;
   22843         final String packageAbiOverride;
   22844         final int appId;
   22845         final String seinfo;
   22846         final String label;
   22847         final int targetSdkVersion;
   22848         final PackageFreezer freezer;
   22849         final int[] installedUserIds;
   22850 
   22851         // reader
   22852         synchronized (mPackages) {
   22853             final PackageParser.Package pkg = mPackages.get(packageName);
   22854             final PackageSetting ps = mSettings.mPackages.get(packageName);
   22855             if (pkg == null
   22856                     || ps == null
   22857                     || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
   22858                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
   22859             }
   22860             if (pkg.applicationInfo.isSystemApp()) {
   22861                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
   22862                         "Cannot move system application");
   22863             }
   22864 
   22865             final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
   22866             final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
   22867                     com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
   22868             if (isInternalStorage && !allow3rdPartyOnInternal) {
   22869                 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
   22870                         "3rd party apps are not allowed on internal storage");
   22871             }
   22872 
   22873             if (pkg.applicationInfo.isExternalAsec()) {
   22874                 currentAsec = true;
   22875                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
   22876             } else if (pkg.applicationInfo.isForwardLocked()) {
   22877                 currentAsec = true;
   22878                 currentVolumeUuid = "forward_locked";
   22879             } else {
   22880                 currentAsec = false;
   22881                 currentVolumeUuid = ps.volumeUuid;
   22882 
   22883                 final File probe = new File(pkg.codePath);
   22884                 final File probeOat = new File(probe, "oat");
   22885                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
   22886                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
   22887                             "Move only supported for modern cluster style installs");
   22888                 }
   22889             }
   22890 
   22891             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
   22892                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
   22893                         "Package already moved to " + volumeUuid);
   22894             }
   22895             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
   22896                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
   22897                         "Device admin cannot be moved");
   22898             }
   22899 
   22900             if (mFrozenPackages.contains(packageName)) {
   22901                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
   22902                         "Failed to move already frozen package");
   22903             }
   22904 
   22905             codeFile = new File(pkg.codePath);
   22906             installerPackageName = ps.installerPackageName;
   22907             packageAbiOverride = ps.cpuAbiOverrideString;
   22908             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
   22909             seinfo = pkg.applicationInfo.seInfo;
   22910             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
   22911             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
   22912             freezer = freezePackage(packageName, "movePackageInternal");
   22913             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
   22914         }
   22915 
   22916         final Bundle extras = new Bundle();
   22917         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
   22918         extras.putString(Intent.EXTRA_TITLE, label);
   22919         mMoveCallbacks.notifyCreated(moveId, extras);
   22920 
   22921         int installFlags;
   22922         final boolean moveCompleteApp;
   22923         final File measurePath;
   22924 
   22925         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
   22926             installFlags = INSTALL_INTERNAL;
   22927             moveCompleteApp = !currentAsec;
   22928             measurePath = Environment.getDataAppDirectory(volumeUuid);
   22929         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
   22930             installFlags = INSTALL_EXTERNAL;
   22931             moveCompleteApp = false;
   22932             measurePath = storage.getPrimaryPhysicalVolume().getPath();
   22933         } else {
   22934             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
   22935             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
   22936                     || !volume.isMountedWritable()) {
   22937                 freezer.close();
   22938                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
   22939                         "Move location not mounted private volume");
   22940             }
   22941 
   22942             Preconditions.checkState(!currentAsec);
   22943 
   22944             installFlags = INSTALL_INTERNAL;
   22945             moveCompleteApp = true;
   22946             measurePath = Environment.getDataAppDirectory(volumeUuid);
   22947         }
   22948 
   22949         // If we're moving app data around, we need all the users unlocked
   22950         if (moveCompleteApp) {
   22951             for (int userId : installedUserIds) {
   22952                 if (StorageManager.isFileEncryptedNativeOrEmulated()
   22953                         && !StorageManager.isUserKeyUnlocked(userId)) {
   22954                     throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
   22955                             "User " + userId + " must be unlocked");
   22956                 }
   22957             }
   22958         }
   22959 
   22960         final PackageStats stats = new PackageStats(null, -1);
   22961         synchronized (mInstaller) {
   22962             for (int userId : installedUserIds) {
   22963                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
   22964                     freezer.close();
   22965                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
   22966                             "Failed to measure package size");
   22967                 }
   22968             }
   22969         }
   22970 
   22971         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
   22972                 + stats.dataSize);
   22973 
   22974         final long startFreeBytes = measurePath.getUsableSpace();
   22975         final long sizeBytes;
   22976         if (moveCompleteApp) {
   22977             sizeBytes = stats.codeSize + stats.dataSize;
   22978         } else {
   22979             sizeBytes = stats.codeSize;
   22980         }
   22981 
   22982         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
   22983             freezer.close();
   22984             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
   22985                     "Not enough free space to move");
   22986         }
   22987 
   22988         mMoveCallbacks.notifyStatusChanged(moveId, 10);
   22989 
   22990         final CountDownLatch installedLatch = new CountDownLatch(1);
   22991         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
   22992             @Override
   22993             public void onUserActionRequired(Intent intent) throws RemoteException {
   22994                 throw new IllegalStateException();
   22995             }
   22996 
   22997             @Override
   22998             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
   22999                     Bundle extras) throws RemoteException {
   23000                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
   23001                         + PackageManager.installStatusToString(returnCode, msg));
   23002 
   23003                 installedLatch.countDown();
   23004                 freezer.close();
   23005 
   23006                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
   23007                 switch (status) {
   23008                     case PackageInstaller.STATUS_SUCCESS:
   23009                         mMoveCallbacks.notifyStatusChanged(moveId,
   23010                                 PackageManager.MOVE_SUCCEEDED);
   23011                         break;
   23012                     case PackageInstaller.STATUS_FAILURE_STORAGE:
   23013                         mMoveCallbacks.notifyStatusChanged(moveId,
   23014                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
   23015                         break;
   23016                     default:
   23017                         mMoveCallbacks.notifyStatusChanged(moveId,
   23018                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
   23019                         break;
   23020                 }
   23021             }
   23022         };
   23023 
   23024         final MoveInfo move;
   23025         if (moveCompleteApp) {
   23026             // Kick off a thread to report progress estimates
   23027             new Thread() {
   23028                 @Override
   23029                 public void run() {
   23030                     while (true) {
   23031                         try {
   23032                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
   23033                                 break;
   23034                             }
   23035                         } catch (InterruptedException ignored) {
   23036                         }
   23037 
   23038                         final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
   23039                         final int progress = 10 + (int) MathUtils.constrain(
   23040                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
   23041                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
   23042                     }
   23043                 }
   23044             }.start();
   23045 
   23046             final String dataAppName = codeFile.getName();
   23047             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
   23048                     dataAppName, appId, seinfo, targetSdkVersion);
   23049         } else {
   23050             move = null;
   23051         }
   23052 
   23053         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
   23054 
   23055         final Message msg = mHandler.obtainMessage(INIT_COPY);
   23056         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
   23057         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
   23058                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
   23059                 packageAbiOverride, null /*grantedPermissions*/,
   23060                 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
   23061         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
   23062         msg.obj = params;
   23063 
   23064         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
   23065                 System.identityHashCode(msg.obj));
   23066         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
   23067                 System.identityHashCode(msg.obj));
   23068 
   23069         mHandler.sendMessage(msg);
   23070     }
   23071 
   23072     @Override
   23073     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
   23074         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
   23075 
   23076         final int realMoveId = mNextMoveId.getAndIncrement();
   23077         final Bundle extras = new Bundle();
   23078         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
   23079         mMoveCallbacks.notifyCreated(realMoveId, extras);
   23080 
   23081         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
   23082             @Override
   23083             public void onCreated(int moveId, Bundle extras) {
   23084                 // Ignored
   23085             }
   23086 
   23087             @Override
   23088             public void onStatusChanged(int moveId, int status, long estMillis) {
   23089                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
   23090             }
   23091         };
   23092 
   23093         final StorageManager storage = mContext.getSystemService(StorageManager.class);
   23094         storage.setPrimaryStorageUuid(volumeUuid, callback);
   23095         return realMoveId;
   23096     }
   23097 
   23098     @Override
   23099     public int getMoveStatus(int moveId) {
   23100         mContext.enforceCallingOrSelfPermission(
   23101                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
   23102         return mMoveCallbacks.mLastStatus.get(moveId);
   23103     }
   23104 
   23105     @Override
   23106     public void registerMoveCallback(IPackageMoveObserver callback) {
   23107         mContext.enforceCallingOrSelfPermission(
   23108                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
   23109         mMoveCallbacks.register(callback);
   23110     }
   23111 
   23112     @Override
   23113     public void unregisterMoveCallback(IPackageMoveObserver callback) {
   23114         mContext.enforceCallingOrSelfPermission(
   23115                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
   23116         mMoveCallbacks.unregister(callback);
   23117     }
   23118 
   23119     @Override
   23120     public boolean setInstallLocation(int loc) {
   23121         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
   23122                 null);
   23123         if (getInstallLocation() == loc) {
   23124             return true;
   23125         }
   23126         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
   23127                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
   23128             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
   23129                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
   23130             return true;
   23131         }
   23132         return false;
   23133    }
   23134 
   23135     @Override
   23136     public int getInstallLocation() {
   23137         // allow instant app access
   23138         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   23139                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
   23140                 PackageHelper.APP_INSTALL_AUTO);
   23141     }
   23142 
   23143     /** Called by UserManagerService */
   23144     void cleanUpUser(UserManagerService userManager, int userHandle) {
   23145         synchronized (mPackages) {
   23146             mDirtyUsers.remove(userHandle);
   23147             mUserNeedsBadging.delete(userHandle);
   23148             mSettings.removeUserLPw(userHandle);
   23149             mPendingBroadcasts.remove(userHandle);
   23150             mInstantAppRegistry.onUserRemovedLPw(userHandle);
   23151             removeUnusedPackagesLPw(userManager, userHandle);
   23152         }
   23153     }
   23154 
   23155     /**
   23156      * We're removing userHandle and would like to remove any downloaded packages
   23157      * that are no longer in use by any other user.
   23158      * @param userHandle the user being removed
   23159      */
   23160     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
   23161         final boolean DEBUG_CLEAN_APKS = false;
   23162         int [] users = userManager.getUserIds();
   23163         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
   23164         while (psit.hasNext()) {
   23165             PackageSetting ps = psit.next();
   23166             if (ps.pkg == null) {
   23167                 continue;
   23168             }
   23169             final String packageName = ps.pkg.packageName;
   23170             // Skip over if system app
   23171             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   23172                 continue;
   23173             }
   23174             if (DEBUG_CLEAN_APKS) {
   23175                 Slog.i(TAG, "Checking package " + packageName);
   23176             }
   23177             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
   23178             if (keep) {
   23179                 if (DEBUG_CLEAN_APKS) {
   23180                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
   23181                 }
   23182             } else {
   23183                 for (int i = 0; i < users.length; i++) {
   23184                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
   23185                         keep = true;
   23186                         if (DEBUG_CLEAN_APKS) {
   23187                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
   23188                                     + users[i]);
   23189                         }
   23190                         break;
   23191                     }
   23192                 }
   23193             }
   23194             if (!keep) {
   23195                 if (DEBUG_CLEAN_APKS) {
   23196                     Slog.i(TAG, "  Removing package " + packageName);
   23197                 }
   23198                 mHandler.post(new Runnable() {
   23199                     public void run() {
   23200                         deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
   23201                                 userHandle, 0);
   23202                     } //end run
   23203                 });
   23204             }
   23205         }
   23206     }
   23207 
   23208     /** Called by UserManagerService */
   23209     void createNewUser(int userId, String[] disallowedPackages) {
   23210         synchronized (mInstallLock) {
   23211             mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
   23212         }
   23213         synchronized (mPackages) {
   23214             scheduleWritePackageRestrictionsLocked(userId);
   23215             scheduleWritePackageListLocked(userId);
   23216             applyFactoryDefaultBrowserLPw(userId);
   23217             primeDomainVerificationsLPw(userId);
   23218         }
   23219     }
   23220 
   23221     void onNewUserCreated(final int userId) {
   23222         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
   23223         synchronized(mPackages) {
   23224             // If permission review for legacy apps is required, we represent
   23225             // dagerous permissions for such apps as always granted runtime
   23226             // permissions to keep per user flag state whether review is needed.
   23227             // Hence, if a new user is added we have to propagate dangerous
   23228             // permission grants for these legacy apps.
   23229             if (mSettings.mPermissions.mPermissionReviewRequired) {
   23230 // NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
   23231                 mPermissionManager.updateAllPermissions(
   23232                         StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
   23233                         mPermissionCallback);
   23234             }
   23235         }
   23236     }
   23237 
   23238     @Override
   23239     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
   23240         mContext.enforceCallingOrSelfPermission(
   23241                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   23242                 "Only package verification agents can read the verifier device identity");
   23243 
   23244         synchronized (mPackages) {
   23245             return mSettings.getVerifierDeviceIdentityLPw();
   23246         }
   23247     }
   23248 
   23249     @Override
   23250     public void setPermissionEnforced(String permission, boolean enforced) {
   23251         // TODO: Now that we no longer change GID for storage, this should to away.
   23252         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
   23253                 "setPermissionEnforced");
   23254         if (READ_EXTERNAL_STORAGE.equals(permission)) {
   23255             synchronized (mPackages) {
   23256                 if (mSettings.mReadExternalStorageEnforced == null
   23257                         || mSettings.mReadExternalStorageEnforced != enforced) {
   23258                     mSettings.mReadExternalStorageEnforced =
   23259                             enforced ? Boolean.TRUE : Boolean.FALSE;
   23260                     mSettings.writeLPr();
   23261                 }
   23262             }
   23263             // kill any non-foreground processes so we restart them and
   23264             // grant/revoke the GID.
   23265             final IActivityManager am = ActivityManager.getService();
   23266             if (am != null) {
   23267                 final long token = Binder.clearCallingIdentity();
   23268                 try {
   23269                     am.killProcessesBelowForeground("setPermissionEnforcement");
   23270                 } catch (RemoteException e) {
   23271                 } finally {
   23272                     Binder.restoreCallingIdentity(token);
   23273                 }
   23274             }
   23275         } else {
   23276             throw new IllegalArgumentException("No selective enforcement for " + permission);
   23277         }
   23278     }
   23279 
   23280     @Override
   23281     @Deprecated
   23282     public boolean isPermissionEnforced(String permission) {
   23283         // allow instant applications
   23284         return true;
   23285     }
   23286 
   23287     @Override
   23288     public boolean isStorageLow() {
   23289         // allow instant applications
   23290         final long token = Binder.clearCallingIdentity();
   23291         try {
   23292             final DeviceStorageMonitorInternal
   23293                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
   23294             if (dsm != null) {
   23295                 return dsm.isMemoryLow();
   23296             } else {
   23297                 return false;
   23298             }
   23299         } finally {
   23300             Binder.restoreCallingIdentity(token);
   23301         }
   23302     }
   23303 
   23304     @Override
   23305     public IPackageInstaller getPackageInstaller() {
   23306         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   23307             return null;
   23308         }
   23309         return mInstallerService;
   23310     }
   23311 
   23312     @Override
   23313     public IArtManager getArtManager() {
   23314         return mArtManagerService;
   23315     }
   23316 
   23317     private boolean userNeedsBadging(int userId) {
   23318         int index = mUserNeedsBadging.indexOfKey(userId);
   23319         if (index < 0) {
   23320             final UserInfo userInfo;
   23321             final long token = Binder.clearCallingIdentity();
   23322             try {
   23323                 userInfo = sUserManager.getUserInfo(userId);
   23324             } finally {
   23325                 Binder.restoreCallingIdentity(token);
   23326             }
   23327             final boolean b;
   23328             if (userInfo != null && userInfo.isManagedProfile()) {
   23329                 b = true;
   23330             } else {
   23331                 b = false;
   23332             }
   23333             mUserNeedsBadging.put(userId, b);
   23334             return b;
   23335         }
   23336         return mUserNeedsBadging.valueAt(index);
   23337     }
   23338 
   23339     @Override
   23340     public KeySet getKeySetByAlias(String packageName, String alias) {
   23341         if (packageName == null || alias == null) {
   23342             return null;
   23343         }
   23344         synchronized(mPackages) {
   23345             final PackageParser.Package pkg = mPackages.get(packageName);
   23346             if (pkg == null) {
   23347                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
   23348                 throw new IllegalArgumentException("Unknown package: " + packageName);
   23349             }
   23350             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   23351             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
   23352                 Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
   23353                 throw new IllegalArgumentException("Unknown package: " + packageName);
   23354             }
   23355             final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   23356             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
   23357         }
   23358     }
   23359 
   23360     @Override
   23361     public KeySet getSigningKeySet(String packageName) {
   23362         if (packageName == null) {
   23363             return null;
   23364         }
   23365         synchronized(mPackages) {
   23366             final int callingUid = Binder.getCallingUid();
   23367             final int callingUserId = UserHandle.getUserId(callingUid);
   23368             final PackageParser.Package pkg = mPackages.get(packageName);
   23369             if (pkg == null) {
   23370                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
   23371                 throw new IllegalArgumentException("Unknown package: " + packageName);
   23372             }
   23373             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   23374             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
   23375                 // filter and pretend the package doesn't exist
   23376                 Slog.w(TAG, "KeySet requested for filtered package: " + packageName
   23377                         + ", uid:" + callingUid);
   23378                 throw new IllegalArgumentException("Unknown package: " + packageName);
   23379             }
   23380             if (pkg.applicationInfo.uid != callingUid
   23381                     && Process.SYSTEM_UID != callingUid) {
   23382                 throw new SecurityException("May not access signing KeySet of other apps.");
   23383             }
   23384             final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   23385             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
   23386         }
   23387     }
   23388 
   23389     @Override
   23390     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
   23391         final int callingUid = Binder.getCallingUid();
   23392         if (getInstantAppPackageName(callingUid) != null) {
   23393             return false;
   23394         }
   23395         if (packageName == null || ks == null) {
   23396             return false;
   23397         }
   23398         synchronized(mPackages) {
   23399             final PackageParser.Package pkg = mPackages.get(packageName);
   23400             if (pkg == null
   23401                     || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
   23402                             UserHandle.getUserId(callingUid))) {
   23403                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
   23404                 throw new IllegalArgumentException("Unknown package: " + packageName);
   23405             }
   23406             IBinder ksh = ks.getToken();
   23407             if (ksh instanceof KeySetHandle) {
   23408                 final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   23409                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
   23410             }
   23411             return false;
   23412         }
   23413     }
   23414 
   23415     @Override
   23416     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
   23417         final int callingUid = Binder.getCallingUid();
   23418         if (getInstantAppPackageName(callingUid) != null) {
   23419             return false;
   23420         }
   23421         if (packageName == null || ks == null) {
   23422             return false;
   23423         }
   23424         synchronized(mPackages) {
   23425             final PackageParser.Package pkg = mPackages.get(packageName);
   23426             if (pkg == null
   23427                     || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
   23428                             UserHandle.getUserId(callingUid))) {
   23429                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
   23430                 throw new IllegalArgumentException("Unknown package: " + packageName);
   23431             }
   23432             IBinder ksh = ks.getToken();
   23433             if (ksh instanceof KeySetHandle) {
   23434                 final KeySetManagerService ksms = mSettings.mKeySetManagerService;
   23435                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
   23436             }
   23437             return false;
   23438         }
   23439     }
   23440 
   23441     private void deletePackageIfUnusedLPr(final String packageName) {
   23442         PackageSetting ps = mSettings.mPackages.get(packageName);
   23443         if (ps == null) {
   23444             return;
   23445         }
   23446         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
   23447             // TODO Implement atomic delete if package is unused
   23448             // It is currently possible that the package will be deleted even if it is installed
   23449             // after this method returns.
   23450             mHandler.post(new Runnable() {
   23451                 public void run() {
   23452                     deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
   23453                             0, PackageManager.DELETE_ALL_USERS);
   23454                 }
   23455             });
   23456         }
   23457     }
   23458 
   23459     /**
   23460      * Check and throw if the given before/after packages would be considered a
   23461      * downgrade.
   23462      */
   23463     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
   23464             throws PackageManagerException {
   23465         if (after.getLongVersionCode() < before.getLongVersionCode()) {
   23466             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
   23467                     "Update version code " + after.versionCode + " is older than current "
   23468                     + before.getLongVersionCode());
   23469         } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
   23470             if (after.baseRevisionCode < before.baseRevisionCode) {
   23471                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
   23472                         "Update base revision code " + after.baseRevisionCode
   23473                         + " is older than current " + before.baseRevisionCode);
   23474             }
   23475 
   23476             if (!ArrayUtils.isEmpty(after.splitNames)) {
   23477                 for (int i = 0; i < after.splitNames.length; i++) {
   23478                     final String splitName = after.splitNames[i];
   23479                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
   23480                     if (j != -1) {
   23481                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
   23482                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
   23483                                     "Update split " + splitName + " revision code "
   23484                                     + after.splitRevisionCodes[i] + " is older than current "
   23485                                     + before.splitRevisionCodes[j]);
   23486                         }
   23487                     }
   23488                 }
   23489             }
   23490         }
   23491     }
   23492 
   23493     private static class MoveCallbacks extends Handler {
   23494         private static final int MSG_CREATED = 1;
   23495         private static final int MSG_STATUS_CHANGED = 2;
   23496 
   23497         private final RemoteCallbackList<IPackageMoveObserver>
   23498                 mCallbacks = new RemoteCallbackList<>();
   23499 
   23500         private final SparseIntArray mLastStatus = new SparseIntArray();
   23501 
   23502         public MoveCallbacks(Looper looper) {
   23503             super(looper);
   23504         }
   23505 
   23506         public void register(IPackageMoveObserver callback) {
   23507             mCallbacks.register(callback);
   23508         }
   23509 
   23510         public void unregister(IPackageMoveObserver callback) {
   23511             mCallbacks.unregister(callback);
   23512         }
   23513 
   23514         @Override
   23515         public void handleMessage(Message msg) {
   23516             final SomeArgs args = (SomeArgs) msg.obj;
   23517             final int n = mCallbacks.beginBroadcast();
   23518             for (int i = 0; i < n; i++) {
   23519                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
   23520                 try {
   23521                     invokeCallback(callback, msg.what, args);
   23522                 } catch (RemoteException ignored) {
   23523                 }
   23524             }
   23525             mCallbacks.finishBroadcast();
   23526             args.recycle();
   23527         }
   23528 
   23529         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
   23530                 throws RemoteException {
   23531             switch (what) {
   23532                 case MSG_CREATED: {
   23533                     callback.onCreated(args.argi1, (Bundle) args.arg2);
   23534                     break;
   23535                 }
   23536                 case MSG_STATUS_CHANGED: {
   23537                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
   23538                     break;
   23539                 }
   23540             }
   23541         }
   23542 
   23543         private void notifyCreated(int moveId, Bundle extras) {
   23544             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
   23545 
   23546             final SomeArgs args = SomeArgs.obtain();
   23547             args.argi1 = moveId;
   23548             args.arg2 = extras;
   23549             obtainMessage(MSG_CREATED, args).sendToTarget();
   23550         }
   23551 
   23552         private void notifyStatusChanged(int moveId, int status) {
   23553             notifyStatusChanged(moveId, status, -1);
   23554         }
   23555 
   23556         private void notifyStatusChanged(int moveId, int status, long estMillis) {
   23557             Slog.v(TAG, "Move " + moveId + " status " + status);
   23558 
   23559             final SomeArgs args = SomeArgs.obtain();
   23560             args.argi1 = moveId;
   23561             args.argi2 = status;
   23562             args.arg3 = estMillis;
   23563             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
   23564 
   23565             synchronized (mLastStatus) {
   23566                 mLastStatus.put(moveId, status);
   23567             }
   23568         }
   23569     }
   23570 
   23571     private final static class OnPermissionChangeListeners extends Handler {
   23572         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
   23573 
   23574         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
   23575                 new RemoteCallbackList<>();
   23576 
   23577         public OnPermissionChangeListeners(Looper looper) {
   23578             super(looper);
   23579         }
   23580 
   23581         @Override
   23582         public void handleMessage(Message msg) {
   23583             switch (msg.what) {
   23584                 case MSG_ON_PERMISSIONS_CHANGED: {
   23585                     final int uid = msg.arg1;
   23586                     handleOnPermissionsChanged(uid);
   23587                 } break;
   23588             }
   23589         }
   23590 
   23591         public void addListenerLocked(IOnPermissionsChangeListener listener) {
   23592             mPermissionListeners.register(listener);
   23593 
   23594         }
   23595 
   23596         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
   23597             mPermissionListeners.unregister(listener);
   23598         }
   23599 
   23600         public void onPermissionsChanged(int uid) {
   23601             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
   23602                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
   23603             }
   23604         }
   23605 
   23606         private void handleOnPermissionsChanged(int uid) {
   23607             final int count = mPermissionListeners.beginBroadcast();
   23608             try {
   23609                 for (int i = 0; i < count; i++) {
   23610                     IOnPermissionsChangeListener callback = mPermissionListeners
   23611                             .getBroadcastItem(i);
   23612                     try {
   23613                         callback.onPermissionsChanged(uid);
   23614                     } catch (RemoteException e) {
   23615                         Log.e(TAG, "Permission listener is dead", e);
   23616                     }
   23617                 }
   23618             } finally {
   23619                 mPermissionListeners.finishBroadcast();
   23620             }
   23621         }
   23622     }
   23623 
   23624     private class PackageManagerNative extends IPackageManagerNative.Stub {
   23625         @Override
   23626         public String[] getNamesForUids(int[] uids) throws RemoteException {
   23627             final String[] results = PackageManagerService.this.getNamesForUids(uids);
   23628             // massage results so they can be parsed by the native binder
   23629             for (int i = results.length - 1; i >= 0; --i) {
   23630                 if (results[i] == null) {
   23631                     results[i] = "";
   23632                 }
   23633             }
   23634             return results;
   23635         }
   23636 
   23637         // NB: this differentiates between preloads and sideloads
   23638         @Override
   23639         public String getInstallerForPackage(String packageName) throws RemoteException {
   23640             final String installerName = getInstallerPackageName(packageName);
   23641             if (!TextUtils.isEmpty(installerName)) {
   23642                 return installerName;
   23643             }
   23644             // differentiate between preload and sideload
   23645             int callingUser = UserHandle.getUserId(Binder.getCallingUid());
   23646             ApplicationInfo appInfo = getApplicationInfo(packageName,
   23647                                     /*flags*/ 0,
   23648                                     /*userId*/ callingUser);
   23649             if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   23650                 return "preload";
   23651             }
   23652             return "";
   23653         }
   23654 
   23655         @Override
   23656         public long getVersionCodeForPackage(String packageName) throws RemoteException {
   23657             try {
   23658                 int callingUser = UserHandle.getUserId(Binder.getCallingUid());
   23659                 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
   23660                 if (pInfo != null) {
   23661                     return pInfo.getLongVersionCode();
   23662                 }
   23663             } catch (Exception e) {
   23664             }
   23665             return 0;
   23666         }
   23667     }
   23668 
   23669     private class PackageManagerInternalImpl extends PackageManagerInternal {
   23670         @Override
   23671         public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
   23672                 int flagValues, int userId) {
   23673             PackageManagerService.this.updatePermissionFlags(
   23674                     permName, packageName, flagMask, flagValues, userId);
   23675         }
   23676 
   23677         @Override
   23678         public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
   23679             SigningDetails sd = getSigningDetails(packageName);
   23680             if (sd == null) {
   23681                 return false;
   23682             }
   23683             return sd.hasSha256Certificate(restoringFromSigHash,
   23684                     SigningDetails.CertCapabilities.INSTALLED_DATA);
   23685         }
   23686 
   23687         @Override
   23688         public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
   23689             SigningDetails sd = getSigningDetails(packageName);
   23690             if (sd == null) {
   23691                 return false;
   23692             }
   23693             return sd.hasCertificate(restoringFromSig,
   23694                     SigningDetails.CertCapabilities.INSTALLED_DATA);
   23695         }
   23696 
   23697         @Override
   23698         public boolean hasSignatureCapability(int serverUid, int clientUid,
   23699                 @SigningDetails.CertCapabilities int capability) {
   23700             SigningDetails serverSigningDetails = getSigningDetails(serverUid);
   23701             SigningDetails clientSigningDetails = getSigningDetails(clientUid);
   23702             return serverSigningDetails.checkCapability(clientSigningDetails, capability)
   23703                     || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
   23704 
   23705         }
   23706 
   23707         private SigningDetails getSigningDetails(@NonNull String packageName) {
   23708             synchronized (mPackages) {
   23709                 PackageParser.Package p = mPackages.get(packageName);
   23710                 if (p == null) {
   23711                     return null;
   23712                 }
   23713                 return p.mSigningDetails;
   23714             }
   23715         }
   23716 
   23717         private SigningDetails getSigningDetails(int uid) {
   23718             synchronized (mPackages) {
   23719                 final int appId = UserHandle.getAppId(uid);
   23720                 final Object obj = mSettings.getUserIdLPr(appId);
   23721                 if (obj != null) {
   23722                     if (obj instanceof SharedUserSetting) {
   23723                         return ((SharedUserSetting) obj).signatures.mSigningDetails;
   23724                     } else if (obj instanceof PackageSetting) {
   23725                         final PackageSetting ps = (PackageSetting) obj;
   23726                         return ps.signatures.mSigningDetails;
   23727                     }
   23728                 }
   23729                 return SigningDetails.UNKNOWN;
   23730             }
   23731         }
   23732 
   23733         @Override
   23734         public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
   23735             return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
   23736         }
   23737 
   23738         @Override
   23739         public boolean isInstantApp(String packageName, int userId) {
   23740             return PackageManagerService.this.isInstantApp(packageName, userId);
   23741         }
   23742 
   23743         @Override
   23744         public String getInstantAppPackageName(int uid) {
   23745             return PackageManagerService.this.getInstantAppPackageName(uid);
   23746         }
   23747 
   23748         @Override
   23749         public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
   23750             synchronized (mPackages) {
   23751                 return PackageManagerService.this.filterAppAccessLPr(
   23752                         (PackageSetting) pkg.mExtras, callingUid, userId);
   23753             }
   23754         }
   23755 
   23756         @Override
   23757         public PackageParser.Package getPackage(String packageName) {
   23758             synchronized (mPackages) {
   23759                 packageName = resolveInternalPackageNameLPr(
   23760                         packageName, PackageManager.VERSION_CODE_HIGHEST);
   23761                 return mPackages.get(packageName);
   23762             }
   23763         }
   23764 
   23765         @Override
   23766         public PackageList getPackageList(PackageListObserver observer) {
   23767             synchronized (mPackages) {
   23768                 final int N = mPackages.size();
   23769                 final ArrayList<String> list = new ArrayList<>(N);
   23770                 for (int i = 0; i < N; i++) {
   23771                     list.add(mPackages.keyAt(i));
   23772                 }
   23773                 final PackageList packageList = new PackageList(list, observer);
   23774                 if (observer != null) {
   23775                     mPackageListObservers.add(packageList);
   23776                 }
   23777                 return packageList;
   23778             }
   23779         }
   23780 
   23781         @Override
   23782         public void removePackageListObserver(PackageListObserver observer) {
   23783             synchronized (mPackages) {
   23784                 mPackageListObservers.remove(observer);
   23785             }
   23786         }
   23787 
   23788         @Override
   23789         public PackageParser.Package getDisabledPackage(String packageName) {
   23790             synchronized (mPackages) {
   23791                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
   23792                 return (ps != null) ? ps.pkg : null;
   23793             }
   23794         }
   23795 
   23796         @Override
   23797         public String getKnownPackageName(int knownPackage, int userId) {
   23798             switch(knownPackage) {
   23799                 case PackageManagerInternal.PACKAGE_BROWSER:
   23800                     return getDefaultBrowserPackageName(userId);
   23801                 case PackageManagerInternal.PACKAGE_INSTALLER:
   23802                     return mRequiredInstallerPackage;
   23803                 case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
   23804                     return mSetupWizardPackage;
   23805                 case PackageManagerInternal.PACKAGE_SYSTEM:
   23806                     return "android";
   23807                 case PackageManagerInternal.PACKAGE_VERIFIER:
   23808                     return mRequiredVerifierPackage;
   23809                 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
   23810                     return mSystemTextClassifierPackage;
   23811             }
   23812             return null;
   23813         }
   23814 
   23815         @Override
   23816         public boolean isResolveActivityComponent(ComponentInfo component) {
   23817             return mResolveActivity.packageName.equals(component.packageName)
   23818                     && mResolveActivity.name.equals(component.name);
   23819         }
   23820 
   23821         @Override
   23822         public void setLocationPackagesProvider(PackagesProvider provider) {
   23823             mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
   23824         }
   23825 
   23826         @Override
   23827         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
   23828             mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
   23829         }
   23830 
   23831         @Override
   23832         public void setSmsAppPackagesProvider(PackagesProvider provider) {
   23833             mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
   23834         }
   23835 
   23836         @Override
   23837         public void setDialerAppPackagesProvider(PackagesProvider provider) {
   23838             mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
   23839         }
   23840 
   23841         @Override
   23842         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
   23843             mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
   23844         }
   23845 
   23846         @Override
   23847         public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
   23848             mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
   23849         }
   23850 
   23851         @Override
   23852         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
   23853             mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
   23854         }
   23855 
   23856         @Override
   23857         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
   23858             mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
   23859         }
   23860 
   23861         @Override
   23862         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
   23863             synchronized (mPackages) {
   23864                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
   23865             }
   23866             mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
   23867         }
   23868 
   23869         @Override
   23870         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
   23871             mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
   23872                     packageName, userId);
   23873         }
   23874 
   23875         @Override
   23876         public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
   23877             mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
   23878                     packageName, userId);
   23879         }
   23880 
   23881         @Override
   23882         public void setKeepUninstalledPackages(final List<String> packageList) {
   23883             Preconditions.checkNotNull(packageList);
   23884             List<String> removedFromList = null;
   23885             synchronized (mPackages) {
   23886                 if (mKeepUninstalledPackages != null) {
   23887                     final int packagesCount = mKeepUninstalledPackages.size();
   23888                     for (int i = 0; i < packagesCount; i++) {
   23889                         String oldPackage = mKeepUninstalledPackages.get(i);
   23890                         if (packageList != null && packageList.contains(oldPackage)) {
   23891                             continue;
   23892                         }
   23893                         if (removedFromList == null) {
   23894                             removedFromList = new ArrayList<>();
   23895                         }
   23896                         removedFromList.add(oldPackage);
   23897                     }
   23898                 }
   23899                 mKeepUninstalledPackages = new ArrayList<>(packageList);
   23900                 if (removedFromList != null) {
   23901                     final int removedCount = removedFromList.size();
   23902                     for (int i = 0; i < removedCount; i++) {
   23903                         deletePackageIfUnusedLPr(removedFromList.get(i));
   23904                     }
   23905                 }
   23906             }
   23907         }
   23908 
   23909         @Override
   23910         public boolean isPermissionsReviewRequired(String packageName, int userId) {
   23911             synchronized (mPackages) {
   23912                 return mPermissionManager.isPermissionsReviewRequired(
   23913                         mPackages.get(packageName), userId);
   23914             }
   23915         }
   23916 
   23917         @Override
   23918         public PackageInfo getPackageInfo(
   23919                 String packageName, int flags, int filterCallingUid, int userId) {
   23920             return PackageManagerService.this
   23921                     .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
   23922                             flags, filterCallingUid, userId);
   23923         }
   23924 
   23925         @Override
   23926         public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
   23927             synchronized (mPackages) {
   23928                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   23929                 PersistableBundle launcherExtras = null;
   23930                 if (ps != null) {
   23931                     launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
   23932                 }
   23933                 return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
   23934             }
   23935         }
   23936 
   23937         @Override
   23938         public boolean isPackageSuspended(String packageName, int userId) {
   23939             synchronized (mPackages) {
   23940                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   23941                 return (ps != null) ? ps.getSuspended(userId) : false;
   23942             }
   23943         }
   23944 
   23945         @Override
   23946         public String getSuspendingPackage(String suspendedPackage, int userId) {
   23947             synchronized (mPackages) {
   23948                 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
   23949                 return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
   23950             }
   23951         }
   23952 
   23953         @Override
   23954         public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
   23955             synchronized (mPackages) {
   23956                 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
   23957                 return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
   23958             }
   23959         }
   23960 
   23961         @Override
   23962         public int getPackageUid(String packageName, int flags, int userId) {
   23963             return PackageManagerService.this
   23964                     .getPackageUid(packageName, flags, userId);
   23965         }
   23966 
   23967         @Override
   23968         public ApplicationInfo getApplicationInfo(
   23969                 String packageName, int flags, int filterCallingUid, int userId) {
   23970             return PackageManagerService.this
   23971                     .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
   23972         }
   23973 
   23974         @Override
   23975         public ActivityInfo getActivityInfo(
   23976                 ComponentName component, int flags, int filterCallingUid, int userId) {
   23977             return PackageManagerService.this
   23978                     .getActivityInfoInternal(component, flags, filterCallingUid, userId);
   23979         }
   23980 
   23981         @Override
   23982         public List<ResolveInfo> queryIntentActivities(
   23983                 Intent intent, int flags, int filterCallingUid, int userId) {
   23984             final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
   23985             return PackageManagerService.this
   23986                     .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
   23987                             userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
   23988         }
   23989 
   23990         @Override
   23991         public List<ResolveInfo> queryIntentServices(
   23992                 Intent intent, int flags, int callingUid, int userId) {
   23993             final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
   23994             return PackageManagerService.this
   23995                     .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
   23996                             false);
   23997         }
   23998 
   23999         @Override
   24000         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
   24001                 int userId) {
   24002             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
   24003         }
   24004 
   24005         @Override
   24006         public ComponentName getDefaultHomeActivity(int userId) {
   24007             return PackageManagerService.this.getDefaultHomeActivity(userId);
   24008         }
   24009 
   24010         @Override
   24011         public void setDeviceAndProfileOwnerPackages(
   24012                 int deviceOwnerUserId, String deviceOwnerPackage,
   24013                 SparseArray<String> profileOwnerPackages) {
   24014             mProtectedPackages.setDeviceAndProfileOwnerPackages(
   24015                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
   24016 
   24017             final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>();
   24018             if (deviceOwnerPackage != null) {
   24019                 usersWithPoOrDo.add(deviceOwnerUserId);
   24020             }
   24021             final int sz = profileOwnerPackages.size();
   24022             for (int i = 0; i < sz; i++) {
   24023                 if (profileOwnerPackages.valueAt(i) != null) {
   24024                     usersWithPoOrDo.add(profileOwnerPackages.keyAt(i));
   24025                 }
   24026             }
   24027             unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo);
   24028         }
   24029 
   24030         @Override
   24031         public boolean isPackageDataProtected(int userId, String packageName) {
   24032             return mProtectedPackages.isPackageDataProtected(userId, packageName);
   24033         }
   24034 
   24035         @Override
   24036         public boolean isPackageStateProtected(String packageName, int userId) {
   24037             return mProtectedPackages.isPackageStateProtected(userId, packageName);
   24038         }
   24039 
   24040         @Override
   24041         public boolean isPackageEphemeral(int userId, String packageName) {
   24042             synchronized (mPackages) {
   24043                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   24044                 return ps != null ? ps.getInstantApp(userId) : false;
   24045             }
   24046         }
   24047 
   24048         @Override
   24049         public boolean wasPackageEverLaunched(String packageName, int userId) {
   24050             synchronized (mPackages) {
   24051                 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
   24052             }
   24053         }
   24054 
   24055         @Override
   24056         public void grantRuntimePermission(String packageName, String permName, int userId,
   24057                 boolean overridePolicy) {
   24058             PackageManagerService.this.mPermissionManager.grantRuntimePermission(
   24059                     permName, packageName, overridePolicy, getCallingUid(), userId,
   24060                     mPermissionCallback);
   24061         }
   24062 
   24063         @Override
   24064         public void revokeRuntimePermission(String packageName, String permName, int userId,
   24065                 boolean overridePolicy) {
   24066             mPermissionManager.revokeRuntimePermission(
   24067                     permName, packageName, overridePolicy, getCallingUid(), userId,
   24068                     mPermissionCallback);
   24069         }
   24070 
   24071         @Override
   24072         public String getNameForUid(int uid) {
   24073             return PackageManagerService.this.getNameForUid(uid);
   24074         }
   24075 
   24076         @Override
   24077         public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
   24078                 Intent origIntent, String resolvedType, String callingPackage,
   24079                 Bundle verificationBundle, int userId) {
   24080             PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
   24081                     responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
   24082                     userId);
   24083         }
   24084 
   24085         @Override
   24086         public void grantEphemeralAccess(int userId, Intent intent,
   24087                 int targetAppId, int ephemeralAppId) {
   24088             synchronized (mPackages) {
   24089                 mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
   24090                         targetAppId, ephemeralAppId);
   24091             }
   24092         }
   24093 
   24094         @Override
   24095         public boolean isInstantAppInstallerComponent(ComponentName component) {
   24096             synchronized (mPackages) {
   24097                 return mInstantAppInstallerActivity != null
   24098                         && mInstantAppInstallerActivity.getComponentName().equals(component);
   24099             }
   24100         }
   24101 
   24102         @Override
   24103         public void pruneInstantApps() {
   24104             mInstantAppRegistry.pruneInstantApps();
   24105         }
   24106 
   24107         @Override
   24108         public String getSetupWizardPackageName() {
   24109             return mSetupWizardPackage;
   24110         }
   24111 
   24112         public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
   24113             if (policy != null) {
   24114                 mExternalSourcesPolicy = policy;
   24115             }
   24116         }
   24117 
   24118         @Override
   24119         public boolean isPackagePersistent(String packageName) {
   24120             synchronized (mPackages) {
   24121                 PackageParser.Package pkg = mPackages.get(packageName);
   24122                 return pkg != null
   24123                         ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
   24124                                         | ApplicationInfo.FLAG_PERSISTENT)) ==
   24125                                 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
   24126                         : false;
   24127             }
   24128         }
   24129 
   24130         @Override
   24131         public boolean isLegacySystemApp(Package pkg) {
   24132             synchronized (mPackages) {
   24133                 final PackageSetting ps = (PackageSetting) pkg.mExtras;
   24134                 return mPromoteSystemApps
   24135                         && ps.isSystem()
   24136                         && mExistingSystemPackages.contains(ps.name);
   24137             }
   24138         }
   24139 
   24140         @Override
   24141         public List<PackageInfo> getOverlayPackages(int userId) {
   24142             final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
   24143             synchronized (mPackages) {
   24144                 for (PackageParser.Package p : mPackages.values()) {
   24145                     if (p.mOverlayTarget != null) {
   24146                         PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
   24147                         if (pkg != null) {
   24148                             overlayPackages.add(pkg);
   24149                         }
   24150                     }
   24151                 }
   24152             }
   24153             return overlayPackages;
   24154         }
   24155 
   24156         @Override
   24157         public List<String> getTargetPackageNames(int userId) {
   24158             List<String> targetPackages = new ArrayList<>();
   24159             synchronized (mPackages) {
   24160                 for (PackageParser.Package p : mPackages.values()) {
   24161                     if (p.mOverlayTarget == null) {
   24162                         targetPackages.add(p.packageName);
   24163                     }
   24164                 }
   24165             }
   24166             return targetPackages;
   24167         }
   24168 
   24169         @Override
   24170         public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
   24171                 @Nullable List<String> overlayPackageNames) {
   24172             synchronized (mPackages) {
   24173                 if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
   24174                     Slog.e(TAG, "failed to find package " + targetPackageName);
   24175                     return false;
   24176                 }
   24177                 ArrayList<String> overlayPaths = null;
   24178                 if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
   24179                     final int N = overlayPackageNames.size();
   24180                     overlayPaths = new ArrayList<>(N);
   24181                     for (int i = 0; i < N; i++) {
   24182                         final String packageName = overlayPackageNames.get(i);
   24183                         final PackageParser.Package pkg = mPackages.get(packageName);
   24184                         if (pkg == null) {
   24185                             Slog.e(TAG, "failed to find package " + packageName);
   24186                             return false;
   24187                         }
   24188                         overlayPaths.add(pkg.baseCodePath);
   24189                     }
   24190                 }
   24191 
   24192                 final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
   24193                 ps.setOverlayPaths(overlayPaths, userId);
   24194                 return true;
   24195             }
   24196         }
   24197 
   24198         @Override
   24199         public ResolveInfo resolveIntent(Intent intent, String resolvedType,
   24200                 int flags, int userId, boolean resolveForStart, int filterCallingUid) {
   24201             return resolveIntentInternal(
   24202                     intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
   24203         }
   24204 
   24205         @Override
   24206         public ResolveInfo resolveService(Intent intent, String resolvedType,
   24207                 int flags, int userId, int callingUid) {
   24208             return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
   24209         }
   24210 
   24211         @Override
   24212         public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
   24213             return PackageManagerService.this.resolveContentProviderInternal(
   24214                     name, flags, userId);
   24215         }
   24216 
   24217         @Override
   24218         public void addIsolatedUid(int isolatedUid, int ownerUid) {
   24219             synchronized (mPackages) {
   24220                 mIsolatedOwners.put(isolatedUid, ownerUid);
   24221             }
   24222         }
   24223 
   24224         @Override
   24225         public void removeIsolatedUid(int isolatedUid) {
   24226             synchronized (mPackages) {
   24227                 mIsolatedOwners.delete(isolatedUid);
   24228             }
   24229         }
   24230 
   24231         @Override
   24232         public int getUidTargetSdkVersion(int uid) {
   24233             synchronized (mPackages) {
   24234                 return getUidTargetSdkVersionLockedLPr(uid);
   24235             }
   24236         }
   24237 
   24238         @Override
   24239         public int getPackageTargetSdkVersion(String packageName) {
   24240             synchronized (mPackages) {
   24241                 return getPackageTargetSdkVersionLockedLPr(packageName);
   24242             }
   24243         }
   24244 
   24245         @Override
   24246         public boolean canAccessInstantApps(int callingUid, int userId) {
   24247             return PackageManagerService.this.canViewInstantApps(callingUid, userId);
   24248         }
   24249 
   24250         @Override
   24251         public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
   24252             synchronized (mPackages) {
   24253                 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   24254                 return !PackageManagerService.this.filterAppAccessLPr(
   24255                         ps, callingUid, component, TYPE_UNKNOWN, userId);
   24256             }
   24257         }
   24258 
   24259         @Override
   24260         public boolean hasInstantApplicationMetadata(String packageName, int userId) {
   24261             synchronized (mPackages) {
   24262                 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
   24263             }
   24264         }
   24265 
   24266         @Override
   24267         public void notifyPackageUse(String packageName, int reason) {
   24268             synchronized (mPackages) {
   24269                 PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
   24270             }
   24271         }
   24272     }
   24273 
   24274     @Override
   24275     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
   24276         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
   24277         synchronized (mPackages) {
   24278             final long identity = Binder.clearCallingIdentity();
   24279             try {
   24280                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
   24281                         packageNames, userId);
   24282             } finally {
   24283                 Binder.restoreCallingIdentity(identity);
   24284             }
   24285         }
   24286     }
   24287 
   24288     @Override
   24289     public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
   24290         enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
   24291         synchronized (mPackages) {
   24292             final long identity = Binder.clearCallingIdentity();
   24293             try {
   24294                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
   24295                         packageNames, userId);
   24296             } finally {
   24297                 Binder.restoreCallingIdentity(identity);
   24298             }
   24299         }
   24300     }
   24301 
   24302     @Override
   24303     public void grantDefaultPermissionsToEnabledTelephonyDataServices(
   24304             String[] packageNames, int userId) {
   24305         enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
   24306         synchronized (mPackages) {
   24307             Binder.withCleanCallingIdentity( () -> {
   24308                 mDefaultPermissionPolicy.
   24309                         grantDefaultPermissionsToEnabledTelephonyDataServices(
   24310                                 packageNames, userId);
   24311             });
   24312         }
   24313     }
   24314 
   24315     @Override
   24316     public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
   24317             String[] packageNames, int userId) {
   24318         enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
   24319         synchronized (mPackages) {
   24320             Binder.withCleanCallingIdentity( () -> {
   24321                 mDefaultPermissionPolicy.
   24322                         revokeDefaultPermissionsFromDisabledTelephonyDataServices(
   24323                                 packageNames, userId);
   24324             });
   24325         }
   24326     }
   24327 
   24328     @Override
   24329     public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
   24330         enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
   24331         synchronized (mPackages) {
   24332             final long identity = Binder.clearCallingIdentity();
   24333             try {
   24334                 mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
   24335                         packageName, userId);
   24336             } finally {
   24337                 Binder.restoreCallingIdentity(identity);
   24338             }
   24339         }
   24340     }
   24341 
   24342     @Override
   24343     public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
   24344         enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
   24345         synchronized (mPackages) {
   24346             final long identity = Binder.clearCallingIdentity();
   24347             try {
   24348                 mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
   24349             } finally {
   24350                 Binder.restoreCallingIdentity(identity);
   24351             }
   24352         }
   24353     }
   24354 
   24355     private static void enforceSystemOrPhoneCaller(String tag) {
   24356         int callingUid = Binder.getCallingUid();
   24357         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
   24358             throw new SecurityException(
   24359                     "Cannot call " + tag + " from UID " + callingUid);
   24360         }
   24361     }
   24362 
   24363     boolean isHistoricalPackageUsageAvailable() {
   24364         return mPackageUsage.isHistoricalPackageUsageAvailable();
   24365     }
   24366 
   24367     /**
   24368      * Return a <b>copy</b> of the collection of packages known to the package manager.
   24369      * @return A copy of the values of mPackages.
   24370      */
   24371     Collection<PackageParser.Package> getPackages() {
   24372         synchronized (mPackages) {
   24373             return new ArrayList<>(mPackages.values());
   24374         }
   24375     }
   24376 
   24377     /**
   24378      * Logs process start information (including base APK hash) to the security log.
   24379      * @hide
   24380      */
   24381     @Override
   24382     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
   24383             String apkFile, int pid) {
   24384         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   24385             return;
   24386         }
   24387         if (!SecurityLog.isLoggingEnabled()) {
   24388             return;
   24389         }
   24390         Bundle data = new Bundle();
   24391         data.putLong("startTimestamp", System.currentTimeMillis());
   24392         data.putString("processName", processName);
   24393         data.putInt("uid", uid);
   24394         data.putString("seinfo", seinfo);
   24395         data.putString("apkFile", apkFile);
   24396         data.putInt("pid", pid);
   24397         Message msg = mProcessLoggingHandler.obtainMessage(
   24398                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
   24399         msg.setData(data);
   24400         mProcessLoggingHandler.sendMessage(msg);
   24401     }
   24402 
   24403     public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
   24404         return mCompilerStats.getPackageStats(pkgName);
   24405     }
   24406 
   24407     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
   24408         return getOrCreateCompilerPackageStats(pkg.packageName);
   24409     }
   24410 
   24411     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
   24412         return mCompilerStats.getOrCreatePackageStats(pkgName);
   24413     }
   24414 
   24415     public void deleteCompilerPackageStats(String pkgName) {
   24416         mCompilerStats.deletePackageStats(pkgName);
   24417     }
   24418 
   24419     @Override
   24420     public int getInstallReason(String packageName, int userId) {
   24421         final int callingUid = Binder.getCallingUid();
   24422         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   24423                 true /* requireFullPermission */, false /* checkShell */,
   24424                 "get install reason");
   24425         synchronized (mPackages) {
   24426             final PackageSetting ps = mSettings.mPackages.get(packageName);
   24427             if (filterAppAccessLPr(ps, callingUid, userId)) {
   24428                 return PackageManager.INSTALL_REASON_UNKNOWN;
   24429             }
   24430             if (ps != null) {
   24431                 return ps.getInstallReason(userId);
   24432             }
   24433         }
   24434         return PackageManager.INSTALL_REASON_UNKNOWN;
   24435     }
   24436 
   24437     @Override
   24438     public boolean canRequestPackageInstalls(String packageName, int userId) {
   24439         return canRequestPackageInstallsInternal(packageName, 0, userId,
   24440                 true /* throwIfPermNotDeclared*/);
   24441     }
   24442 
   24443     private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
   24444             boolean throwIfPermNotDeclared) {
   24445         int callingUid = Binder.getCallingUid();
   24446         int uid = getPackageUid(packageName, 0, userId);
   24447         if (callingUid != uid && callingUid != Process.ROOT_UID
   24448                 && callingUid != Process.SYSTEM_UID) {
   24449             throw new SecurityException(
   24450                     "Caller uid " + callingUid + " does not own package " + packageName);
   24451         }
   24452         ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
   24453         if (info == null) {
   24454             return false;
   24455         }
   24456         if (info.targetSdkVersion < Build.VERSION_CODES.O) {
   24457             return false;
   24458         }
   24459         if (isInstantApp(packageName, userId)) {
   24460             return false;
   24461         }
   24462         String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
   24463         String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
   24464         if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
   24465             if (throwIfPermNotDeclared) {
   24466                 throw new SecurityException("Need to declare " + appOpPermission
   24467                         + " to call this api");
   24468             } else {
   24469                 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
   24470                 return false;
   24471             }
   24472         }
   24473         if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
   24474             return false;
   24475         }
   24476         if (mExternalSourcesPolicy != null) {
   24477             int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
   24478             if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
   24479                 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
   24480             }
   24481         }
   24482         return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
   24483     }
   24484 
   24485     @Override
   24486     public ComponentName getInstantAppResolverSettingsComponent() {
   24487         return mInstantAppResolverSettingsComponent;
   24488     }
   24489 
   24490     @Override
   24491     public ComponentName getInstantAppInstallerComponent() {
   24492         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
   24493             return null;
   24494         }
   24495         return mInstantAppInstallerActivity == null
   24496                 ? null : mInstantAppInstallerActivity.getComponentName();
   24497     }
   24498 
   24499     @Override
   24500     public String getInstantAppAndroidId(String packageName, int userId) {
   24501         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
   24502                 "getInstantAppAndroidId");
   24503         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
   24504                 true /* requireFullPermission */, false /* checkShell */,
   24505                 "getInstantAppAndroidId");
   24506         // Make sure the target is an Instant App.
   24507         if (!isInstantApp(packageName, userId)) {
   24508             return null;
   24509         }
   24510         synchronized (mPackages) {
   24511             return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
   24512         }
   24513     }
   24514 
   24515     boolean canHaveOatDir(String packageName) {
   24516         synchronized (mPackages) {
   24517             PackageParser.Package p = mPackages.get(packageName);
   24518             if (p == null) {
   24519                 return false;
   24520             }
   24521             return p.canHaveOatDir();
   24522         }
   24523     }
   24524 
   24525     private String getOatDir(PackageParser.Package pkg) {
   24526         if (!pkg.canHaveOatDir()) {
   24527             return null;
   24528         }
   24529         File codePath = new File(pkg.codePath);
   24530         if (codePath.isDirectory()) {
   24531             return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
   24532         }
   24533         return null;
   24534     }
   24535 
   24536     void deleteOatArtifactsOfPackage(String packageName) {
   24537         final String[] instructionSets;
   24538         final List<String> codePaths;
   24539         final String oatDir;
   24540         final PackageParser.Package pkg;
   24541         synchronized (mPackages) {
   24542             pkg = mPackages.get(packageName);
   24543         }
   24544         instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
   24545         codePaths = pkg.getAllCodePaths();
   24546         oatDir = getOatDir(pkg);
   24547 
   24548         for (String codePath : codePaths) {
   24549             for (String isa : instructionSets) {
   24550                 try {
   24551                     mInstaller.deleteOdex(codePath, isa, oatDir);
   24552                 } catch (InstallerException e) {
   24553                     Log.e(TAG, "Failed deleting oat files for " + codePath, e);
   24554                 }
   24555             }
   24556         }
   24557     }
   24558 
   24559     Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
   24560         Set<String> unusedPackages = new HashSet<>();
   24561         long currentTimeInMillis = System.currentTimeMillis();
   24562         synchronized (mPackages) {
   24563             for (PackageParser.Package pkg : mPackages.values()) {
   24564                 PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
   24565                 if (ps == null) {
   24566                     continue;
   24567                 }
   24568                 PackageDexUsage.PackageUseInfo packageUseInfo =
   24569                       getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
   24570                 if (PackageManagerServiceUtils
   24571                         .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
   24572                                 downgradeTimeThresholdMillis, packageUseInfo,
   24573                                 pkg.getLatestPackageUseTimeInMills(),
   24574                                 pkg.getLatestForegroundPackageUseTimeInMills())) {
   24575                     unusedPackages.add(pkg.packageName);
   24576                 }
   24577             }
   24578         }
   24579         return unusedPackages;
   24580     }
   24581 
   24582     @Override
   24583     public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
   24584             int userId) {
   24585         final int callingUid = Binder.getCallingUid();
   24586         final int callingAppId = UserHandle.getAppId(callingUid);
   24587 
   24588         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   24589                 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
   24590 
   24591         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
   24592                 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
   24593             throw new SecurityException("Caller must have the "
   24594                     + SET_HARMFUL_APP_WARNINGS + " permission.");
   24595         }
   24596 
   24597         synchronized(mPackages) {
   24598             mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
   24599             scheduleWritePackageRestrictionsLocked(userId);
   24600         }
   24601     }
   24602 
   24603     @Nullable
   24604     @Override
   24605     public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
   24606         final int callingUid = Binder.getCallingUid();
   24607         final int callingAppId = UserHandle.getAppId(callingUid);
   24608 
   24609         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   24610                 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
   24611 
   24612         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
   24613                 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
   24614             throw new SecurityException("Caller must have the "
   24615                     + SET_HARMFUL_APP_WARNINGS + " permission.");
   24616         }
   24617 
   24618         synchronized(mPackages) {
   24619             return mSettings.getHarmfulAppWarningLPr(packageName, userId);
   24620         }
   24621     }
   24622 
   24623     @Override
   24624     public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
   24625         final int callingUid = Binder.getCallingUid();
   24626         final int callingAppId = UserHandle.getAppId(callingUid);
   24627 
   24628         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
   24629                 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
   24630 
   24631         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
   24632                 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
   24633             throw new SecurityException("Caller must have the "
   24634                     + MANAGE_DEVICE_ADMINS + " permission.");
   24635         }
   24636 
   24637         return mProtectedPackages.isPackageStateProtected(userId, packageName);
   24638     }
   24639 }
   24640 
   24641 interface PackageSender {
   24642     /**
   24643      * @param userIds User IDs where the action occurred on a full application
   24644      * @param instantUserIds User IDs where the action occurred on an instant application
   24645      */
   24646     void sendPackageBroadcast(final String action, final String pkg,
   24647         final Bundle extras, final int flags, final String targetPkg,
   24648         final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
   24649     void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
   24650         boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
   24651     void notifyPackageAdded(String packageName);
   24652     void notifyPackageRemoved(String packageName);
   24653 }
   24654