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.GRANT_REVOKE_PERMISSIONS;
     20 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
     21 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
     22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
     23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
     24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
     25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
     26 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
     27 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
     28 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
     29 import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
     30 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
     31 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
     32 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
     33 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
     34 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
     35 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
     36 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
     37 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
     38 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
     39 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
     40 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
     41 import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
     42 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
     43 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
     44 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
     45 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
     46 import static android.content.pm.PackageParser.isApkFile;
     47 import static android.os.Process.PACKAGE_INFO_GID;
     48 import static android.os.Process.SYSTEM_UID;
     49 import static android.system.OsConstants.O_CREAT;
     50 import static android.system.OsConstants.O_RDWR;
     51 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
     52 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
     53 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
     54 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
     55 import static com.android.internal.util.ArrayUtils.appendInt;
     56 import static com.android.internal.util.ArrayUtils.removeInt;
     57 
     58 import android.util.ArrayMap;
     59 
     60 import com.android.internal.R;
     61 import com.android.internal.app.IMediaContainerService;
     62 import com.android.internal.app.ResolverActivity;
     63 import com.android.internal.content.NativeLibraryHelper;
     64 import com.android.internal.content.PackageHelper;
     65 import com.android.internal.os.IParcelFileDescriptorFactory;
     66 import com.android.internal.util.ArrayUtils;
     67 import com.android.internal.util.FastPrintWriter;
     68 import com.android.internal.util.FastXmlSerializer;
     69 import com.android.internal.util.IndentingPrintWriter;
     70 import com.android.server.EventLogTags;
     71 import com.android.server.IntentResolver;
     72 import com.android.server.LocalServices;
     73 import com.android.server.ServiceThread;
     74 import com.android.server.SystemConfig;
     75 import com.android.server.Watchdog;
     76 import com.android.server.pm.Settings.DatabaseVersion;
     77 import com.android.server.storage.DeviceStorageMonitorInternal;
     78 
     79 import org.xmlpull.v1.XmlSerializer;
     80 
     81 import android.app.ActivityManager;
     82 import android.app.ActivityManagerNative;
     83 import android.app.AppGlobals;
     84 import android.app.IActivityManager;
     85 import android.app.admin.IDevicePolicyManager;
     86 import android.app.backup.IBackupManager;
     87 import android.content.BroadcastReceiver;
     88 import android.content.ComponentName;
     89 import android.content.Context;
     90 import android.content.IIntentReceiver;
     91 import android.content.Intent;
     92 import android.content.IntentFilter;
     93 import android.content.IntentSender;
     94 import android.content.IntentSender.SendIntentException;
     95 import android.content.ServiceConnection;
     96 import android.content.pm.ActivityInfo;
     97 import android.content.pm.ApplicationInfo;
     98 import android.content.pm.FeatureInfo;
     99 import android.content.pm.IPackageDataObserver;
    100 import android.content.pm.IPackageDeleteObserver;
    101 import android.content.pm.IPackageDeleteObserver2;
    102 import android.content.pm.IPackageInstallObserver2;
    103 import android.content.pm.IPackageInstaller;
    104 import android.content.pm.IPackageManager;
    105 import android.content.pm.IPackageMoveObserver;
    106 import android.content.pm.IPackageStatsObserver;
    107 import android.content.pm.InstrumentationInfo;
    108 import android.content.pm.KeySet;
    109 import android.content.pm.ManifestDigest;
    110 import android.content.pm.PackageCleanItem;
    111 import android.content.pm.PackageInfo;
    112 import android.content.pm.PackageInfoLite;
    113 import android.content.pm.PackageInstaller;
    114 import android.content.pm.PackageManager;
    115 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
    116 import android.content.pm.PackageParser.ActivityIntentInfo;
    117 import android.content.pm.PackageParser.PackageLite;
    118 import android.content.pm.PackageParser.PackageParserException;
    119 import android.content.pm.PackageParser;
    120 import android.content.pm.PackageStats;
    121 import android.content.pm.PackageUserState;
    122 import android.content.pm.ParceledListSlice;
    123 import android.content.pm.PermissionGroupInfo;
    124 import android.content.pm.PermissionInfo;
    125 import android.content.pm.ProviderInfo;
    126 import android.content.pm.ResolveInfo;
    127 import android.content.pm.ServiceInfo;
    128 import android.content.pm.Signature;
    129 import android.content.pm.UserInfo;
    130 import android.content.pm.VerificationParams;
    131 import android.content.pm.VerifierDeviceIdentity;
    132 import android.content.pm.VerifierInfo;
    133 import android.content.res.Resources;
    134 import android.hardware.display.DisplayManager;
    135 import android.net.Uri;
    136 import android.os.Binder;
    137 import android.os.Build;
    138 import android.os.Bundle;
    139 import android.os.Environment;
    140 import android.os.Environment.UserEnvironment;
    141 import android.os.storage.StorageManager;
    142 import android.os.Debug;
    143 import android.os.FileUtils;
    144 import android.os.Handler;
    145 import android.os.IBinder;
    146 import android.os.Looper;
    147 import android.os.Message;
    148 import android.os.Parcel;
    149 import android.os.ParcelFileDescriptor;
    150 import android.os.Process;
    151 import android.os.RemoteException;
    152 import android.os.SELinux;
    153 import android.os.ServiceManager;
    154 import android.os.SystemClock;
    155 import android.os.SystemProperties;
    156 import android.os.UserHandle;
    157 import android.os.UserManager;
    158 import android.security.KeyStore;
    159 import android.security.SystemKeyStore;
    160 import android.system.ErrnoException;
    161 import android.system.Os;
    162 import android.system.StructStat;
    163 import android.text.TextUtils;
    164 import android.util.ArraySet;
    165 import android.util.AtomicFile;
    166 import android.util.DisplayMetrics;
    167 import android.util.EventLog;
    168 import android.util.ExceptionUtils;
    169 import android.util.Log;
    170 import android.util.LogPrinter;
    171 import android.util.PrintStreamPrinter;
    172 import android.util.Slog;
    173 import android.util.SparseArray;
    174 import android.util.SparseBooleanArray;
    175 import android.view.Display;
    176 
    177 import java.io.BufferedInputStream;
    178 import java.io.BufferedOutputStream;
    179 import java.io.BufferedReader;
    180 import java.io.File;
    181 import java.io.FileDescriptor;
    182 import java.io.FileInputStream;
    183 import java.io.FileNotFoundException;
    184 import java.io.FileOutputStream;
    185 import java.io.FileReader;
    186 import java.io.FilenameFilter;
    187 import java.io.IOException;
    188 import java.io.InputStream;
    189 import java.io.PrintWriter;
    190 import java.nio.charset.StandardCharsets;
    191 import java.security.NoSuchAlgorithmException;
    192 import java.security.PublicKey;
    193 import java.security.cert.CertificateEncodingException;
    194 import java.security.cert.CertificateException;
    195 import java.text.SimpleDateFormat;
    196 import java.util.ArrayList;
    197 import java.util.Arrays;
    198 import java.util.Collection;
    199 import java.util.Collections;
    200 import java.util.Comparator;
    201 import java.util.Date;
    202 import java.util.HashMap;
    203 import java.util.HashSet;
    204 import java.util.Iterator;
    205 import java.util.List;
    206 import java.util.Map;
    207 import java.util.Objects;
    208 import java.util.Set;
    209 import java.util.concurrent.atomic.AtomicBoolean;
    210 import java.util.concurrent.atomic.AtomicLong;
    211 
    212 import dalvik.system.DexFile;
    213 import dalvik.system.StaleDexCacheError;
    214 import dalvik.system.VMRuntime;
    215 
    216 import libcore.io.IoUtils;
    217 import libcore.util.EmptyArray;
    218 
    219 /**
    220  * Keep track of all those .apks everywhere.
    221  *
    222  * This is very central to the platform's security; please run the unit
    223  * tests whenever making modifications here:
    224  *
    225 mmm frameworks/base/tests/AndroidTests
    226 adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
    227 adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
    228  *
    229  * {@hide}
    230  */
    231 public class PackageManagerService extends IPackageManager.Stub {
    232     static final String TAG = "PackageManager";
    233     static final boolean DEBUG_SETTINGS = false;
    234     static final boolean DEBUG_PREFERRED = false;
    235     static final boolean DEBUG_UPGRADE = false;
    236     private static final boolean DEBUG_INSTALL = false;
    237     private static final boolean DEBUG_REMOVE = false;
    238     private static final boolean DEBUG_BROADCASTS = false;
    239     private static final boolean DEBUG_SHOW_INFO = false;
    240     private static final boolean DEBUG_PACKAGE_INFO = false;
    241     private static final boolean DEBUG_INTENT_MATCHING = false;
    242     private static final boolean DEBUG_PACKAGE_SCANNING = false;
    243     private static final boolean DEBUG_VERIFY = false;
    244     private static final boolean DEBUG_DEXOPT = false;
    245     private static final boolean DEBUG_ABI_SELECTION = false;
    246 
    247     private static final int RADIO_UID = Process.PHONE_UID;
    248     private static final int LOG_UID = Process.LOG_UID;
    249     private static final int NFC_UID = Process.NFC_UID;
    250     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
    251     private static final int SHELL_UID = Process.SHELL_UID;
    252 
    253     // Cap the size of permission trees that 3rd party apps can define
    254     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
    255 
    256     // Suffix used during package installation when copying/moving
    257     // package apks to install directory.
    258     private static final String INSTALL_PACKAGE_SUFFIX = "-";
    259 
    260     static final int SCAN_NO_DEX = 1<<1;
    261     static final int SCAN_FORCE_DEX = 1<<2;
    262     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
    263     static final int SCAN_NEW_INSTALL = 1<<4;
    264     static final int SCAN_NO_PATHS = 1<<5;
    265     static final int SCAN_UPDATE_TIME = 1<<6;
    266     static final int SCAN_DEFER_DEX = 1<<7;
    267     static final int SCAN_BOOTING = 1<<8;
    268     static final int SCAN_TRUSTED_OVERLAY = 1<<9;
    269     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
    270     static final int SCAN_REPLACING = 1<<11;
    271 
    272     static final int REMOVE_CHATTY = 1<<16;
    273 
    274     /**
    275      * Timeout (in milliseconds) after which the watchdog should declare that
    276      * our handler thread is wedged.  The usual default for such things is one
    277      * minute but we sometimes do very lengthy I/O operations on this thread,
    278      * such as installing multi-gigabyte applications, so ours needs to be longer.
    279      */
    280     private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
    281 
    282     /**
    283      * Whether verification is enabled by default.
    284      */
    285     private static final boolean DEFAULT_VERIFY_ENABLE = true;
    286 
    287     /**
    288      * The default maximum time to wait for the verification agent to return in
    289      * milliseconds.
    290      */
    291     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
    292 
    293     /**
    294      * The default response for package verification timeout.
    295      *
    296      * This can be either PackageManager.VERIFICATION_ALLOW or
    297      * PackageManager.VERIFICATION_REJECT.
    298      */
    299     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
    300 
    301     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
    302 
    303     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
    304             DEFAULT_CONTAINER_PACKAGE,
    305             "com.android.defcontainer.DefaultContainerService");
    306 
    307     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
    308 
    309     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
    310 
    311     private static String sPreferredInstructionSet;
    312 
    313     final ServiceThread mHandlerThread;
    314 
    315     private static final String IDMAP_PREFIX = "/data/resource-cache/";
    316     private static final String IDMAP_SUFFIX = "@idmap";
    317 
    318     final PackageHandler mHandler;
    319 
    320     /**
    321      * Messages for {@link #mHandler} that need to wait for system ready before
    322      * being dispatched.
    323      */
    324     private ArrayList<Message> mPostSystemReadyMessages;
    325 
    326     final int mSdkVersion = Build.VERSION.SDK_INT;
    327 
    328     final Context mContext;
    329     final boolean mFactoryTest;
    330     final boolean mOnlyCore;
    331     final boolean mLazyDexOpt;
    332     final DisplayMetrics mMetrics;
    333     final int mDefParseFlags;
    334     final String[] mSeparateProcesses;
    335 
    336     // This is where all application persistent data goes.
    337     final File mAppDataDir;
    338 
    339     // This is where all application persistent data goes for secondary users.
    340     final File mUserAppDataDir;
    341 
    342     /** The location for ASEC container files on internal storage. */
    343     final String mAsecInternalPath;
    344 
    345     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
    346     // LOCK HELD.  Can be called with mInstallLock held.
    347     final Installer mInstaller;
    348 
    349     /** Directory where installed third-party apps stored */
    350     final File mAppInstallDir;
    351 
    352     /**
    353      * Directory to which applications installed internally have their
    354      * 32 bit native libraries copied.
    355      */
    356     private File mAppLib32InstallDir;
    357 
    358     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
    359     // apps.
    360     final File mDrmAppPrivateInstallDir;
    361 
    362     // ----------------------------------------------------------------
    363 
    364     // Lock for state used when installing and doing other long running
    365     // operations.  Methods that must be called with this lock held have
    366     // the suffix "LI".
    367     final Object mInstallLock = new Object();
    368 
    369     // ----------------------------------------------------------------
    370 
    371     // Keys are String (package name), values are Package.  This also serves
    372     // as the lock for the global state.  Methods that must be called with
    373     // this lock held have the prefix "LP".
    374     final HashMap<String, PackageParser.Package> mPackages =
    375             new HashMap<String, PackageParser.Package>();
    376 
    377     // Tracks available target package names -> overlay package paths.
    378     final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
    379         new HashMap<String, HashMap<String, PackageParser.Package>>();
    380 
    381     final Settings mSettings;
    382     boolean mRestoredSettings;
    383 
    384     // System configuration read by SystemConfig.
    385     final int[] mGlobalGids;
    386     final SparseArray<HashSet<String>> mSystemPermissions;
    387     final HashMap<String, FeatureInfo> mAvailableFeatures;
    388 
    389     // If mac_permissions.xml was found for seinfo labeling.
    390     boolean mFoundPolicyFile;
    391 
    392     // If a recursive restorecon of /data/data/<pkg> is needed.
    393     private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
    394 
    395     public static final class SharedLibraryEntry {
    396         public final String path;
    397         public final String apk;
    398 
    399         SharedLibraryEntry(String _path, String _apk) {
    400             path = _path;
    401             apk = _apk;
    402         }
    403     }
    404 
    405     // Currently known shared libraries.
    406     final HashMap<String, SharedLibraryEntry> mSharedLibraries =
    407             new HashMap<String, SharedLibraryEntry>();
    408 
    409     // All available activities, for your resolving pleasure.
    410     final ActivityIntentResolver mActivities =
    411             new ActivityIntentResolver();
    412 
    413     // All available receivers, for your resolving pleasure.
    414     final ActivityIntentResolver mReceivers =
    415             new ActivityIntentResolver();
    416 
    417     // All available services, for your resolving pleasure.
    418     final ServiceIntentResolver mServices = new ServiceIntentResolver();
    419 
    420     // All available providers, for your resolving pleasure.
    421     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
    422 
    423     // Mapping from provider base names (first directory in content URI codePath)
    424     // to the provider information.
    425     final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
    426             new HashMap<String, PackageParser.Provider>();
    427 
    428     // Mapping from instrumentation class names to info about them.
    429     final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
    430             new HashMap<ComponentName, PackageParser.Instrumentation>();
    431 
    432     // Mapping from permission names to info about them.
    433     final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
    434             new HashMap<String, PackageParser.PermissionGroup>();
    435 
    436     // Packages whose data we have transfered into another package, thus
    437     // should no longer exist.
    438     final HashSet<String> mTransferedPackages = new HashSet<String>();
    439 
    440     // Broadcast actions that are only available to the system.
    441     final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
    442 
    443     /** List of packages waiting for verification. */
    444     final SparseArray<PackageVerificationState> mPendingVerification
    445             = new SparseArray<PackageVerificationState>();
    446 
    447     /** Set of packages associated with each app op permission. */
    448     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
    449 
    450     final PackageInstallerService mInstallerService;
    451 
    452     HashSet<PackageParser.Package> mDeferredDexOpt = null;
    453 
    454     // Cache of users who need badging.
    455     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
    456 
    457     /** Token for keys in mPendingVerification. */
    458     private int mPendingVerificationToken = 0;
    459 
    460     volatile boolean mSystemReady;
    461     volatile boolean mSafeMode;
    462     volatile boolean mHasSystemUidErrors;
    463 
    464     ApplicationInfo mAndroidApplication;
    465     final ActivityInfo mResolveActivity = new ActivityInfo();
    466     final ResolveInfo mResolveInfo = new ResolveInfo();
    467     ComponentName mResolveComponentName;
    468     PackageParser.Package mPlatformPackage;
    469     ComponentName mCustomResolverComponentName;
    470 
    471     boolean mResolverReplaced = false;
    472 
    473     // Set of pending broadcasts for aggregating enable/disable of components.
    474     static class PendingPackageBroadcasts {
    475         // for each user id, a map of <package name -> components within that package>
    476         final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
    477 
    478         public PendingPackageBroadcasts() {
    479             mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
    480         }
    481 
    482         public ArrayList<String> get(int userId, String packageName) {
    483             HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
    484             return packages.get(packageName);
    485         }
    486 
    487         public void put(int userId, String packageName, ArrayList<String> components) {
    488             HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
    489             packages.put(packageName, components);
    490         }
    491 
    492         public void remove(int userId, String packageName) {
    493             HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
    494             if (packages != null) {
    495                 packages.remove(packageName);
    496             }
    497         }
    498 
    499         public void remove(int userId) {
    500             mUidMap.remove(userId);
    501         }
    502 
    503         public int userIdCount() {
    504             return mUidMap.size();
    505         }
    506 
    507         public int userIdAt(int n) {
    508             return mUidMap.keyAt(n);
    509         }
    510 
    511         public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
    512             return mUidMap.get(userId);
    513         }
    514 
    515         public int size() {
    516             // total number of pending broadcast entries across all userIds
    517             int num = 0;
    518             for (int i = 0; i< mUidMap.size(); i++) {
    519                 num += mUidMap.valueAt(i).size();
    520             }
    521             return num;
    522         }
    523 
    524         public void clear() {
    525             mUidMap.clear();
    526         }
    527 
    528         private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
    529             HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
    530             if (map == null) {
    531                 map = new HashMap<String, ArrayList<String>>();
    532                 mUidMap.put(userId, map);
    533             }
    534             return map;
    535         }
    536     }
    537     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
    538 
    539     // Service Connection to remote media container service to copy
    540     // package uri's from external media onto secure containers
    541     // or internal storage.
    542     private IMediaContainerService mContainerService = null;
    543 
    544     static final int SEND_PENDING_BROADCAST = 1;
    545     static final int MCS_BOUND = 3;
    546     static final int END_COPY = 4;
    547     static final int INIT_COPY = 5;
    548     static final int MCS_UNBIND = 6;
    549     static final int START_CLEANING_PACKAGE = 7;
    550     static final int FIND_INSTALL_LOC = 8;
    551     static final int POST_INSTALL = 9;
    552     static final int MCS_RECONNECT = 10;
    553     static final int MCS_GIVE_UP = 11;
    554     static final int UPDATED_MEDIA_STATUS = 12;
    555     static final int WRITE_SETTINGS = 13;
    556     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
    557     static final int PACKAGE_VERIFIED = 15;
    558     static final int CHECK_PENDING_VERIFICATION = 16;
    559 
    560     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
    561 
    562     // Delay time in millisecs
    563     static final int BROADCAST_DELAY = 10 * 1000;
    564 
    565     static UserManagerService sUserManager;
    566 
    567     // Stores a list of users whose package restrictions file needs to be updated
    568     private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
    569 
    570     final private DefaultContainerConnection mDefContainerConn =
    571             new DefaultContainerConnection();
    572     class DefaultContainerConnection implements ServiceConnection {
    573         public void onServiceConnected(ComponentName name, IBinder service) {
    574             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
    575             IMediaContainerService imcs =
    576                 IMediaContainerService.Stub.asInterface(service);
    577             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
    578         }
    579 
    580         public void onServiceDisconnected(ComponentName name) {
    581             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
    582         }
    583     };
    584 
    585     // Recordkeeping of restore-after-install operations that are currently in flight
    586     // between the Package Manager and the Backup Manager
    587     class PostInstallData {
    588         public InstallArgs args;
    589         public PackageInstalledInfo res;
    590 
    591         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
    592             args = _a;
    593             res = _r;
    594         }
    595     };
    596     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
    597     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
    598 
    599     private final String mRequiredVerifierPackage;
    600 
    601     private final PackageUsage mPackageUsage = new PackageUsage();
    602 
    603     private class PackageUsage {
    604         private static final int WRITE_INTERVAL
    605             = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
    606 
    607         private final Object mFileLock = new Object();
    608         private final AtomicLong mLastWritten = new AtomicLong(0);
    609         private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
    610 
    611         private boolean mIsHistoricalPackageUsageAvailable = true;
    612 
    613         boolean isHistoricalPackageUsageAvailable() {
    614             return mIsHistoricalPackageUsageAvailable;
    615         }
    616 
    617         void write(boolean force) {
    618             if (force) {
    619                 writeInternal();
    620                 return;
    621             }
    622             if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
    623                 && !DEBUG_DEXOPT) {
    624                 return;
    625             }
    626             if (mBackgroundWriteRunning.compareAndSet(false, true)) {
    627                 new Thread("PackageUsage_DiskWriter") {
    628                     @Override
    629                     public void run() {
    630                         try {
    631                             writeInternal();
    632                         } finally {
    633                             mBackgroundWriteRunning.set(false);
    634                         }
    635                     }
    636                 }.start();
    637             }
    638         }
    639 
    640         private void writeInternal() {
    641             synchronized (mPackages) {
    642                 synchronized (mFileLock) {
    643                     AtomicFile file = getFile();
    644                     FileOutputStream f = null;
    645                     try {
    646                         f = file.startWrite();
    647                         BufferedOutputStream out = new BufferedOutputStream(f);
    648                         FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
    649                         StringBuilder sb = new StringBuilder();
    650                         for (PackageParser.Package pkg : mPackages.values()) {
    651                             if (pkg.mLastPackageUsageTimeInMills == 0) {
    652                                 continue;
    653                             }
    654                             sb.setLength(0);
    655                             sb.append(pkg.packageName);
    656                             sb.append(' ');
    657                             sb.append((long)pkg.mLastPackageUsageTimeInMills);
    658                             sb.append('\n');
    659                             out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
    660                         }
    661                         out.flush();
    662                         file.finishWrite(f);
    663                     } catch (IOException e) {
    664                         if (f != null) {
    665                             file.failWrite(f);
    666                         }
    667                         Log.e(TAG, "Failed to write package usage times", e);
    668                     }
    669                 }
    670             }
    671             mLastWritten.set(SystemClock.elapsedRealtime());
    672         }
    673 
    674         void readLP() {
    675             synchronized (mFileLock) {
    676                 AtomicFile file = getFile();
    677                 BufferedInputStream in = null;
    678                 try {
    679                     in = new BufferedInputStream(file.openRead());
    680                     StringBuffer sb = new StringBuffer();
    681                     while (true) {
    682                         String packageName = readToken(in, sb, ' ');
    683                         if (packageName == null) {
    684                             break;
    685                         }
    686                         String timeInMillisString = readToken(in, sb, '\n');
    687                         if (timeInMillisString == null) {
    688                             throw new IOException("Failed to find last usage time for package "
    689                                                   + packageName);
    690                         }
    691                         PackageParser.Package pkg = mPackages.get(packageName);
    692                         if (pkg == null) {
    693                             continue;
    694                         }
    695                         long timeInMillis;
    696                         try {
    697                             timeInMillis = Long.parseLong(timeInMillisString.toString());
    698                         } catch (NumberFormatException e) {
    699                             throw new IOException("Failed to parse " + timeInMillisString
    700                                                   + " as a long.", e);
    701                         }
    702                         pkg.mLastPackageUsageTimeInMills = timeInMillis;
    703                     }
    704                 } catch (FileNotFoundException expected) {
    705                     mIsHistoricalPackageUsageAvailable = false;
    706                 } catch (IOException e) {
    707                     Log.w(TAG, "Failed to read package usage times", e);
    708                 } finally {
    709                     IoUtils.closeQuietly(in);
    710                 }
    711             }
    712             mLastWritten.set(SystemClock.elapsedRealtime());
    713         }
    714 
    715         private String readToken(InputStream in, StringBuffer sb, char endOfToken)
    716                 throws IOException {
    717             sb.setLength(0);
    718             while (true) {
    719                 int ch = in.read();
    720                 if (ch == -1) {
    721                     if (sb.length() == 0) {
    722                         return null;
    723                     }
    724                     throw new IOException("Unexpected EOF");
    725                 }
    726                 if (ch == endOfToken) {
    727                     return sb.toString();
    728                 }
    729                 sb.append((char)ch);
    730             }
    731         }
    732 
    733         private AtomicFile getFile() {
    734             File dataDir = Environment.getDataDirectory();
    735             File systemDir = new File(dataDir, "system");
    736             File fname = new File(systemDir, "package-usage.list");
    737             return new AtomicFile(fname);
    738         }
    739     }
    740 
    741     class PackageHandler extends Handler {
    742         private boolean mBound = false;
    743         final ArrayList<HandlerParams> mPendingInstalls =
    744             new ArrayList<HandlerParams>();
    745 
    746         private boolean connectToService() {
    747             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
    748                     " DefaultContainerService");
    749             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
    750             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
    751             if (mContext.bindServiceAsUser(service, mDefContainerConn,
    752                     Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
    753                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    754                 mBound = true;
    755                 return true;
    756             }
    757             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    758             return false;
    759         }
    760 
    761         private void disconnectService() {
    762             mContainerService = null;
    763             mBound = false;
    764             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
    765             mContext.unbindService(mDefContainerConn);
    766             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    767         }
    768 
    769         PackageHandler(Looper looper) {
    770             super(looper);
    771         }
    772 
    773         public void handleMessage(Message msg) {
    774             try {
    775                 doHandleMessage(msg);
    776             } finally {
    777                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    778             }
    779         }
    780 
    781         void doHandleMessage(Message msg) {
    782             switch (msg.what) {
    783                 case INIT_COPY: {
    784                     HandlerParams params = (HandlerParams) msg.obj;
    785                     int idx = mPendingInstalls.size();
    786                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
    787                     // If a bind was already initiated we dont really
    788                     // need to do anything. The pending install
    789                     // will be processed later on.
    790                     if (!mBound) {
    791                         // If this is the only one pending we might
    792                         // have to bind to the service again.
    793                         if (!connectToService()) {
    794                             Slog.e(TAG, "Failed to bind to media container service");
    795                             params.serviceError();
    796                             return;
    797                         } else {
    798                             // Once we bind to the service, the first
    799                             // pending request will be processed.
    800                             mPendingInstalls.add(idx, params);
    801                         }
    802                     } else {
    803                         mPendingInstalls.add(idx, params);
    804                         // Already bound to the service. Just make
    805                         // sure we trigger off processing the first request.
    806                         if (idx == 0) {
    807                             mHandler.sendEmptyMessage(MCS_BOUND);
    808                         }
    809                     }
    810                     break;
    811                 }
    812                 case MCS_BOUND: {
    813                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
    814                     if (msg.obj != null) {
    815                         mContainerService = (IMediaContainerService) msg.obj;
    816                     }
    817                     if (mContainerService == null) {
    818                         // Something seriously wrong. Bail out
    819                         Slog.e(TAG, "Cannot bind to media container service");
    820                         for (HandlerParams params : mPendingInstalls) {
    821                             // Indicate service bind error
    822                             params.serviceError();
    823                         }
    824                         mPendingInstalls.clear();
    825                     } else if (mPendingInstalls.size() > 0) {
    826                         HandlerParams params = mPendingInstalls.get(0);
    827                         if (params != null) {
    828                             if (params.startCopy()) {
    829                                 // We are done...  look for more work or to
    830                                 // go idle.
    831                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
    832                                         "Checking for more work or unbind...");
    833                                 // Delete pending install
    834                                 if (mPendingInstalls.size() > 0) {
    835                                     mPendingInstalls.remove(0);
    836                                 }
    837                                 if (mPendingInstalls.size() == 0) {
    838                                     if (mBound) {
    839                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
    840                                                 "Posting delayed MCS_UNBIND");
    841                                         removeMessages(MCS_UNBIND);
    842                                         Message ubmsg = obtainMessage(MCS_UNBIND);
    843                                         // Unbind after a little delay, to avoid
    844                                         // continual thrashing.
    845                                         sendMessageDelayed(ubmsg, 10000);
    846                                     }
    847                                 } else {
    848                                     // There are more pending requests in queue.
    849                                     // Just post MCS_BOUND message to trigger processing
    850                                     // of next pending install.
    851                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
    852                                             "Posting MCS_BOUND for next work");
    853                                     mHandler.sendEmptyMessage(MCS_BOUND);
    854                                 }
    855                             }
    856                         }
    857                     } else {
    858                         // Should never happen ideally.
    859                         Slog.w(TAG, "Empty queue");
    860                     }
    861                     break;
    862                 }
    863                 case MCS_RECONNECT: {
    864                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
    865                     if (mPendingInstalls.size() > 0) {
    866                         if (mBound) {
    867                             disconnectService();
    868                         }
    869                         if (!connectToService()) {
    870                             Slog.e(TAG, "Failed to bind to media container service");
    871                             for (HandlerParams params : mPendingInstalls) {
    872                                 // Indicate service bind error
    873                                 params.serviceError();
    874                             }
    875                             mPendingInstalls.clear();
    876                         }
    877                     }
    878                     break;
    879                 }
    880                 case MCS_UNBIND: {
    881                     // If there is no actual work left, then time to unbind.
    882                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
    883 
    884                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
    885                         if (mBound) {
    886                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
    887 
    888                             disconnectService();
    889                         }
    890                     } else if (mPendingInstalls.size() > 0) {
    891                         // There are more pending requests in queue.
    892                         // Just post MCS_BOUND message to trigger processing
    893                         // of next pending install.
    894                         mHandler.sendEmptyMessage(MCS_BOUND);
    895                     }
    896 
    897                     break;
    898                 }
    899                 case MCS_GIVE_UP: {
    900                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
    901                     mPendingInstalls.remove(0);
    902                     break;
    903                 }
    904                 case SEND_PENDING_BROADCAST: {
    905                     String packages[];
    906                     ArrayList<String> components[];
    907                     int size = 0;
    908                     int uids[];
    909                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
    910                     synchronized (mPackages) {
    911                         if (mPendingBroadcasts == null) {
    912                             return;
    913                         }
    914                         size = mPendingBroadcasts.size();
    915                         if (size <= 0) {
    916                             // Nothing to be done. Just return
    917                             return;
    918                         }
    919                         packages = new String[size];
    920                         components = new ArrayList[size];
    921                         uids = new int[size];
    922                         int i = 0;  // filling out the above arrays
    923 
    924                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
    925                             int packageUserId = mPendingBroadcasts.userIdAt(n);
    926                             Iterator<Map.Entry<String, ArrayList<String>>> it
    927                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
    928                                             .entrySet().iterator();
    929                             while (it.hasNext() && i < size) {
    930                                 Map.Entry<String, ArrayList<String>> ent = it.next();
    931                                 packages[i] = ent.getKey();
    932                                 components[i] = ent.getValue();
    933                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
    934                                 uids[i] = (ps != null)
    935                                         ? UserHandle.getUid(packageUserId, ps.appId)
    936                                         : -1;
    937                                 i++;
    938                             }
    939                         }
    940                         size = i;
    941                         mPendingBroadcasts.clear();
    942                     }
    943                     // Send broadcasts
    944                     for (int i = 0; i < size; i++) {
    945                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
    946                     }
    947                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    948                     break;
    949                 }
    950                 case START_CLEANING_PACKAGE: {
    951                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
    952                     final String packageName = (String)msg.obj;
    953                     final int userId = msg.arg1;
    954                     final boolean andCode = msg.arg2 != 0;
    955                     synchronized (mPackages) {
    956                         if (userId == UserHandle.USER_ALL) {
    957                             int[] users = sUserManager.getUserIds();
    958                             for (int user : users) {
    959                                 mSettings.addPackageToCleanLPw(
    960                                         new PackageCleanItem(user, packageName, andCode));
    961                             }
    962                         } else {
    963                             mSettings.addPackageToCleanLPw(
    964                                     new PackageCleanItem(userId, packageName, andCode));
    965                         }
    966                     }
    967                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    968                     startCleaningPackages();
    969                 } break;
    970                 case POST_INSTALL: {
    971                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
    972                     PostInstallData data = mRunningInstalls.get(msg.arg1);
    973                     mRunningInstalls.delete(msg.arg1);
    974                     boolean deleteOld = false;
    975 
    976                     if (data != null) {
    977                         InstallArgs args = data.args;
    978                         PackageInstalledInfo res = data.res;
    979 
    980                         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
    981                             res.removedInfo.sendBroadcast(false, true, false);
    982                             Bundle extras = new Bundle(1);
    983                             extras.putInt(Intent.EXTRA_UID, res.uid);
    984                             // Determine the set of users who are adding this
    985                             // package for the first time vs. those who are seeing
    986                             // an update.
    987                             int[] firstUsers;
    988                             int[] updateUsers = new int[0];
    989                             if (res.origUsers == null || res.origUsers.length == 0) {
    990                                 firstUsers = res.newUsers;
    991                             } else {
    992                                 firstUsers = new int[0];
    993                                 for (int i=0; i<res.newUsers.length; i++) {
    994                                     int user = res.newUsers[i];
    995                                     boolean isNew = true;
    996                                     for (int j=0; j<res.origUsers.length; j++) {
    997                                         if (res.origUsers[j] == user) {
    998                                             isNew = false;
    999                                             break;
   1000                                         }
   1001                                     }
   1002                                     if (isNew) {
   1003                                         int[] newFirst = new int[firstUsers.length+1];
   1004                                         System.arraycopy(firstUsers, 0, newFirst, 0,
   1005                                                 firstUsers.length);
   1006                                         newFirst[firstUsers.length] = user;
   1007                                         firstUsers = newFirst;
   1008                                     } else {
   1009                                         int[] newUpdate = new int[updateUsers.length+1];
   1010                                         System.arraycopy(updateUsers, 0, newUpdate, 0,
   1011                                                 updateUsers.length);
   1012                                         newUpdate[updateUsers.length] = user;
   1013                                         updateUsers = newUpdate;
   1014                                     }
   1015                                 }
   1016                             }
   1017                             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
   1018                                     res.pkg.applicationInfo.packageName,
   1019                                     extras, null, null, firstUsers);
   1020                             final boolean update = res.removedInfo.removedPackage != null;
   1021                             if (update) {
   1022                                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
   1023                             }
   1024                             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
   1025                                     res.pkg.applicationInfo.packageName,
   1026                                     extras, null, null, updateUsers);
   1027                             if (update) {
   1028                                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
   1029                                         res.pkg.applicationInfo.packageName,
   1030                                         extras, null, null, updateUsers);
   1031                                 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
   1032                                         null, null,
   1033                                         res.pkg.applicationInfo.packageName, null, updateUsers);
   1034 
   1035                                 // treat asec-hosted packages like removable media on upgrade
   1036                                 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
   1037                                     if (DEBUG_INSTALL) {
   1038                                         Slog.i(TAG, "upgrading pkg " + res.pkg
   1039                                                 + " is ASEC-hosted -> AVAILABLE");
   1040                                     }
   1041                                     int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
   1042                                     ArrayList<String> pkgList = new ArrayList<String>(1);
   1043                                     pkgList.add(res.pkg.applicationInfo.packageName);
   1044                                     sendResourcesChangedBroadcast(true, true,
   1045                                             pkgList,uidArray, null);
   1046                                 }
   1047                             }
   1048                             if (res.removedInfo.args != null) {
   1049                                 // Remove the replaced package's older resources safely now
   1050                                 deleteOld = true;
   1051                             }
   1052 
   1053                             // Log current value of "unknown sources" setting
   1054                             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
   1055                                 getUnknownSourcesSettings());
   1056                         }
   1057                         // Force a gc to clear up things
   1058                         Runtime.getRuntime().gc();
   1059                         // We delete after a gc for applications  on sdcard.
   1060                         if (deleteOld) {
   1061                             synchronized (mInstallLock) {
   1062                                 res.removedInfo.args.doPostDeleteLI(true);
   1063                             }
   1064                         }
   1065                         if (args.observer != null) {
   1066                             try {
   1067                                 Bundle extras = extrasForInstallResult(res);
   1068                                 args.observer.onPackageInstalled(res.name, res.returnCode,
   1069                                         res.returnMsg, extras);
   1070                             } catch (RemoteException e) {
   1071                                 Slog.i(TAG, "Observer no longer exists.");
   1072                             }
   1073                         }
   1074                     } else {
   1075                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
   1076                     }
   1077                 } break;
   1078                 case UPDATED_MEDIA_STATUS: {
   1079                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
   1080                     boolean reportStatus = msg.arg1 == 1;
   1081                     boolean doGc = msg.arg2 == 1;
   1082                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
   1083                     if (doGc) {
   1084                         // Force a gc to clear up stale containers.
   1085                         Runtime.getRuntime().gc();
   1086                     }
   1087                     if (msg.obj != null) {
   1088                         @SuppressWarnings("unchecked")
   1089                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
   1090                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
   1091                         // Unload containers
   1092                         unloadAllContainers(args);
   1093                     }
   1094                     if (reportStatus) {
   1095                         try {
   1096                             if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
   1097                             PackageHelper.getMountService().finishMediaUpdate();
   1098                         } catch (RemoteException e) {
   1099                             Log.e(TAG, "MountService not running?");
   1100                         }
   1101                     }
   1102                 } break;
   1103                 case WRITE_SETTINGS: {
   1104                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1105                     synchronized (mPackages) {
   1106                         removeMessages(WRITE_SETTINGS);
   1107                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   1108                         mSettings.writeLPr();
   1109                         mDirtyUsers.clear();
   1110                     }
   1111                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1112                 } break;
   1113                 case WRITE_PACKAGE_RESTRICTIONS: {
   1114                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
   1115                     synchronized (mPackages) {
   1116                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
   1117                         for (int userId : mDirtyUsers) {
   1118                             mSettings.writePackageRestrictionsLPr(userId);
   1119                         }
   1120                         mDirtyUsers.clear();
   1121                     }
   1122                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
   1123                 } break;
   1124                 case CHECK_PENDING_VERIFICATION: {
   1125                     final int verificationId = msg.arg1;
   1126                     final PackageVerificationState state = mPendingVerification.get(verificationId);
   1127 
   1128                     if ((state != null) && !state.timeoutExtended()) {
   1129                         final InstallArgs args = state.getInstallArgs();
   1130                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
   1131 
   1132                         Slog.i(TAG, "Verification timed out for " + originUri);
   1133                         mPendingVerification.remove(verificationId);
   1134 
   1135                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   1136 
   1137                         if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
   1138                             Slog.i(TAG, "Continuing with installation of " + originUri);
   1139                             state.setVerifierResponse(Binder.getCallingUid(),
   1140                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
   1141                             broadcastPackageVerified(verificationId, originUri,
   1142                                     PackageManager.VERIFICATION_ALLOW,
   1143                                     state.getInstallArgs().getUser());
   1144                             try {
   1145                                 ret = args.copyApk(mContainerService, true);
   1146                             } catch (RemoteException e) {
   1147                                 Slog.e(TAG, "Could not contact the ContainerService");
   1148                             }
   1149                         } else {
   1150                             broadcastPackageVerified(verificationId, originUri,
   1151                                     PackageManager.VERIFICATION_REJECT,
   1152                                     state.getInstallArgs().getUser());
   1153                         }
   1154 
   1155                         processPendingInstall(args, ret);
   1156                         mHandler.sendEmptyMessage(MCS_UNBIND);
   1157                     }
   1158                     break;
   1159                 }
   1160                 case PACKAGE_VERIFIED: {
   1161                     final int verificationId = msg.arg1;
   1162 
   1163                     final PackageVerificationState state = mPendingVerification.get(verificationId);
   1164                     if (state == null) {
   1165                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
   1166                         break;
   1167                     }
   1168 
   1169                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
   1170 
   1171                     state.setVerifierResponse(response.callerUid, response.code);
   1172 
   1173                     if (state.isVerificationComplete()) {
   1174                         mPendingVerification.remove(verificationId);
   1175 
   1176                         final InstallArgs args = state.getInstallArgs();
   1177                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
   1178 
   1179                         int ret;
   1180                         if (state.isInstallAllowed()) {
   1181                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   1182                             broadcastPackageVerified(verificationId, originUri,
   1183                                     response.code, state.getInstallArgs().getUser());
   1184                             try {
   1185                                 ret = args.copyApk(mContainerService, true);
   1186                             } catch (RemoteException e) {
   1187                                 Slog.e(TAG, "Could not contact the ContainerService");
   1188                             }
   1189                         } else {
   1190                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   1191                         }
   1192 
   1193                         processPendingInstall(args, ret);
   1194 
   1195                         mHandler.sendEmptyMessage(MCS_UNBIND);
   1196                     }
   1197 
   1198                     break;
   1199                 }
   1200             }
   1201         }
   1202     }
   1203 
   1204     Bundle extrasForInstallResult(PackageInstalledInfo res) {
   1205         Bundle extras = null;
   1206         switch (res.returnCode) {
   1207             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
   1208                 extras = new Bundle();
   1209                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
   1210                         res.origPermission);
   1211                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
   1212                         res.origPackage);
   1213                 break;
   1214             }
   1215         }
   1216         return extras;
   1217     }
   1218 
   1219     void scheduleWriteSettingsLocked() {
   1220         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
   1221             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
   1222         }
   1223     }
   1224 
   1225     void scheduleWritePackageRestrictionsLocked(int userId) {
   1226         if (!sUserManager.exists(userId)) return;
   1227         mDirtyUsers.add(userId);
   1228         if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
   1229             mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
   1230         }
   1231     }
   1232 
   1233     public static final PackageManagerService main(Context context, Installer installer,
   1234             boolean factoryTest, boolean onlyCore) {
   1235         PackageManagerService m = new PackageManagerService(context, installer,
   1236                 factoryTest, onlyCore);
   1237         ServiceManager.addService("package", m);
   1238         return m;
   1239     }
   1240 
   1241     static String[] splitString(String str, char sep) {
   1242         int count = 1;
   1243         int i = 0;
   1244         while ((i=str.indexOf(sep, i)) >= 0) {
   1245             count++;
   1246             i++;
   1247         }
   1248 
   1249         String[] res = new String[count];
   1250         i=0;
   1251         count = 0;
   1252         int lastI=0;
   1253         while ((i=str.indexOf(sep, i)) >= 0) {
   1254             res[count] = str.substring(lastI, i);
   1255             count++;
   1256             i++;
   1257             lastI = i;
   1258         }
   1259         res[count] = str.substring(lastI, str.length());
   1260         return res;
   1261     }
   1262 
   1263     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
   1264         DisplayManager displayManager = (DisplayManager) context.getSystemService(
   1265                 Context.DISPLAY_SERVICE);
   1266         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
   1267     }
   1268 
   1269     public PackageManagerService(Context context, Installer installer,
   1270             boolean factoryTest, boolean onlyCore) {
   1271         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
   1272                 SystemClock.uptimeMillis());
   1273 
   1274         if (mSdkVersion <= 0) {
   1275             Slog.w(TAG, "**** ro.build.version.sdk not set!");
   1276         }
   1277 
   1278         mContext = context;
   1279         mFactoryTest = factoryTest;
   1280         mOnlyCore = onlyCore;
   1281         mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
   1282         mMetrics = new DisplayMetrics();
   1283         mSettings = new Settings(context);
   1284         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
   1285                 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
   1286         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
   1287                 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
   1288         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
   1289                 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
   1290         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
   1291                 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
   1292         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
   1293                 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
   1294         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
   1295                 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
   1296 
   1297         String separateProcesses = SystemProperties.get("debug.separate_processes");
   1298         if (separateProcesses != null && separateProcesses.length() > 0) {
   1299             if ("*".equals(separateProcesses)) {
   1300                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
   1301                 mSeparateProcesses = null;
   1302                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
   1303             } else {
   1304                 mDefParseFlags = 0;
   1305                 mSeparateProcesses = separateProcesses.split(",");
   1306                 Slog.w(TAG, "Running with debug.separate_processes: "
   1307                         + separateProcesses);
   1308             }
   1309         } else {
   1310             mDefParseFlags = 0;
   1311             mSeparateProcesses = null;
   1312         }
   1313 
   1314         mInstaller = installer;
   1315 
   1316         getDefaultDisplayMetrics(context, mMetrics);
   1317 
   1318         SystemConfig systemConfig = SystemConfig.getInstance();
   1319         mGlobalGids = systemConfig.getGlobalGids();
   1320         mSystemPermissions = systemConfig.getSystemPermissions();
   1321         mAvailableFeatures = systemConfig.getAvailableFeatures();
   1322 
   1323         synchronized (mInstallLock) {
   1324         // writer
   1325         synchronized (mPackages) {
   1326             mHandlerThread = new ServiceThread(TAG,
   1327                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
   1328             mHandlerThread.start();
   1329             mHandler = new PackageHandler(mHandlerThread.getLooper());
   1330             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
   1331 
   1332             File dataDir = Environment.getDataDirectory();
   1333             mAppDataDir = new File(dataDir, "data");
   1334             mAppInstallDir = new File(dataDir, "app");
   1335             mAppLib32InstallDir = new File(dataDir, "app-lib");
   1336             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
   1337             mUserAppDataDir = new File(dataDir, "user");
   1338             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
   1339 
   1340             sUserManager = new UserManagerService(context, this,
   1341                     mInstallLock, mPackages);
   1342 
   1343             // Propagate permission configuration in to package manager.
   1344             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
   1345                     = systemConfig.getPermissions();
   1346             for (int i=0; i<permConfig.size(); i++) {
   1347                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
   1348                 BasePermission bp = mSettings.mPermissions.get(perm.name);
   1349                 if (bp == null) {
   1350                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
   1351                     mSettings.mPermissions.put(perm.name, bp);
   1352                 }
   1353                 if (perm.gids != null) {
   1354                     bp.gids = appendInts(bp.gids, perm.gids);
   1355                 }
   1356             }
   1357 
   1358             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
   1359             for (int i=0; i<libConfig.size(); i++) {
   1360                 mSharedLibraries.put(libConfig.keyAt(i),
   1361                         new SharedLibraryEntry(libConfig.valueAt(i), null));
   1362             }
   1363 
   1364             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
   1365 
   1366             mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
   1367                     mSdkVersion, mOnlyCore);
   1368 
   1369             String customResolverActivity = Resources.getSystem().getString(
   1370                     R.string.config_customResolverActivity);
   1371             if (TextUtils.isEmpty(customResolverActivity)) {
   1372                 customResolverActivity = null;
   1373             } else {
   1374                 mCustomResolverComponentName = ComponentName.unflattenFromString(
   1375                         customResolverActivity);
   1376             }
   1377 
   1378             long startTime = SystemClock.uptimeMillis();
   1379 
   1380             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
   1381                     startTime);
   1382 
   1383             // Set flag to monitor and not change apk file paths when
   1384             // scanning install directories.
   1385             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
   1386 
   1387             final HashSet<String> alreadyDexOpted = new HashSet<String>();
   1388 
   1389             /**
   1390              * Add everything in the in the boot class path to the
   1391              * list of process files because dexopt will have been run
   1392              * if necessary during zygote startup.
   1393              */
   1394             final String bootClassPath = System.getenv("BOOTCLASSPATH");
   1395             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
   1396 
   1397             if (bootClassPath != null) {
   1398                 String[] bootClassPathElements = splitString(bootClassPath, ':');
   1399                 for (String element : bootClassPathElements) {
   1400                     alreadyDexOpted.add(element);
   1401                 }
   1402             } else {
   1403                 Slog.w(TAG, "No BOOTCLASSPATH found!");
   1404             }
   1405 
   1406             if (systemServerClassPath != null) {
   1407                 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
   1408                 for (String element : systemServerClassPathElements) {
   1409                     alreadyDexOpted.add(element);
   1410                 }
   1411             } else {
   1412                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
   1413             }
   1414 
   1415             boolean didDexOptLibraryOrTool = false;
   1416 
   1417             final List<String> allInstructionSets = getAllInstructionSets();
   1418             final String[] dexCodeInstructionSets =
   1419                 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
   1420 
   1421             /**
   1422              * Ensure all external libraries have had dexopt run on them.
   1423              */
   1424             if (mSharedLibraries.size() > 0) {
   1425                 // NOTE: For now, we're compiling these system "shared libraries"
   1426                 // (and framework jars) into all available architectures. It's possible
   1427                 // to compile them only when we come across an app that uses them (there's
   1428                 // already logic for that in scanPackageLI) but that adds some complexity.
   1429                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
   1430                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
   1431                         final String lib = libEntry.path;
   1432                         if (lib == null) {
   1433                             continue;
   1434                         }
   1435 
   1436                         try {
   1437                             byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
   1438                                                                                  dexCodeInstructionSet,
   1439                                                                                  false);
   1440                             if (dexoptRequired != DexFile.UP_TO_DATE) {
   1441                                 alreadyDexOpted.add(lib);
   1442 
   1443                                 // The list of "shared libraries" we have at this point is
   1444                                 if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
   1445                                     mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
   1446                                 } else {
   1447                                     mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
   1448                                 }
   1449                                 didDexOptLibraryOrTool = true;
   1450                             }
   1451                         } catch (FileNotFoundException e) {
   1452                             Slog.w(TAG, "Library not found: " + lib);
   1453                         } catch (IOException e) {
   1454                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
   1455                                     + e.getMessage());
   1456                         }
   1457                     }
   1458                 }
   1459             }
   1460 
   1461             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
   1462 
   1463             // Gross hack for now: we know this file doesn't contain any
   1464             // code, so don't dexopt it to avoid the resulting log spew.
   1465             alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
   1466 
   1467             // Gross hack for now: we know this file is only part of
   1468             // the boot class path for art, so don't dexopt it to
   1469             // avoid the resulting log spew.
   1470             alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
   1471 
   1472             /**
   1473              * And there are a number of commands implemented in Java, which
   1474              * we currently need to do the dexopt on so that they can be
   1475              * run from a non-root shell.
   1476              */
   1477             String[] frameworkFiles = frameworkDir.list();
   1478             if (frameworkFiles != null) {
   1479                 // TODO: We could compile these only for the most preferred ABI. We should
   1480                 // first double check that the dex files for these commands are not referenced
   1481                 // by other system apps.
   1482                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
   1483                     for (int i=0; i<frameworkFiles.length; i++) {
   1484                         File libPath = new File(frameworkDir, frameworkFiles[i]);
   1485                         String path = libPath.getPath();
   1486                         // Skip the file if we already did it.
   1487                         if (alreadyDexOpted.contains(path)) {
   1488                             continue;
   1489                         }
   1490                         // Skip the file if it is not a type we want to dexopt.
   1491                         if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
   1492                             continue;
   1493                         }
   1494                         try {
   1495                             byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
   1496                                                                                  dexCodeInstructionSet,
   1497                                                                                  false);
   1498                             if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
   1499                                 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
   1500                                 didDexOptLibraryOrTool = true;
   1501                             } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
   1502                                 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
   1503                                 didDexOptLibraryOrTool = true;
   1504                             }
   1505                         } catch (FileNotFoundException e) {
   1506                             Slog.w(TAG, "Jar not found: " + path);
   1507                         } catch (IOException e) {
   1508                             Slog.w(TAG, "Exception reading jar: " + path, e);
   1509                         }
   1510                     }
   1511                 }
   1512             }
   1513 
   1514             // Collect vendor overlay packages.
   1515             // (Do this before scanning any apps.)
   1516             // For security and version matching reason, only consider
   1517             // overlay packages if they reside in VENDOR_OVERLAY_DIR.
   1518             File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
   1519             scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
   1520                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
   1521 
   1522             // Find base frameworks (resource packages without code).
   1523             scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
   1524                     | PackageParser.PARSE_IS_SYSTEM_DIR
   1525                     | PackageParser.PARSE_IS_PRIVILEGED,
   1526                     scanFlags | SCAN_NO_DEX, 0);
   1527 
   1528             // Collected privileged system packages.
   1529             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
   1530             scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
   1531                     | PackageParser.PARSE_IS_SYSTEM_DIR
   1532                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
   1533 
   1534             // Collect ordinary system packages.
   1535             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
   1536             scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
   1537                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
   1538 
   1539             // Collect all vendor packages.
   1540             File vendorAppDir = new File("/vendor/app");
   1541             try {
   1542                 vendorAppDir = vendorAppDir.getCanonicalFile();
   1543             } catch (IOException e) {
   1544                 // failed to look up canonical path, continue with original one
   1545             }
   1546             scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
   1547                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
   1548 
   1549             // Collect all OEM packages.
   1550             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
   1551             scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
   1552                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
   1553 
   1554             if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
   1555             mInstaller.moveFiles();
   1556 
   1557             // Prune any system packages that no longer exist.
   1558             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
   1559             final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
   1560             if (!mOnlyCore) {
   1561                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
   1562                 while (psit.hasNext()) {
   1563                     PackageSetting ps = psit.next();
   1564 
   1565                     /*
   1566                      * If this is not a system app, it can't be a
   1567                      * disable system app.
   1568                      */
   1569                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
   1570                         continue;
   1571                     }
   1572 
   1573                     /*
   1574                      * If the package is scanned, it's not erased.
   1575                      */
   1576                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
   1577                     if (scannedPkg != null) {
   1578                         /*
   1579                          * If the system app is both scanned and in the
   1580                          * disabled packages list, then it must have been
   1581                          * added via OTA. Remove it from the currently
   1582                          * scanned package so the previously user-installed
   1583                          * application can be scanned.
   1584                          */
   1585                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
   1586                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
   1587                                     + ps.name + "; removing system app.  Last known codePath="
   1588                                     + ps.codePathString + ", installStatus=" + ps.installStatus
   1589                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
   1590                                     + scannedPkg.mVersionCode);
   1591                             removePackageLI(ps, true);
   1592                             expectingBetter.put(ps.name, ps.codePath);
   1593                         }
   1594 
   1595                         continue;
   1596                     }
   1597 
   1598                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
   1599                         psit.remove();
   1600                         logCriticalInfo(Log.WARN, "System package " + ps.name
   1601                                 + " no longer exists; wiping its data");
   1602                         removeDataDirsLI(ps.name);
   1603                     } else {
   1604                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
   1605                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
   1606                             possiblyDeletedUpdatedSystemApps.add(ps.name);
   1607                         }
   1608                     }
   1609                 }
   1610             }
   1611 
   1612             //look for any incomplete package installations
   1613             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
   1614             //clean up list
   1615             for(int i = 0; i < deletePkgsList.size(); i++) {
   1616                 //clean up here
   1617                 cleanupInstallFailedPackage(deletePkgsList.get(i));
   1618             }
   1619             //delete tmp files
   1620             deleteTempPackageFiles();
   1621 
   1622             // Remove any shared userIDs that have no associated packages
   1623             mSettings.pruneSharedUsersLPw();
   1624 
   1625             if (!mOnlyCore) {
   1626                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
   1627                         SystemClock.uptimeMillis());
   1628                 scanDirLI(mAppInstallDir, 0, scanFlags, 0);
   1629 
   1630                 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
   1631                         scanFlags, 0);
   1632 
   1633                 /**
   1634                  * Remove disable package settings for any updated system
   1635                  * apps that were removed via an OTA. If they're not a
   1636                  * previously-updated app, remove them completely.
   1637                  * Otherwise, just revoke their system-level permissions.
   1638                  */
   1639                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
   1640                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
   1641                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
   1642 
   1643                     String msg;
   1644                     if (deletedPkg == null) {
   1645                         msg = "Updated system package " + deletedAppName
   1646                                 + " no longer exists; wiping its data";
   1647                         removeDataDirsLI(deletedAppName);
   1648                     } else {
   1649                         msg = "Updated system app + " + deletedAppName
   1650                                 + " no longer present; removing system privileges for "
   1651                                 + deletedAppName;
   1652 
   1653                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
   1654 
   1655                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
   1656                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
   1657                     }
   1658                     logCriticalInfo(Log.WARN, msg);
   1659                 }
   1660 
   1661                 /**
   1662                  * Make sure all system apps that we expected to appear on
   1663                  * the userdata partition actually showed up. If they never
   1664                  * appeared, crawl back and revive the system version.
   1665                  */
   1666                 for (int i = 0; i < expectingBetter.size(); i++) {
   1667                     final String packageName = expectingBetter.keyAt(i);
   1668                     if (!mPackages.containsKey(packageName)) {
   1669                         final File scanFile = expectingBetter.valueAt(i);
   1670 
   1671                         logCriticalInfo(Log.WARN, "Expected better " + packageName
   1672                                 + " but never showed up; reverting to system");
   1673 
   1674                         final int reparseFlags;
   1675                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
   1676                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   1677                                     | PackageParser.PARSE_IS_SYSTEM_DIR
   1678                                     | PackageParser.PARSE_IS_PRIVILEGED;
   1679                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
   1680                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   1681                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
   1682                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
   1683                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   1684                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
   1685                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
   1686                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
   1687                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
   1688                         } else {
   1689                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
   1690                             continue;
   1691                         }
   1692 
   1693                         mSettings.enableSystemPackageLPw(packageName);
   1694 
   1695                         try {
   1696                             scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
   1697                         } catch (PackageManagerException e) {
   1698                             Slog.e(TAG, "Failed to parse original system package: "
   1699                                     + e.getMessage());
   1700                         }
   1701                     }
   1702                 }
   1703             }
   1704 
   1705             // Now that we know all of the shared libraries, update all clients to have
   1706             // the correct library paths.
   1707             updateAllSharedLibrariesLPw();
   1708 
   1709             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
   1710                 // NOTE: We ignore potential failures here during a system scan (like
   1711                 // the rest of the commands above) because there's precious little we
   1712                 // can do about it. A settings error is reported, though.
   1713                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
   1714                         false /* force dexopt */, false /* defer dexopt */);
   1715             }
   1716 
   1717             // Now that we know all the packages we are keeping,
   1718             // read and update their last usage times.
   1719             mPackageUsage.readLP();
   1720 
   1721             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
   1722                     SystemClock.uptimeMillis());
   1723             Slog.i(TAG, "Time to scan packages: "
   1724                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
   1725                     + " seconds");
   1726 
   1727             // If the platform SDK has changed since the last time we booted,
   1728             // we need to re-grant app permission to catch any new ones that
   1729             // appear.  This is really a hack, and means that apps can in some
   1730             // cases get permissions that the user didn't initially explicitly
   1731             // allow...  it would be nice to have some better way to handle
   1732             // this situation.
   1733             final boolean regrantPermissions = mSettings.mInternalSdkPlatform
   1734                     != mSdkVersion;
   1735             if (regrantPermissions) Slog.i(TAG, "Platform changed from "
   1736                     + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
   1737                     + "; regranting permissions for internal storage");
   1738             mSettings.mInternalSdkPlatform = mSdkVersion;
   1739 
   1740             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
   1741                     | (regrantPermissions
   1742                             ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
   1743                             : 0));
   1744 
   1745             // If this is the first boot, and it is a normal boot, then
   1746             // we need to initialize the default preferred apps.
   1747             if (!mRestoredSettings && !onlyCore) {
   1748                 mSettings.readDefaultPreferredAppsLPw(this, 0);
   1749             }
   1750 
   1751             // If this is first boot after an OTA, and a normal boot, then
   1752             // we need to clear code cache directories.
   1753             if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
   1754                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
   1755                 for (String pkgName : mSettings.mPackages.keySet()) {
   1756                     deleteCodeCacheDirsLI(pkgName);
   1757                 }
   1758                 mSettings.mFingerprint = Build.FINGERPRINT;
   1759             }
   1760 
   1761             // All the changes are done during package scanning.
   1762             mSettings.updateInternalDatabaseVersion();
   1763 
   1764             // can downgrade to reader
   1765             mSettings.writeLPr();
   1766 
   1767             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
   1768                     SystemClock.uptimeMillis());
   1769 
   1770 
   1771             mRequiredVerifierPackage = getRequiredVerifierLPr();
   1772         } // synchronized (mPackages)
   1773         } // synchronized (mInstallLock)
   1774 
   1775         mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
   1776 
   1777         // Now after opening every single application zip, make sure they
   1778         // are all flushed.  Not really needed, but keeps things nice and
   1779         // tidy.
   1780         Runtime.getRuntime().gc();
   1781     }
   1782 
   1783     @Override
   1784     public boolean isFirstBoot() {
   1785         return !mRestoredSettings;
   1786     }
   1787 
   1788     @Override
   1789     public boolean isOnlyCoreApps() {
   1790         return mOnlyCore;
   1791     }
   1792 
   1793     private String getRequiredVerifierLPr() {
   1794         final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
   1795         final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
   1796                 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
   1797 
   1798         String requiredVerifier = null;
   1799 
   1800         final int N = receivers.size();
   1801         for (int i = 0; i < N; i++) {
   1802             final ResolveInfo info = receivers.get(i);
   1803 
   1804             if (info.activityInfo == null) {
   1805                 continue;
   1806             }
   1807 
   1808             final String packageName = info.activityInfo.packageName;
   1809 
   1810             final PackageSetting ps = mSettings.mPackages.get(packageName);
   1811             if (ps == null) {
   1812                 continue;
   1813             }
   1814 
   1815             final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
   1816             if (!gp.grantedPermissions
   1817                     .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
   1818                 continue;
   1819             }
   1820 
   1821             if (requiredVerifier != null) {
   1822                 throw new RuntimeException("There can be only one required verifier");
   1823             }
   1824 
   1825             requiredVerifier = packageName;
   1826         }
   1827 
   1828         return requiredVerifier;
   1829     }
   1830 
   1831     @Override
   1832     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   1833             throws RemoteException {
   1834         try {
   1835             return super.onTransact(code, data, reply, flags);
   1836         } catch (RuntimeException e) {
   1837             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
   1838                 Slog.wtf(TAG, "Package Manager Crash", e);
   1839             }
   1840             throw e;
   1841         }
   1842     }
   1843 
   1844     void cleanupInstallFailedPackage(PackageSetting ps) {
   1845         logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
   1846 
   1847         removeDataDirsLI(ps.name);
   1848         if (ps.codePath != null) {
   1849             if (ps.codePath.isDirectory()) {
   1850                 FileUtils.deleteContents(ps.codePath);
   1851             }
   1852             ps.codePath.delete();
   1853         }
   1854         if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
   1855             if (ps.resourcePath.isDirectory()) {
   1856                 FileUtils.deleteContents(ps.resourcePath);
   1857             }
   1858             ps.resourcePath.delete();
   1859         }
   1860         mSettings.removePackageLPw(ps.name);
   1861     }
   1862 
   1863     static int[] appendInts(int[] cur, int[] add) {
   1864         if (add == null) return cur;
   1865         if (cur == null) return add;
   1866         final int N = add.length;
   1867         for (int i=0; i<N; i++) {
   1868             cur = appendInt(cur, add[i]);
   1869         }
   1870         return cur;
   1871     }
   1872 
   1873     static int[] removeInts(int[] cur, int[] rem) {
   1874         if (rem == null) return cur;
   1875         if (cur == null) return cur;
   1876         final int N = rem.length;
   1877         for (int i=0; i<N; i++) {
   1878             cur = removeInt(cur, rem[i]);
   1879         }
   1880         return cur;
   1881     }
   1882 
   1883     PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
   1884         if (!sUserManager.exists(userId)) return null;
   1885         final PackageSetting ps = (PackageSetting) p.mExtras;
   1886         if (ps == null) {
   1887             return null;
   1888         }
   1889         final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
   1890         final PackageUserState state = ps.readUserState(userId);
   1891         return PackageParser.generatePackageInfo(p, gp.gids, flags,
   1892                 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
   1893                 state, userId);
   1894     }
   1895 
   1896     @Override
   1897     public boolean isPackageAvailable(String packageName, int userId) {
   1898         if (!sUserManager.exists(userId)) return false;
   1899         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
   1900         synchronized (mPackages) {
   1901             PackageParser.Package p = mPackages.get(packageName);
   1902             if (p != null) {
   1903                 final PackageSetting ps = (PackageSetting) p.mExtras;
   1904                 if (ps != null) {
   1905                     final PackageUserState state = ps.readUserState(userId);
   1906                     if (state != null) {
   1907                         return PackageParser.isAvailable(state);
   1908                     }
   1909                 }
   1910             }
   1911         }
   1912         return false;
   1913     }
   1914 
   1915     @Override
   1916     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
   1917         if (!sUserManager.exists(userId)) return null;
   1918         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
   1919         // reader
   1920         synchronized (mPackages) {
   1921             PackageParser.Package p = mPackages.get(packageName);
   1922             if (DEBUG_PACKAGE_INFO)
   1923                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
   1924             if (p != null) {
   1925                 return generatePackageInfo(p, flags, userId);
   1926             }
   1927             if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
   1928                 return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
   1929             }
   1930         }
   1931         return null;
   1932     }
   1933 
   1934     @Override
   1935     public String[] currentToCanonicalPackageNames(String[] names) {
   1936         String[] out = new String[names.length];
   1937         // reader
   1938         synchronized (mPackages) {
   1939             for (int i=names.length-1; i>=0; i--) {
   1940                 PackageSetting ps = mSettings.mPackages.get(names[i]);
   1941                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
   1942             }
   1943         }
   1944         return out;
   1945     }
   1946 
   1947     @Override
   1948     public String[] canonicalToCurrentPackageNames(String[] names) {
   1949         String[] out = new String[names.length];
   1950         // reader
   1951         synchronized (mPackages) {
   1952             for (int i=names.length-1; i>=0; i--) {
   1953                 String cur = mSettings.mRenamedPackages.get(names[i]);
   1954                 out[i] = cur != null ? cur : names[i];
   1955             }
   1956         }
   1957         return out;
   1958     }
   1959 
   1960     @Override
   1961     public int getPackageUid(String packageName, int userId) {
   1962         if (!sUserManager.exists(userId)) return -1;
   1963         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
   1964         // reader
   1965         synchronized (mPackages) {
   1966             PackageParser.Package p = mPackages.get(packageName);
   1967             if(p != null) {
   1968                 return UserHandle.getUid(userId, p.applicationInfo.uid);
   1969             }
   1970             PackageSetting ps = mSettings.mPackages.get(packageName);
   1971             if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
   1972                 return -1;
   1973             }
   1974             p = ps.pkg;
   1975             return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
   1976         }
   1977     }
   1978 
   1979     @Override
   1980     public int[] getPackageGids(String packageName) {
   1981         // reader
   1982         synchronized (mPackages) {
   1983             PackageParser.Package p = mPackages.get(packageName);
   1984             if (DEBUG_PACKAGE_INFO)
   1985                 Log.v(TAG, "getPackageGids" + packageName + ": " + p);
   1986             if (p != null) {
   1987                 final PackageSetting ps = (PackageSetting)p.mExtras;
   1988                 return ps.getGids();
   1989             }
   1990         }
   1991         // stupid thing to indicate an error.
   1992         return new int[0];
   1993     }
   1994 
   1995     static final PermissionInfo generatePermissionInfo(
   1996             BasePermission bp, int flags) {
   1997         if (bp.perm != null) {
   1998             return PackageParser.generatePermissionInfo(bp.perm, flags);
   1999         }
   2000         PermissionInfo pi = new PermissionInfo();
   2001         pi.name = bp.name;
   2002         pi.packageName = bp.sourcePackage;
   2003         pi.nonLocalizedLabel = bp.name;
   2004         pi.protectionLevel = bp.protectionLevel;
   2005         return pi;
   2006     }
   2007 
   2008     @Override
   2009     public PermissionInfo getPermissionInfo(String name, int flags) {
   2010         // reader
   2011         synchronized (mPackages) {
   2012             final BasePermission p = mSettings.mPermissions.get(name);
   2013             if (p != null) {
   2014                 return generatePermissionInfo(p, flags);
   2015             }
   2016             return null;
   2017         }
   2018     }
   2019 
   2020     @Override
   2021     public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
   2022         // reader
   2023         synchronized (mPackages) {
   2024             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
   2025             for (BasePermission p : mSettings.mPermissions.values()) {
   2026                 if (group == null) {
   2027                     if (p.perm == null || p.perm.info.group == null) {
   2028                         out.add(generatePermissionInfo(p, flags));
   2029                     }
   2030                 } else {
   2031                     if (p.perm != null && group.equals(p.perm.info.group)) {
   2032                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
   2033                     }
   2034                 }
   2035             }
   2036 
   2037             if (out.size() > 0) {
   2038                 return out;
   2039             }
   2040             return mPermissionGroups.containsKey(group) ? out : null;
   2041         }
   2042     }
   2043 
   2044     @Override
   2045     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
   2046         // reader
   2047         synchronized (mPackages) {
   2048             return PackageParser.generatePermissionGroupInfo(
   2049                     mPermissionGroups.get(name), flags);
   2050         }
   2051     }
   2052 
   2053     @Override
   2054     public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
   2055         // reader
   2056         synchronized (mPackages) {
   2057             final int N = mPermissionGroups.size();
   2058             ArrayList<PermissionGroupInfo> out
   2059                     = new ArrayList<PermissionGroupInfo>(N);
   2060             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
   2061                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
   2062             }
   2063             return out;
   2064         }
   2065     }
   2066 
   2067     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
   2068             int userId) {
   2069         if (!sUserManager.exists(userId)) return null;
   2070         PackageSetting ps = mSettings.mPackages.get(packageName);
   2071         if (ps != null) {
   2072             if (ps.pkg == null) {
   2073                 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
   2074                         flags, userId);
   2075                 if (pInfo != null) {
   2076                     return pInfo.applicationInfo;
   2077                 }
   2078                 return null;
   2079             }
   2080             return PackageParser.generateApplicationInfo(ps.pkg, flags,
   2081                     ps.readUserState(userId), userId);
   2082         }
   2083         return null;
   2084     }
   2085 
   2086     private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
   2087             int userId) {
   2088         if (!sUserManager.exists(userId)) return null;
   2089         PackageSetting ps = mSettings.mPackages.get(packageName);
   2090         if (ps != null) {
   2091             PackageParser.Package pkg = ps.pkg;
   2092             if (pkg == null) {
   2093                 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
   2094                     return null;
   2095                 }
   2096                 // Only data remains, so we aren't worried about code paths
   2097                 pkg = new PackageParser.Package(packageName);
   2098                 pkg.applicationInfo.packageName = packageName;
   2099                 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
   2100                 pkg.applicationInfo.dataDir =
   2101                         getDataPathForPackage(packageName, 0).getPath();
   2102                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
   2103                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
   2104             }
   2105             return generatePackageInfo(pkg, flags, userId);
   2106         }
   2107         return null;
   2108     }
   2109 
   2110     @Override
   2111     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
   2112         if (!sUserManager.exists(userId)) return null;
   2113         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
   2114         // writer
   2115         synchronized (mPackages) {
   2116             PackageParser.Package p = mPackages.get(packageName);
   2117             if (DEBUG_PACKAGE_INFO) Log.v(
   2118                     TAG, "getApplicationInfo " + packageName
   2119                     + ": " + p);
   2120             if (p != null) {
   2121                 PackageSetting ps = mSettings.mPackages.get(packageName);
   2122                 if (ps == null) return null;
   2123                 // Note: isEnabledLP() does not apply here - always return info
   2124                 return PackageParser.generateApplicationInfo(
   2125                         p, flags, ps.readUserState(userId), userId);
   2126             }
   2127             if ("android".equals(packageName)||"system".equals(packageName)) {
   2128                 return mAndroidApplication;
   2129             }
   2130             if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
   2131                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
   2132             }
   2133         }
   2134         return null;
   2135     }
   2136 
   2137 
   2138     @Override
   2139     public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
   2140         mContext.enforceCallingOrSelfPermission(
   2141                 android.Manifest.permission.CLEAR_APP_CACHE, null);
   2142         // Queue up an async operation since clearing cache may take a little while.
   2143         mHandler.post(new Runnable() {
   2144             public void run() {
   2145                 mHandler.removeCallbacks(this);
   2146                 int retCode = -1;
   2147                 synchronized (mInstallLock) {
   2148                     retCode = mInstaller.freeCache(freeStorageSize);
   2149                     if (retCode < 0) {
   2150                         Slog.w(TAG, "Couldn't clear application caches");
   2151                     }
   2152                 }
   2153                 if (observer != null) {
   2154                     try {
   2155                         observer.onRemoveCompleted(null, (retCode >= 0));
   2156                     } catch (RemoteException e) {
   2157                         Slog.w(TAG, "RemoveException when invoking call back");
   2158                     }
   2159                 }
   2160             }
   2161         });
   2162     }
   2163 
   2164     @Override
   2165     public void freeStorage(final long freeStorageSize, final IntentSender pi) {
   2166         mContext.enforceCallingOrSelfPermission(
   2167                 android.Manifest.permission.CLEAR_APP_CACHE, null);
   2168         // Queue up an async operation since clearing cache may take a little while.
   2169         mHandler.post(new Runnable() {
   2170             public void run() {
   2171                 mHandler.removeCallbacks(this);
   2172                 int retCode = -1;
   2173                 synchronized (mInstallLock) {
   2174                     retCode = mInstaller.freeCache(freeStorageSize);
   2175                     if (retCode < 0) {
   2176                         Slog.w(TAG, "Couldn't clear application caches");
   2177                     }
   2178                 }
   2179                 if(pi != null) {
   2180                     try {
   2181                         // Callback via pending intent
   2182                         int code = (retCode >= 0) ? 1 : 0;
   2183                         pi.sendIntent(null, code, null,
   2184                                 null, null);
   2185                     } catch (SendIntentException e1) {
   2186                         Slog.i(TAG, "Failed to send pending intent");
   2187                     }
   2188                 }
   2189             }
   2190         });
   2191     }
   2192 
   2193     void freeStorage(long freeStorageSize) throws IOException {
   2194         synchronized (mInstallLock) {
   2195             if (mInstaller.freeCache(freeStorageSize) < 0) {
   2196                 throw new IOException("Failed to free enough space");
   2197             }
   2198         }
   2199     }
   2200 
   2201     @Override
   2202     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
   2203         if (!sUserManager.exists(userId)) return null;
   2204         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
   2205         synchronized (mPackages) {
   2206             PackageParser.Activity a = mActivities.mActivities.get(component);
   2207 
   2208             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
   2209             if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
   2210                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   2211                 if (ps == null) return null;
   2212                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
   2213                         userId);
   2214             }
   2215             if (mResolveComponentName.equals(component)) {
   2216                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
   2217                         new PackageUserState(), userId);
   2218             }
   2219         }
   2220         return null;
   2221     }
   2222 
   2223     @Override
   2224     public boolean activitySupportsIntent(ComponentName component, Intent intent,
   2225             String resolvedType) {
   2226         synchronized (mPackages) {
   2227             PackageParser.Activity a = mActivities.mActivities.get(component);
   2228             if (a == null) {
   2229                 return false;
   2230             }
   2231             for (int i=0; i<a.intents.size(); i++) {
   2232                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
   2233                         intent.getData(), intent.getCategories(), TAG) >= 0) {
   2234                     return true;
   2235                 }
   2236             }
   2237             return false;
   2238         }
   2239     }
   2240 
   2241     @Override
   2242     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
   2243         if (!sUserManager.exists(userId)) return null;
   2244         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
   2245         synchronized (mPackages) {
   2246             PackageParser.Activity a = mReceivers.mActivities.get(component);
   2247             if (DEBUG_PACKAGE_INFO) Log.v(
   2248                 TAG, "getReceiverInfo " + component + ": " + a);
   2249             if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
   2250                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   2251                 if (ps == null) return null;
   2252                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
   2253                         userId);
   2254             }
   2255         }
   2256         return null;
   2257     }
   2258 
   2259     @Override
   2260     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
   2261         if (!sUserManager.exists(userId)) return null;
   2262         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
   2263         synchronized (mPackages) {
   2264             PackageParser.Service s = mServices.mServices.get(component);
   2265             if (DEBUG_PACKAGE_INFO) Log.v(
   2266                 TAG, "getServiceInfo " + component + ": " + s);
   2267             if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
   2268                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   2269                 if (ps == null) return null;
   2270                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
   2271                         userId);
   2272             }
   2273         }
   2274         return null;
   2275     }
   2276 
   2277     @Override
   2278     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
   2279         if (!sUserManager.exists(userId)) return null;
   2280         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
   2281         synchronized (mPackages) {
   2282             PackageParser.Provider p = mProviders.mProviders.get(component);
   2283             if (DEBUG_PACKAGE_INFO) Log.v(
   2284                 TAG, "getProviderInfo " + component + ": " + p);
   2285             if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
   2286                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
   2287                 if (ps == null) return null;
   2288                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
   2289                         userId);
   2290             }
   2291         }
   2292         return null;
   2293     }
   2294 
   2295     @Override
   2296     public String[] getSystemSharedLibraryNames() {
   2297         Set<String> libSet;
   2298         synchronized (mPackages) {
   2299             libSet = mSharedLibraries.keySet();
   2300             int size = libSet.size();
   2301             if (size > 0) {
   2302                 String[] libs = new String[size];
   2303                 libSet.toArray(libs);
   2304                 return libs;
   2305             }
   2306         }
   2307         return null;
   2308     }
   2309 
   2310     @Override
   2311     public FeatureInfo[] getSystemAvailableFeatures() {
   2312         Collection<FeatureInfo> featSet;
   2313         synchronized (mPackages) {
   2314             featSet = mAvailableFeatures.values();
   2315             int size = featSet.size();
   2316             if (size > 0) {
   2317                 FeatureInfo[] features = new FeatureInfo[size+1];
   2318                 featSet.toArray(features);
   2319                 FeatureInfo fi = new FeatureInfo();
   2320                 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
   2321                         FeatureInfo.GL_ES_VERSION_UNDEFINED);
   2322                 features[size] = fi;
   2323                 return features;
   2324             }
   2325         }
   2326         return null;
   2327     }
   2328 
   2329     @Override
   2330     public boolean hasSystemFeature(String name) {
   2331         synchronized (mPackages) {
   2332             return mAvailableFeatures.containsKey(name);
   2333         }
   2334     }
   2335 
   2336     private void checkValidCaller(int uid, int userId) {
   2337         if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
   2338             return;
   2339 
   2340         throw new SecurityException("Caller uid=" + uid
   2341                 + " is not privileged to communicate with user=" + userId);
   2342     }
   2343 
   2344     @Override
   2345     public int checkPermission(String permName, String pkgName) {
   2346         synchronized (mPackages) {
   2347             PackageParser.Package p = mPackages.get(pkgName);
   2348             if (p != null && p.mExtras != null) {
   2349                 PackageSetting ps = (PackageSetting)p.mExtras;
   2350                 if (ps.sharedUser != null) {
   2351                     if (ps.sharedUser.grantedPermissions.contains(permName)) {
   2352                         return PackageManager.PERMISSION_GRANTED;
   2353                     }
   2354                 } else if (ps.grantedPermissions.contains(permName)) {
   2355                     return PackageManager.PERMISSION_GRANTED;
   2356                 }
   2357             }
   2358         }
   2359         return PackageManager.PERMISSION_DENIED;
   2360     }
   2361 
   2362     @Override
   2363     public int checkUidPermission(String permName, int uid) {
   2364         synchronized (mPackages) {
   2365             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   2366             if (obj != null) {
   2367                 GrantedPermissions gp = (GrantedPermissions)obj;
   2368                 if (gp.grantedPermissions.contains(permName)) {
   2369                     return PackageManager.PERMISSION_GRANTED;
   2370                 }
   2371             } else {
   2372                 HashSet<String> perms = mSystemPermissions.get(uid);
   2373                 if (perms != null && perms.contains(permName)) {
   2374                     return PackageManager.PERMISSION_GRANTED;
   2375                 }
   2376             }
   2377         }
   2378         return PackageManager.PERMISSION_DENIED;
   2379     }
   2380 
   2381     /**
   2382      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
   2383      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
   2384      * @param checkShell TODO(yamasani):
   2385      * @param message the message to log on security exception
   2386      */
   2387     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
   2388             boolean checkShell, String message) {
   2389         if (userId < 0) {
   2390             throw new IllegalArgumentException("Invalid userId " + userId);
   2391         }
   2392         if (checkShell) {
   2393             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
   2394         }
   2395         if (userId == UserHandle.getUserId(callingUid)) return;
   2396         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
   2397             if (requireFullPermission) {
   2398                 mContext.enforceCallingOrSelfPermission(
   2399                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
   2400             } else {
   2401                 try {
   2402                     mContext.enforceCallingOrSelfPermission(
   2403                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
   2404                 } catch (SecurityException se) {
   2405                     mContext.enforceCallingOrSelfPermission(
   2406                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
   2407                 }
   2408             }
   2409         }
   2410     }
   2411 
   2412     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
   2413         if (callingUid == Process.SHELL_UID) {
   2414             if (userHandle >= 0
   2415                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
   2416                 throw new SecurityException("Shell does not have permission to access user "
   2417                         + userHandle);
   2418             } else if (userHandle < 0) {
   2419                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
   2420                         + Debug.getCallers(3));
   2421             }
   2422         }
   2423     }
   2424 
   2425     private BasePermission findPermissionTreeLP(String permName) {
   2426         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
   2427             if (permName.startsWith(bp.name) &&
   2428                     permName.length() > bp.name.length() &&
   2429                     permName.charAt(bp.name.length()) == '.') {
   2430                 return bp;
   2431             }
   2432         }
   2433         return null;
   2434     }
   2435 
   2436     private BasePermission checkPermissionTreeLP(String permName) {
   2437         if (permName != null) {
   2438             BasePermission bp = findPermissionTreeLP(permName);
   2439             if (bp != null) {
   2440                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
   2441                     return bp;
   2442                 }
   2443                 throw new SecurityException("Calling uid "
   2444                         + Binder.getCallingUid()
   2445                         + " is not allowed to add to permission tree "
   2446                         + bp.name + " owned by uid " + bp.uid);
   2447             }
   2448         }
   2449         throw new SecurityException("No permission tree found for " + permName);
   2450     }
   2451 
   2452     static boolean compareStrings(CharSequence s1, CharSequence s2) {
   2453         if (s1 == null) {
   2454             return s2 == null;
   2455         }
   2456         if (s2 == null) {
   2457             return false;
   2458         }
   2459         if (s1.getClass() != s2.getClass()) {
   2460             return false;
   2461         }
   2462         return s1.equals(s2);
   2463     }
   2464 
   2465     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
   2466         if (pi1.icon != pi2.icon) return false;
   2467         if (pi1.logo != pi2.logo) return false;
   2468         if (pi1.protectionLevel != pi2.protectionLevel) return false;
   2469         if (!compareStrings(pi1.name, pi2.name)) return false;
   2470         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
   2471         // We'll take care of setting this one.
   2472         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
   2473         // These are not currently stored in settings.
   2474         //if (!compareStrings(pi1.group, pi2.group)) return false;
   2475         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
   2476         //if (pi1.labelRes != pi2.labelRes) return false;
   2477         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
   2478         return true;
   2479     }
   2480 
   2481     int permissionInfoFootprint(PermissionInfo info) {
   2482         int size = info.name.length();
   2483         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
   2484         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
   2485         return size;
   2486     }
   2487 
   2488     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
   2489         int size = 0;
   2490         for (BasePermission perm : mSettings.mPermissions.values()) {
   2491             if (perm.uid == tree.uid) {
   2492                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
   2493             }
   2494         }
   2495         return size;
   2496     }
   2497 
   2498     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
   2499         // We calculate the max size of permissions defined by this uid and throw
   2500         // if that plus the size of 'info' would exceed our stated maximum.
   2501         if (tree.uid != Process.SYSTEM_UID) {
   2502             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
   2503             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
   2504                 throw new SecurityException("Permission tree size cap exceeded");
   2505             }
   2506         }
   2507     }
   2508 
   2509     boolean addPermissionLocked(PermissionInfo info, boolean async) {
   2510         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
   2511             throw new SecurityException("Label must be specified in permission");
   2512         }
   2513         BasePermission tree = checkPermissionTreeLP(info.name);
   2514         BasePermission bp = mSettings.mPermissions.get(info.name);
   2515         boolean added = bp == null;
   2516         boolean changed = true;
   2517         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
   2518         if (added) {
   2519             enforcePermissionCapLocked(info, tree);
   2520             bp = new BasePermission(info.name, tree.sourcePackage,
   2521                     BasePermission.TYPE_DYNAMIC);
   2522         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
   2523             throw new SecurityException(
   2524                     "Not allowed to modify non-dynamic permission "
   2525                     + info.name);
   2526         } else {
   2527             if (bp.protectionLevel == fixedLevel
   2528                     && bp.perm.owner.equals(tree.perm.owner)
   2529                     && bp.uid == tree.uid
   2530                     && comparePermissionInfos(bp.perm.info, info)) {
   2531                 changed = false;
   2532             }
   2533         }
   2534         bp.protectionLevel = fixedLevel;
   2535         info = new PermissionInfo(info);
   2536         info.protectionLevel = fixedLevel;
   2537         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
   2538         bp.perm.info.packageName = tree.perm.info.packageName;
   2539         bp.uid = tree.uid;
   2540         if (added) {
   2541             mSettings.mPermissions.put(info.name, bp);
   2542         }
   2543         if (changed) {
   2544             if (!async) {
   2545                 mSettings.writeLPr();
   2546             } else {
   2547                 scheduleWriteSettingsLocked();
   2548             }
   2549         }
   2550         return added;
   2551     }
   2552 
   2553     @Override
   2554     public boolean addPermission(PermissionInfo info) {
   2555         synchronized (mPackages) {
   2556             return addPermissionLocked(info, false);
   2557         }
   2558     }
   2559 
   2560     @Override
   2561     public boolean addPermissionAsync(PermissionInfo info) {
   2562         synchronized (mPackages) {
   2563             return addPermissionLocked(info, true);
   2564         }
   2565     }
   2566 
   2567     @Override
   2568     public void removePermission(String name) {
   2569         synchronized (mPackages) {
   2570             checkPermissionTreeLP(name);
   2571             BasePermission bp = mSettings.mPermissions.get(name);
   2572             if (bp != null) {
   2573                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
   2574                     throw new SecurityException(
   2575                             "Not allowed to modify non-dynamic permission "
   2576                             + name);
   2577                 }
   2578                 mSettings.mPermissions.remove(name);
   2579                 mSettings.writeLPr();
   2580             }
   2581         }
   2582     }
   2583 
   2584     private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
   2585         int index = pkg.requestedPermissions.indexOf(bp.name);
   2586         if (index == -1) {
   2587             throw new SecurityException("Package " + pkg.packageName
   2588                     + " has not requested permission " + bp.name);
   2589         }
   2590         boolean isNormal =
   2591                 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
   2592                         == PermissionInfo.PROTECTION_NORMAL);
   2593         boolean isDangerous =
   2594                 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
   2595                         == PermissionInfo.PROTECTION_DANGEROUS);
   2596         boolean isDevelopment =
   2597                 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
   2598 
   2599         if (!isNormal && !isDangerous && !isDevelopment) {
   2600             throw new SecurityException("Permission " + bp.name
   2601                     + " is not a changeable permission type");
   2602         }
   2603 
   2604         if (isNormal || isDangerous) {
   2605             if (pkg.requestedPermissionsRequired.get(index)) {
   2606                 throw new SecurityException("Can't change " + bp.name
   2607                         + ". It is required by the application");
   2608             }
   2609         }
   2610     }
   2611 
   2612     @Override
   2613     public void grantPermission(String packageName, String permissionName) {
   2614         mContext.enforceCallingOrSelfPermission(
   2615                 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
   2616         synchronized (mPackages) {
   2617             final PackageParser.Package pkg = mPackages.get(packageName);
   2618             if (pkg == null) {
   2619                 throw new IllegalArgumentException("Unknown package: " + packageName);
   2620             }
   2621             final BasePermission bp = mSettings.mPermissions.get(permissionName);
   2622             if (bp == null) {
   2623                 throw new IllegalArgumentException("Unknown permission: " + permissionName);
   2624             }
   2625 
   2626             checkGrantRevokePermissions(pkg, bp);
   2627 
   2628             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   2629             if (ps == null) {
   2630                 return;
   2631             }
   2632             final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
   2633             if (gp.grantedPermissions.add(permissionName)) {
   2634                 if (ps.haveGids) {
   2635                     gp.gids = appendInts(gp.gids, bp.gids);
   2636                 }
   2637                 mSettings.writeLPr();
   2638             }
   2639         }
   2640     }
   2641 
   2642     @Override
   2643     public void revokePermission(String packageName, String permissionName) {
   2644         int changedAppId = -1;
   2645 
   2646         synchronized (mPackages) {
   2647             final PackageParser.Package pkg = mPackages.get(packageName);
   2648             if (pkg == null) {
   2649                 throw new IllegalArgumentException("Unknown package: " + packageName);
   2650             }
   2651             if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
   2652                 mContext.enforceCallingOrSelfPermission(
   2653                         android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
   2654             }
   2655             final BasePermission bp = mSettings.mPermissions.get(permissionName);
   2656             if (bp == null) {
   2657                 throw new IllegalArgumentException("Unknown permission: " + permissionName);
   2658             }
   2659 
   2660             checkGrantRevokePermissions(pkg, bp);
   2661 
   2662             final PackageSetting ps = (PackageSetting) pkg.mExtras;
   2663             if (ps == null) {
   2664                 return;
   2665             }
   2666             final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
   2667             if (gp.grantedPermissions.remove(permissionName)) {
   2668                 gp.grantedPermissions.remove(permissionName);
   2669                 if (ps.haveGids) {
   2670                     gp.gids = removeInts(gp.gids, bp.gids);
   2671                 }
   2672                 mSettings.writeLPr();
   2673                 changedAppId = ps.appId;
   2674             }
   2675         }
   2676 
   2677         if (changedAppId >= 0) {
   2678             // We changed the perm on someone, kill its processes.
   2679             IActivityManager am = ActivityManagerNative.getDefault();
   2680             if (am != null) {
   2681                 final int callingUserId = UserHandle.getCallingUserId();
   2682                 final long ident = Binder.clearCallingIdentity();
   2683                 try {
   2684                     //XXX we should only revoke for the calling user's app permissions,
   2685                     // but for now we impact all users.
   2686                     //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
   2687                     //        "revoke " + permissionName);
   2688                     int[] users = sUserManager.getUserIds();
   2689                     for (int user : users) {
   2690                         am.killUid(UserHandle.getUid(user, changedAppId),
   2691                                 "revoke " + permissionName);
   2692                     }
   2693                 } catch (RemoteException e) {
   2694                 } finally {
   2695                     Binder.restoreCallingIdentity(ident);
   2696                 }
   2697             }
   2698         }
   2699     }
   2700 
   2701     @Override
   2702     public boolean isProtectedBroadcast(String actionName) {
   2703         synchronized (mPackages) {
   2704             return mProtectedBroadcasts.contains(actionName);
   2705         }
   2706     }
   2707 
   2708     @Override
   2709     public int checkSignatures(String pkg1, String pkg2) {
   2710         synchronized (mPackages) {
   2711             final PackageParser.Package p1 = mPackages.get(pkg1);
   2712             final PackageParser.Package p2 = mPackages.get(pkg2);
   2713             if (p1 == null || p1.mExtras == null
   2714                     || p2 == null || p2.mExtras == null) {
   2715                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   2716             }
   2717             return compareSignatures(p1.mSignatures, p2.mSignatures);
   2718         }
   2719     }
   2720 
   2721     @Override
   2722     public int checkUidSignatures(int uid1, int uid2) {
   2723         // Map to base uids.
   2724         uid1 = UserHandle.getAppId(uid1);
   2725         uid2 = UserHandle.getAppId(uid2);
   2726         // reader
   2727         synchronized (mPackages) {
   2728             Signature[] s1;
   2729             Signature[] s2;
   2730             Object obj = mSettings.getUserIdLPr(uid1);
   2731             if (obj != null) {
   2732                 if (obj instanceof SharedUserSetting) {
   2733                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
   2734                 } else if (obj instanceof PackageSetting) {
   2735                     s1 = ((PackageSetting)obj).signatures.mSignatures;
   2736                 } else {
   2737                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   2738                 }
   2739             } else {
   2740                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   2741             }
   2742             obj = mSettings.getUserIdLPr(uid2);
   2743             if (obj != null) {
   2744                 if (obj instanceof SharedUserSetting) {
   2745                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
   2746                 } else if (obj instanceof PackageSetting) {
   2747                     s2 = ((PackageSetting)obj).signatures.mSignatures;
   2748                 } else {
   2749                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   2750                 }
   2751             } else {
   2752                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
   2753             }
   2754             return compareSignatures(s1, s2);
   2755         }
   2756     }
   2757 
   2758     /**
   2759      * Compares two sets of signatures. Returns:
   2760      * <br />
   2761      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
   2762      * <br />
   2763      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
   2764      * <br />
   2765      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
   2766      * <br />
   2767      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
   2768      * <br />
   2769      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
   2770      */
   2771     static int compareSignatures(Signature[] s1, Signature[] s2) {
   2772         if (s1 == null) {
   2773             return s2 == null
   2774                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
   2775                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
   2776         }
   2777 
   2778         if (s2 == null) {
   2779             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
   2780         }
   2781 
   2782         if (s1.length != s2.length) {
   2783             return PackageManager.SIGNATURE_NO_MATCH;
   2784         }
   2785 
   2786         // Since both signature sets are of size 1, we can compare without HashSets.
   2787         if (s1.length == 1) {
   2788             return s1[0].equals(s2[0]) ?
   2789                     PackageManager.SIGNATURE_MATCH :
   2790                     PackageManager.SIGNATURE_NO_MATCH;
   2791         }
   2792 
   2793         HashSet<Signature> set1 = new HashSet<Signature>();
   2794         for (Signature sig : s1) {
   2795             set1.add(sig);
   2796         }
   2797         HashSet<Signature> set2 = new HashSet<Signature>();
   2798         for (Signature sig : s2) {
   2799             set2.add(sig);
   2800         }
   2801         // Make sure s2 contains all signatures in s1.
   2802         if (set1.equals(set2)) {
   2803             return PackageManager.SIGNATURE_MATCH;
   2804         }
   2805         return PackageManager.SIGNATURE_NO_MATCH;
   2806     }
   2807 
   2808     /**
   2809      * If the database version for this type of package (internal storage or
   2810      * external storage) is less than the version where package signatures
   2811      * were updated, return true.
   2812      */
   2813     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
   2814         return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
   2815                 DatabaseVersion.SIGNATURE_END_ENTITY))
   2816                 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
   2817                         DatabaseVersion.SIGNATURE_END_ENTITY));
   2818     }
   2819 
   2820     /**
   2821      * Used for backward compatibility to make sure any packages with
   2822      * certificate chains get upgraded to the new style. {@code existingSigs}
   2823      * will be in the old format (since they were stored on disk from before the
   2824      * system upgrade) and {@code scannedSigs} will be in the newer format.
   2825      */
   2826     private int compareSignaturesCompat(PackageSignatures existingSigs,
   2827             PackageParser.Package scannedPkg) {
   2828         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
   2829             return PackageManager.SIGNATURE_NO_MATCH;
   2830         }
   2831 
   2832         HashSet<Signature> existingSet = new HashSet<Signature>();
   2833         for (Signature sig : existingSigs.mSignatures) {
   2834             existingSet.add(sig);
   2835         }
   2836         HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
   2837         for (Signature sig : scannedPkg.mSignatures) {
   2838             try {
   2839                 Signature[] chainSignatures = sig.getChainSignatures();
   2840                 for (Signature chainSig : chainSignatures) {
   2841                     scannedCompatSet.add(chainSig);
   2842                 }
   2843             } catch (CertificateEncodingException e) {
   2844                 scannedCompatSet.add(sig);
   2845             }
   2846         }
   2847         /*
   2848          * Make sure the expanded scanned set contains all signatures in the
   2849          * existing one.
   2850          */
   2851         if (scannedCompatSet.equals(existingSet)) {
   2852             // Migrate the old signatures to the new scheme.
   2853             existingSigs.assignSignatures(scannedPkg.mSignatures);
   2854             // The new KeySets will be re-added later in the scanning process.
   2855             synchronized (mPackages) {
   2856                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
   2857             }
   2858             return PackageManager.SIGNATURE_MATCH;
   2859         }
   2860         return PackageManager.SIGNATURE_NO_MATCH;
   2861     }
   2862 
   2863     @Override
   2864     public String[] getPackagesForUid(int uid) {
   2865         uid = UserHandle.getAppId(uid);
   2866         // reader
   2867         synchronized (mPackages) {
   2868             Object obj = mSettings.getUserIdLPr(uid);
   2869             if (obj instanceof SharedUserSetting) {
   2870                 final SharedUserSetting sus = (SharedUserSetting) obj;
   2871                 final int N = sus.packages.size();
   2872                 final String[] res = new String[N];
   2873                 final Iterator<PackageSetting> it = sus.packages.iterator();
   2874                 int i = 0;
   2875                 while (it.hasNext()) {
   2876                     res[i++] = it.next().name;
   2877                 }
   2878                 return res;
   2879             } else if (obj instanceof PackageSetting) {
   2880                 final PackageSetting ps = (PackageSetting) obj;
   2881                 return new String[] { ps.name };
   2882             }
   2883         }
   2884         return null;
   2885     }
   2886 
   2887     @Override
   2888     public String getNameForUid(int uid) {
   2889         // reader
   2890         synchronized (mPackages) {
   2891             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   2892             if (obj instanceof SharedUserSetting) {
   2893                 final SharedUserSetting sus = (SharedUserSetting) obj;
   2894                 return sus.name + ":" + sus.userId;
   2895             } else if (obj instanceof PackageSetting) {
   2896                 final PackageSetting ps = (PackageSetting) obj;
   2897                 return ps.name;
   2898             }
   2899         }
   2900         return null;
   2901     }
   2902 
   2903     @Override
   2904     public int getUidForSharedUser(String sharedUserName) {
   2905         if(sharedUserName == null) {
   2906             return -1;
   2907         }
   2908         // reader
   2909         synchronized (mPackages) {
   2910             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
   2911             if (suid == null) {
   2912                 return -1;
   2913             }
   2914             return suid.userId;
   2915         }
   2916     }
   2917 
   2918     @Override
   2919     public int getFlagsForUid(int uid) {
   2920         synchronized (mPackages) {
   2921             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
   2922             if (obj instanceof SharedUserSetting) {
   2923                 final SharedUserSetting sus = (SharedUserSetting) obj;
   2924                 return sus.pkgFlags;
   2925             } else if (obj instanceof PackageSetting) {
   2926                 final PackageSetting ps = (PackageSetting) obj;
   2927                 return ps.pkgFlags;
   2928             }
   2929         }
   2930         return 0;
   2931     }
   2932 
   2933     @Override
   2934     public boolean isUidPrivileged(int uid) {
   2935         uid = UserHandle.getAppId(uid);
   2936         // reader
   2937         synchronized (mPackages) {
   2938             Object obj = mSettings.getUserIdLPr(uid);
   2939             if (obj instanceof SharedUserSetting) {
   2940                 final SharedUserSetting sus = (SharedUserSetting) obj;
   2941                 final Iterator<PackageSetting> it = sus.packages.iterator();
   2942                 while (it.hasNext()) {
   2943                     if (it.next().isPrivileged()) {
   2944                         return true;
   2945                     }
   2946                 }
   2947             } else if (obj instanceof PackageSetting) {
   2948                 final PackageSetting ps = (PackageSetting) obj;
   2949                 return ps.isPrivileged();
   2950             }
   2951         }
   2952         return false;
   2953     }
   2954 
   2955     @Override
   2956     public String[] getAppOpPermissionPackages(String permissionName) {
   2957         synchronized (mPackages) {
   2958             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
   2959             if (pkgs == null) {
   2960                 return null;
   2961             }
   2962             return pkgs.toArray(new String[pkgs.size()]);
   2963         }
   2964     }
   2965 
   2966     @Override
   2967     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
   2968             int flags, int userId) {
   2969         if (!sUserManager.exists(userId)) return null;
   2970         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
   2971         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
   2972         return chooseBestActivity(intent, resolvedType, flags, query, userId);
   2973     }
   2974 
   2975     @Override
   2976     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
   2977             IntentFilter filter, int match, ComponentName activity) {
   2978         final int userId = UserHandle.getCallingUserId();
   2979         if (DEBUG_PREFERRED) {
   2980             Log.v(TAG, "setLastChosenActivity intent=" + intent
   2981                 + " resolvedType=" + resolvedType
   2982                 + " flags=" + flags
   2983                 + " filter=" + filter
   2984                 + " match=" + match
   2985                 + " activity=" + activity);
   2986             filter.dump(new PrintStreamPrinter(System.out), "    ");
   2987         }
   2988         intent.setComponent(null);
   2989         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
   2990         // Find any earlier preferred or last chosen entries and nuke them
   2991         findPreferredActivity(intent, resolvedType,
   2992                 flags, query, 0, false, true, false, userId);
   2993         // Add the new activity as the last chosen for this filter
   2994         addPreferredActivityInternal(filter, match, null, activity, false, userId,
   2995                 "Setting last chosen");
   2996     }
   2997 
   2998     @Override
   2999     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
   3000         final int userId = UserHandle.getCallingUserId();
   3001         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
   3002         List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
   3003         return findPreferredActivity(intent, resolvedType, flags, query, 0,
   3004                 false, false, false, userId);
   3005     }
   3006 
   3007     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
   3008             int flags, List<ResolveInfo> query, int userId) {
   3009         if (query != null) {
   3010             final int N = query.size();
   3011             if (N == 1) {
   3012                 return query.get(0);
   3013             } else if (N > 1) {
   3014                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
   3015                 // If there is more than one activity with the same priority,
   3016                 // then let the user decide between them.
   3017                 ResolveInfo r0 = query.get(0);
   3018                 ResolveInfo r1 = query.get(1);
   3019                 if (DEBUG_INTENT_MATCHING || debug) {
   3020                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
   3021                             + r1.activityInfo.name + "=" + r1.priority);
   3022                 }
   3023                 // If the first activity has a higher priority, or a different
   3024                 // default, then it is always desireable to pick it.
   3025                 if (r0.priority != r1.priority
   3026                         || r0.preferredOrder != r1.preferredOrder
   3027                         || r0.isDefault != r1.isDefault) {
   3028                     return query.get(0);
   3029                 }
   3030                 // If we have saved a preference for a preferred activity for
   3031                 // this Intent, use that.
   3032                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
   3033                         flags, query, r0.priority, true, false, debug, userId);
   3034                 if (ri != null) {
   3035                     return ri;
   3036                 }
   3037                 if (userId != 0) {
   3038                     ri = new ResolveInfo(mResolveInfo);
   3039                     ri.activityInfo = new ActivityInfo(ri.activityInfo);
   3040                     ri.activityInfo.applicationInfo = new ApplicationInfo(
   3041                             ri.activityInfo.applicationInfo);
   3042                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
   3043                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
   3044                     return ri;
   3045                 }
   3046                 return mResolveInfo;
   3047             }
   3048         }
   3049         return null;
   3050     }
   3051 
   3052     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
   3053             int flags, List<ResolveInfo> query, boolean debug, int userId) {
   3054         final int N = query.size();
   3055         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
   3056                 .get(userId);
   3057         // Get the list of persistent preferred activities that handle the intent
   3058         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
   3059         List<PersistentPreferredActivity> pprefs = ppir != null
   3060                 ? ppir.queryIntent(intent, resolvedType,
   3061                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
   3062                 : null;
   3063         if (pprefs != null && pprefs.size() > 0) {
   3064             final int M = pprefs.size();
   3065             for (int i=0; i<M; i++) {
   3066                 final PersistentPreferredActivity ppa = pprefs.get(i);
   3067                 if (DEBUG_PREFERRED || debug) {
   3068                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
   3069                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
   3070                             + "\n  component=" + ppa.mComponent);
   3071                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   3072                 }
   3073                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
   3074                         flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
   3075                 if (DEBUG_PREFERRED || debug) {
   3076                     Slog.v(TAG, "Found persistent preferred activity:");
   3077                     if (ai != null) {
   3078                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   3079                     } else {
   3080                         Slog.v(TAG, "  null");
   3081                     }
   3082                 }
   3083                 if (ai == null) {
   3084                     // This previously registered persistent preferred activity
   3085                     // component is no longer known. Ignore it and do NOT remove it.
   3086                     continue;
   3087                 }
   3088                 for (int j=0; j<N; j++) {
   3089                     final ResolveInfo ri = query.get(j);
   3090                     if (!ri.activityInfo.applicationInfo.packageName
   3091                             .equals(ai.applicationInfo.packageName)) {
   3092                         continue;
   3093                     }
   3094                     if (!ri.activityInfo.name.equals(ai.name)) {
   3095                         continue;
   3096                     }
   3097                     //  Found a persistent preference that can handle the intent.
   3098                     if (DEBUG_PREFERRED || debug) {
   3099                         Slog.v(TAG, "Returning persistent preferred activity: " +
   3100                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
   3101                     }
   3102                     return ri;
   3103                 }
   3104             }
   3105         }
   3106         return null;
   3107     }
   3108 
   3109     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
   3110             List<ResolveInfo> query, int priority, boolean always,
   3111             boolean removeMatches, boolean debug, int userId) {
   3112         if (!sUserManager.exists(userId)) return null;
   3113         // writer
   3114         synchronized (mPackages) {
   3115             if (intent.getSelector() != null) {
   3116                 intent = intent.getSelector();
   3117             }
   3118             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
   3119 
   3120             // Try to find a matching persistent preferred activity.
   3121             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
   3122                     debug, userId);
   3123 
   3124             // If a persistent preferred activity matched, use it.
   3125             if (pri != null) {
   3126                 return pri;
   3127             }
   3128 
   3129             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   3130             // Get the list of preferred activities that handle the intent
   3131             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
   3132             List<PreferredActivity> prefs = pir != null
   3133                     ? pir.queryIntent(intent, resolvedType,
   3134                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
   3135                     : null;
   3136             if (prefs != null && prefs.size() > 0) {
   3137                 boolean changed = false;
   3138                 try {
   3139                     // First figure out how good the original match set is.
   3140                     // We will only allow preferred activities that came
   3141                     // from the same match quality.
   3142                     int match = 0;
   3143 
   3144                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
   3145 
   3146                     final int N = query.size();
   3147                     for (int j=0; j<N; j++) {
   3148                         final ResolveInfo ri = query.get(j);
   3149                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
   3150                                 + ": 0x" + Integer.toHexString(match));
   3151                         if (ri.match > match) {
   3152                             match = ri.match;
   3153                         }
   3154                     }
   3155 
   3156                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
   3157                             + Integer.toHexString(match));
   3158 
   3159                     match &= IntentFilter.MATCH_CATEGORY_MASK;
   3160                     final int M = prefs.size();
   3161                     for (int i=0; i<M; i++) {
   3162                         final PreferredActivity pa = prefs.get(i);
   3163                         if (DEBUG_PREFERRED || debug) {
   3164                             Slog.v(TAG, "Checking PreferredActivity ds="
   3165                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
   3166                                     + "\n  component=" + pa.mPref.mComponent);
   3167                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   3168                         }
   3169                         if (pa.mPref.mMatch != match) {
   3170                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
   3171                                     + Integer.toHexString(pa.mPref.mMatch));
   3172                             continue;
   3173                         }
   3174                         // If it's not an "always" type preferred activity and that's what we're
   3175                         // looking for, skip it.
   3176                         if (always && !pa.mPref.mAlways) {
   3177                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
   3178                             continue;
   3179                         }
   3180                         final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
   3181                                 flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
   3182                         if (DEBUG_PREFERRED || debug) {
   3183                             Slog.v(TAG, "Found preferred activity:");
   3184                             if (ai != null) {
   3185                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
   3186                             } else {
   3187                                 Slog.v(TAG, "  null");
   3188                             }
   3189                         }
   3190                         if (ai == null) {
   3191                             // This previously registered preferred activity
   3192                             // component is no longer known.  Most likely an update
   3193                             // to the app was installed and in the new version this
   3194                             // component no longer exists.  Clean it up by removing
   3195                             // it from the preferred activities list, and skip it.
   3196                             Slog.w(TAG, "Removing dangling preferred activity: "
   3197                                     + pa.mPref.mComponent);
   3198                             pir.removeFilter(pa);
   3199                             changed = true;
   3200                             continue;
   3201                         }
   3202                         for (int j=0; j<N; j++) {
   3203                             final ResolveInfo ri = query.get(j);
   3204                             if (!ri.activityInfo.applicationInfo.packageName
   3205                                     .equals(ai.applicationInfo.packageName)) {
   3206                                 continue;
   3207                             }
   3208                             if (!ri.activityInfo.name.equals(ai.name)) {
   3209                                 continue;
   3210                             }
   3211 
   3212                             if (removeMatches) {
   3213                                 pir.removeFilter(pa);
   3214                                 changed = true;
   3215                                 if (DEBUG_PREFERRED) {
   3216                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
   3217                                 }
   3218                                 break;
   3219                             }
   3220 
   3221                             // Okay we found a previously set preferred or last chosen app.
   3222                             // If the result set is different from when this
   3223                             // was created, we need to clear it and re-ask the
   3224                             // user their preference, if we're looking for an "always" type entry.
   3225                             if (always && !pa.mPref.sameSet(query, priority)) {
   3226                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
   3227                                         + intent + " type " + resolvedType);
   3228                                 if (DEBUG_PREFERRED) {
   3229                                     Slog.v(TAG, "Removing preferred activity since set changed "
   3230                                             + pa.mPref.mComponent);
   3231                                 }
   3232                                 pir.removeFilter(pa);
   3233                                 // Re-add the filter as a "last chosen" entry (!always)
   3234                                 PreferredActivity lastChosen = new PreferredActivity(
   3235                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
   3236                                 pir.addFilter(lastChosen);
   3237                                 changed = true;
   3238                                 return null;
   3239                             }
   3240 
   3241                             // Yay! Either the set matched or we're looking for the last chosen
   3242                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
   3243                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
   3244                             return ri;
   3245                         }
   3246                     }
   3247                 } finally {
   3248                     if (changed) {
   3249                         if (DEBUG_PREFERRED) {
   3250                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
   3251                         }
   3252                         mSettings.writePackageRestrictionsLPr(userId);
   3253                     }
   3254                 }
   3255             }
   3256         }
   3257         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
   3258         return null;
   3259     }
   3260 
   3261     /*
   3262      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
   3263      */
   3264     @Override
   3265     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
   3266             int targetUserId) {
   3267         mContext.enforceCallingOrSelfPermission(
   3268                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   3269         List<CrossProfileIntentFilter> matches =
   3270                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
   3271         if (matches != null) {
   3272             int size = matches.size();
   3273             for (int i = 0; i < size; i++) {
   3274                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
   3275             }
   3276         }
   3277         return false;
   3278     }
   3279 
   3280     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
   3281             String resolvedType, int userId) {
   3282         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
   3283         if (resolver != null) {
   3284             return resolver.queryIntent(intent, resolvedType, false, userId);
   3285         }
   3286         return null;
   3287     }
   3288 
   3289     @Override
   3290     public List<ResolveInfo> queryIntentActivities(Intent intent,
   3291             String resolvedType, int flags, int userId) {
   3292         if (!sUserManager.exists(userId)) return Collections.emptyList();
   3293         enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
   3294         ComponentName comp = intent.getComponent();
   3295         if (comp == null) {
   3296             if (intent.getSelector() != null) {
   3297                 intent = intent.getSelector();
   3298                 comp = intent.getComponent();
   3299             }
   3300         }
   3301 
   3302         if (comp != null) {
   3303             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   3304             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
   3305             if (ai != null) {
   3306                 final ResolveInfo ri = new ResolveInfo();
   3307                 ri.activityInfo = ai;
   3308                 list.add(ri);
   3309             }
   3310             return list;
   3311         }
   3312 
   3313         // reader
   3314         synchronized (mPackages) {
   3315             final String pkgName = intent.getPackage();
   3316             if (pkgName == null) {
   3317                 List<CrossProfileIntentFilter> matchingFilters =
   3318                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
   3319                 // Check for results that need to skip the current profile.
   3320                 ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
   3321                         resolvedType, flags, userId);
   3322                 if (resolveInfo != null) {
   3323                     List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
   3324                     result.add(resolveInfo);
   3325                     return result;
   3326                 }
   3327                 // Check for cross profile results.
   3328                 resolveInfo = queryCrossProfileIntents(
   3329                         matchingFilters, intent, resolvedType, flags, userId);
   3330 
   3331                 // Check for results in the current profile.
   3332                 List<ResolveInfo> result = mActivities.queryIntent(
   3333                         intent, resolvedType, flags, userId);
   3334                 if (resolveInfo != null) {
   3335                     result.add(resolveInfo);
   3336                     Collections.sort(result, mResolvePrioritySorter);
   3337                 }
   3338                 return result;
   3339             }
   3340             final PackageParser.Package pkg = mPackages.get(pkgName);
   3341             if (pkg != null) {
   3342                 return mActivities.queryIntentForPackage(intent, resolvedType, flags,
   3343                         pkg.activities, userId);
   3344             }
   3345             return new ArrayList<ResolveInfo>();
   3346         }
   3347     }
   3348 
   3349     private ResolveInfo querySkipCurrentProfileIntents(
   3350             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
   3351             int flags, int sourceUserId) {
   3352         if (matchingFilters != null) {
   3353             int size = matchingFilters.size();
   3354             for (int i = 0; i < size; i ++) {
   3355                 CrossProfileIntentFilter filter = matchingFilters.get(i);
   3356                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
   3357                     // Checking if there are activities in the target user that can handle the
   3358                     // intent.
   3359                     ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
   3360                             flags, sourceUserId);
   3361                     if (resolveInfo != null) {
   3362                         return resolveInfo;
   3363                     }
   3364                 }
   3365             }
   3366         }
   3367         return null;
   3368     }
   3369 
   3370     // Return matching ResolveInfo if any for skip current profile intent filters.
   3371     private ResolveInfo queryCrossProfileIntents(
   3372             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
   3373             int flags, int sourceUserId) {
   3374         if (matchingFilters != null) {
   3375             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
   3376             // match the same intent. For performance reasons, it is better not to
   3377             // run queryIntent twice for the same userId
   3378             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
   3379             int size = matchingFilters.size();
   3380             for (int i = 0; i < size; i++) {
   3381                 CrossProfileIntentFilter filter = matchingFilters.get(i);
   3382                 int targetUserId = filter.getTargetUserId();
   3383                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
   3384                         && !alreadyTriedUserIds.get(targetUserId)) {
   3385                     // Checking if there are activities in the target user that can handle the
   3386                     // intent.
   3387                     ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
   3388                             flags, sourceUserId);
   3389                     if (resolveInfo != null) return resolveInfo;
   3390                     alreadyTriedUserIds.put(targetUserId, true);
   3391                 }
   3392             }
   3393         }
   3394         return null;
   3395     }
   3396 
   3397     private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
   3398             String resolvedType, int flags, int sourceUserId) {
   3399         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
   3400                 resolvedType, flags, filter.getTargetUserId());
   3401         if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
   3402             return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
   3403         }
   3404         return null;
   3405     }
   3406 
   3407     private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
   3408             int sourceUserId, int targetUserId) {
   3409         ResolveInfo forwardingResolveInfo = new ResolveInfo();
   3410         String className;
   3411         if (targetUserId == UserHandle.USER_OWNER) {
   3412             className = FORWARD_INTENT_TO_USER_OWNER;
   3413         } else {
   3414             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
   3415         }
   3416         ComponentName forwardingActivityComponentName = new ComponentName(
   3417                 mAndroidApplication.packageName, className);
   3418         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
   3419                 sourceUserId);
   3420         if (targetUserId == UserHandle.USER_OWNER) {
   3421             forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
   3422             forwardingResolveInfo.noResourceId = true;
   3423         }
   3424         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
   3425         forwardingResolveInfo.priority = 0;
   3426         forwardingResolveInfo.preferredOrder = 0;
   3427         forwardingResolveInfo.match = 0;
   3428         forwardingResolveInfo.isDefault = true;
   3429         forwardingResolveInfo.filter = filter;
   3430         forwardingResolveInfo.targetUserId = targetUserId;
   3431         return forwardingResolveInfo;
   3432     }
   3433 
   3434     @Override
   3435     public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
   3436             Intent[] specifics, String[] specificTypes, Intent intent,
   3437             String resolvedType, int flags, int userId) {
   3438         if (!sUserManager.exists(userId)) return Collections.emptyList();
   3439         enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
   3440                 false, "query intent activity options");
   3441         final String resultsAction = intent.getAction();
   3442 
   3443         List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
   3444                 | PackageManager.GET_RESOLVED_FILTER, userId);
   3445 
   3446         if (DEBUG_INTENT_MATCHING) {
   3447             Log.v(TAG, "Query " + intent + ": " + results);
   3448         }
   3449 
   3450         int specificsPos = 0;
   3451         int N;
   3452 
   3453         // todo: note that the algorithm used here is O(N^2).  This
   3454         // isn't a problem in our current environment, but if we start running
   3455         // into situations where we have more than 5 or 10 matches then this
   3456         // should probably be changed to something smarter...
   3457 
   3458         // First we go through and resolve each of the specific items
   3459         // that were supplied, taking care of removing any corresponding
   3460         // duplicate items in the generic resolve list.
   3461         if (specifics != null) {
   3462             for (int i=0; i<specifics.length; i++) {
   3463                 final Intent sintent = specifics[i];
   3464                 if (sintent == null) {
   3465                     continue;
   3466                 }
   3467 
   3468                 if (DEBUG_INTENT_MATCHING) {
   3469                     Log.v(TAG, "Specific #" + i + ": " + sintent);
   3470                 }
   3471 
   3472                 String action = sintent.getAction();
   3473                 if (resultsAction != null && resultsAction.equals(action)) {
   3474                     // If this action was explicitly requested, then don't
   3475                     // remove things that have it.
   3476                     action = null;
   3477                 }
   3478 
   3479                 ResolveInfo ri = null;
   3480                 ActivityInfo ai = null;
   3481 
   3482                 ComponentName comp = sintent.getComponent();
   3483                 if (comp == null) {
   3484                     ri = resolveIntent(
   3485                         sintent,
   3486                         specificTypes != null ? specificTypes[i] : null,
   3487                             flags, userId);
   3488                     if (ri == null) {
   3489                         continue;
   3490                     }
   3491                     if (ri == mResolveInfo) {
   3492                         // ACK!  Must do something better with this.
   3493                     }
   3494                     ai = ri.activityInfo;
   3495                     comp = new ComponentName(ai.applicationInfo.packageName,
   3496                             ai.name);
   3497                 } else {
   3498                     ai = getActivityInfo(comp, flags, userId);
   3499                     if (ai == null) {
   3500                         continue;
   3501                     }
   3502                 }
   3503 
   3504                 // Look for any generic query activities that are duplicates
   3505                 // of this specific one, and remove them from the results.
   3506                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
   3507                 N = results.size();
   3508                 int j;
   3509                 for (j=specificsPos; j<N; j++) {
   3510                     ResolveInfo sri = results.get(j);
   3511                     if ((sri.activityInfo.name.equals(comp.getClassName())
   3512                             && sri.activityInfo.applicationInfo.packageName.equals(
   3513                                     comp.getPackageName()))
   3514                         || (action != null && sri.filter.matchAction(action))) {
   3515                         results.remove(j);
   3516                         if (DEBUG_INTENT_MATCHING) Log.v(
   3517                             TAG, "Removing duplicate item from " + j
   3518                             + " due to specific " + specificsPos);
   3519                         if (ri == null) {
   3520                             ri = sri;
   3521                         }
   3522                         j--;
   3523                         N--;
   3524                     }
   3525                 }
   3526 
   3527                 // Add this specific item to its proper place.
   3528                 if (ri == null) {
   3529                     ri = new ResolveInfo();
   3530                     ri.activityInfo = ai;
   3531                 }
   3532                 results.add(specificsPos, ri);
   3533                 ri.specificIndex = i;
   3534                 specificsPos++;
   3535             }
   3536         }
   3537 
   3538         // Now we go through the remaining generic results and remove any
   3539         // duplicate actions that are found here.
   3540         N = results.size();
   3541         for (int i=specificsPos; i<N-1; i++) {
   3542             final ResolveInfo rii = results.get(i);
   3543             if (rii.filter == null) {
   3544                 continue;
   3545             }
   3546 
   3547             // Iterate over all of the actions of this result's intent
   3548             // filter...  typically this should be just one.
   3549             final Iterator<String> it = rii.filter.actionsIterator();
   3550             if (it == null) {
   3551                 continue;
   3552             }
   3553             while (it.hasNext()) {
   3554                 final String action = it.next();
   3555                 if (resultsAction != null && resultsAction.equals(action)) {
   3556                     // If this action was explicitly requested, then don't
   3557                     // remove things that have it.
   3558                     continue;
   3559                 }
   3560                 for (int j=i+1; j<N; j++) {
   3561                     final ResolveInfo rij = results.get(j);
   3562                     if (rij.filter != null && rij.filter.hasAction(action)) {
   3563                         results.remove(j);
   3564                         if (DEBUG_INTENT_MATCHING) Log.v(
   3565                             TAG, "Removing duplicate item from " + j
   3566                             + " due to action " + action + " at " + i);
   3567                         j--;
   3568                         N--;
   3569                     }
   3570                 }
   3571             }
   3572 
   3573             // If the caller didn't request filter information, drop it now
   3574             // so we don't have to marshall/unmarshall it.
   3575             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
   3576                 rii.filter = null;
   3577             }
   3578         }
   3579 
   3580         // Filter out the caller activity if so requested.
   3581         if (caller != null) {
   3582             N = results.size();
   3583             for (int i=0; i<N; i++) {
   3584                 ActivityInfo ainfo = results.get(i).activityInfo;
   3585                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
   3586                         && caller.getClassName().equals(ainfo.name)) {
   3587                     results.remove(i);
   3588                     break;
   3589                 }
   3590             }
   3591         }
   3592 
   3593         // If the caller didn't request filter information,
   3594         // drop them now so we don't have to
   3595         // marshall/unmarshall it.
   3596         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
   3597             N = results.size();
   3598             for (int i=0; i<N; i++) {
   3599                 results.get(i).filter = null;
   3600             }
   3601         }
   3602 
   3603         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
   3604         return results;
   3605     }
   3606 
   3607     @Override
   3608     public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
   3609             int userId) {
   3610         if (!sUserManager.exists(userId)) return Collections.emptyList();
   3611         ComponentName comp = intent.getComponent();
   3612         if (comp == null) {
   3613             if (intent.getSelector() != null) {
   3614                 intent = intent.getSelector();
   3615                 comp = intent.getComponent();
   3616             }
   3617         }
   3618         if (comp != null) {
   3619             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   3620             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
   3621             if (ai != null) {
   3622                 ResolveInfo ri = new ResolveInfo();
   3623                 ri.activityInfo = ai;
   3624                 list.add(ri);
   3625             }
   3626             return list;
   3627         }
   3628 
   3629         // reader
   3630         synchronized (mPackages) {
   3631             String pkgName = intent.getPackage();
   3632             if (pkgName == null) {
   3633                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
   3634             }
   3635             final PackageParser.Package pkg = mPackages.get(pkgName);
   3636             if (pkg != null) {
   3637                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
   3638                         userId);
   3639             }
   3640             return null;
   3641         }
   3642     }
   3643 
   3644     @Override
   3645     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
   3646         List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
   3647         if (!sUserManager.exists(userId)) return null;
   3648         if (query != null) {
   3649             if (query.size() >= 1) {
   3650                 // If there is more than one service with the same priority,
   3651                 // just arbitrarily pick the first one.
   3652                 return query.get(0);
   3653             }
   3654         }
   3655         return null;
   3656     }
   3657 
   3658     @Override
   3659     public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
   3660             int userId) {
   3661         if (!sUserManager.exists(userId)) return Collections.emptyList();
   3662         ComponentName comp = intent.getComponent();
   3663         if (comp == null) {
   3664             if (intent.getSelector() != null) {
   3665                 intent = intent.getSelector();
   3666                 comp = intent.getComponent();
   3667             }
   3668         }
   3669         if (comp != null) {
   3670             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   3671             final ServiceInfo si = getServiceInfo(comp, flags, userId);
   3672             if (si != null) {
   3673                 final ResolveInfo ri = new ResolveInfo();
   3674                 ri.serviceInfo = si;
   3675                 list.add(ri);
   3676             }
   3677             return list;
   3678         }
   3679 
   3680         // reader
   3681         synchronized (mPackages) {
   3682             String pkgName = intent.getPackage();
   3683             if (pkgName == null) {
   3684                 return mServices.queryIntent(intent, resolvedType, flags, userId);
   3685             }
   3686             final PackageParser.Package pkg = mPackages.get(pkgName);
   3687             if (pkg != null) {
   3688                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
   3689                         userId);
   3690             }
   3691             return null;
   3692         }
   3693     }
   3694 
   3695     @Override
   3696     public List<ResolveInfo> queryIntentContentProviders(
   3697             Intent intent, String resolvedType, int flags, int userId) {
   3698         if (!sUserManager.exists(userId)) return Collections.emptyList();
   3699         ComponentName comp = intent.getComponent();
   3700         if (comp == null) {
   3701             if (intent.getSelector() != null) {
   3702                 intent = intent.getSelector();
   3703                 comp = intent.getComponent();
   3704             }
   3705         }
   3706         if (comp != null) {
   3707             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
   3708             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
   3709             if (pi != null) {
   3710                 final ResolveInfo ri = new ResolveInfo();
   3711                 ri.providerInfo = pi;
   3712                 list.add(ri);
   3713             }
   3714             return list;
   3715         }
   3716 
   3717         // reader
   3718         synchronized (mPackages) {
   3719             String pkgName = intent.getPackage();
   3720             if (pkgName == null) {
   3721                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
   3722             }
   3723             final PackageParser.Package pkg = mPackages.get(pkgName);
   3724             if (pkg != null) {
   3725                 return mProviders.queryIntentForPackage(
   3726                         intent, resolvedType, flags, pkg.providers, userId);
   3727             }
   3728             return null;
   3729         }
   3730     }
   3731 
   3732     @Override
   3733     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
   3734         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
   3735 
   3736         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
   3737 
   3738         // writer
   3739         synchronized (mPackages) {
   3740             ArrayList<PackageInfo> list;
   3741             if (listUninstalled) {
   3742                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
   3743                 for (PackageSetting ps : mSettings.mPackages.values()) {
   3744                     PackageInfo pi;
   3745                     if (ps.pkg != null) {
   3746                         pi = generatePackageInfo(ps.pkg, flags, userId);
   3747                     } else {
   3748                         pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
   3749                     }
   3750                     if (pi != null) {
   3751                         list.add(pi);
   3752                     }
   3753                 }
   3754             } else {
   3755                 list = new ArrayList<PackageInfo>(mPackages.size());
   3756                 for (PackageParser.Package p : mPackages.values()) {
   3757                     PackageInfo pi = generatePackageInfo(p, flags, userId);
   3758                     if (pi != null) {
   3759                         list.add(pi);
   3760                     }
   3761                 }
   3762             }
   3763 
   3764             return new ParceledListSlice<PackageInfo>(list);
   3765         }
   3766     }
   3767 
   3768     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
   3769             String[] permissions, boolean[] tmp, int flags, int userId) {
   3770         int numMatch = 0;
   3771         final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
   3772         for (int i=0; i<permissions.length; i++) {
   3773             if (gp.grantedPermissions.contains(permissions[i])) {
   3774                 tmp[i] = true;
   3775                 numMatch++;
   3776             } else {
   3777                 tmp[i] = false;
   3778             }
   3779         }
   3780         if (numMatch == 0) {
   3781             return;
   3782         }
   3783         PackageInfo pi;
   3784         if (ps.pkg != null) {
   3785             pi = generatePackageInfo(ps.pkg, flags, userId);
   3786         } else {
   3787             pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
   3788         }
   3789         // The above might return null in cases of uninstalled apps or install-state
   3790         // skew across users/profiles.
   3791         if (pi != null) {
   3792             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
   3793                 if (numMatch == permissions.length) {
   3794                     pi.requestedPermissions = permissions;
   3795                 } else {
   3796                     pi.requestedPermissions = new String[numMatch];
   3797                     numMatch = 0;
   3798                     for (int i=0; i<permissions.length; i++) {
   3799                         if (tmp[i]) {
   3800                             pi.requestedPermissions[numMatch] = permissions[i];
   3801                             numMatch++;
   3802                         }
   3803                     }
   3804                 }
   3805             }
   3806             list.add(pi);
   3807         }
   3808     }
   3809 
   3810     @Override
   3811     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
   3812             String[] permissions, int flags, int userId) {
   3813         if (!sUserManager.exists(userId)) return null;
   3814         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
   3815 
   3816         // writer
   3817         synchronized (mPackages) {
   3818             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
   3819             boolean[] tmpBools = new boolean[permissions.length];
   3820             if (listUninstalled) {
   3821                 for (PackageSetting ps : mSettings.mPackages.values()) {
   3822                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
   3823                 }
   3824             } else {
   3825                 for (PackageParser.Package pkg : mPackages.values()) {
   3826                     PackageSetting ps = (PackageSetting)pkg.mExtras;
   3827                     if (ps != null) {
   3828                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
   3829                                 userId);
   3830                     }
   3831                 }
   3832             }
   3833 
   3834             return new ParceledListSlice<PackageInfo>(list);
   3835         }
   3836     }
   3837 
   3838     @Override
   3839     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
   3840         if (!sUserManager.exists(userId)) return null;
   3841         final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
   3842 
   3843         // writer
   3844         synchronized (mPackages) {
   3845             ArrayList<ApplicationInfo> list;
   3846             if (listUninstalled) {
   3847                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
   3848                 for (PackageSetting ps : mSettings.mPackages.values()) {
   3849                     ApplicationInfo ai;
   3850                     if (ps.pkg != null) {
   3851                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
   3852                                 ps.readUserState(userId), userId);
   3853                     } else {
   3854                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
   3855                     }
   3856                     if (ai != null) {
   3857                         list.add(ai);
   3858                     }
   3859                 }
   3860             } else {
   3861                 list = new ArrayList<ApplicationInfo>(mPackages.size());
   3862                 for (PackageParser.Package p : mPackages.values()) {
   3863                     if (p.mExtras != null) {
   3864                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
   3865                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
   3866                         if (ai != null) {
   3867                             list.add(ai);
   3868                         }
   3869                     }
   3870                 }
   3871             }
   3872 
   3873             return new ParceledListSlice<ApplicationInfo>(list);
   3874         }
   3875     }
   3876 
   3877     public List<ApplicationInfo> getPersistentApplications(int flags) {
   3878         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
   3879 
   3880         // reader
   3881         synchronized (mPackages) {
   3882             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
   3883             final int userId = UserHandle.getCallingUserId();
   3884             while (i.hasNext()) {
   3885                 final PackageParser.Package p = i.next();
   3886                 if (p.applicationInfo != null
   3887                         && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
   3888                         && (!mSafeMode || isSystemApp(p))) {
   3889                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
   3890                     if (ps != null) {
   3891                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
   3892                                 ps.readUserState(userId), userId);
   3893                         if (ai != null) {
   3894                             finalList.add(ai);
   3895                         }
   3896                     }
   3897                 }
   3898             }
   3899         }
   3900 
   3901         return finalList;
   3902     }
   3903 
   3904     @Override
   3905     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
   3906         if (!sUserManager.exists(userId)) return null;
   3907         // reader
   3908         synchronized (mPackages) {
   3909             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
   3910             PackageSetting ps = provider != null
   3911                     ? mSettings.mPackages.get(provider.owner.packageName)
   3912                     : null;
   3913             return ps != null
   3914                     && mSettings.isEnabledLPr(provider.info, flags, userId)
   3915                     && (!mSafeMode || (provider.info.applicationInfo.flags
   3916                             &ApplicationInfo.FLAG_SYSTEM) != 0)
   3917                     ? PackageParser.generateProviderInfo(provider, flags,
   3918                             ps.readUserState(userId), userId)
   3919                     : null;
   3920         }
   3921     }
   3922 
   3923     /**
   3924      * @deprecated
   3925      */
   3926     @Deprecated
   3927     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
   3928         // reader
   3929         synchronized (mPackages) {
   3930             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
   3931                     .entrySet().iterator();
   3932             final int userId = UserHandle.getCallingUserId();
   3933             while (i.hasNext()) {
   3934                 Map.Entry<String, PackageParser.Provider> entry = i.next();
   3935                 PackageParser.Provider p = entry.getValue();
   3936                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
   3937 
   3938                 if (ps != null && p.syncable
   3939                         && (!mSafeMode || (p.info.applicationInfo.flags
   3940                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
   3941                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
   3942                             ps.readUserState(userId), userId);
   3943                     if (info != null) {
   3944                         outNames.add(entry.getKey());
   3945                         outInfo.add(info);
   3946                     }
   3947                 }
   3948             }
   3949         }
   3950     }
   3951 
   3952     @Override
   3953     public List<ProviderInfo> queryContentProviders(String processName,
   3954             int uid, int flags) {
   3955         ArrayList<ProviderInfo> finalList = null;
   3956         // reader
   3957         synchronized (mPackages) {
   3958             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
   3959             final int userId = processName != null ?
   3960                     UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
   3961             while (i.hasNext()) {
   3962                 final PackageParser.Provider p = i.next();
   3963                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
   3964                 if (ps != null && p.info.authority != null
   3965                         && (processName == null
   3966                                 || (p.info.processName.equals(processName)
   3967                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
   3968                         && mSettings.isEnabledLPr(p.info, flags, userId)
   3969                         && (!mSafeMode
   3970                                 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
   3971                     if (finalList == null) {
   3972                         finalList = new ArrayList<ProviderInfo>(3);
   3973                     }
   3974                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
   3975                             ps.readUserState(userId), userId);
   3976                     if (info != null) {
   3977                         finalList.add(info);
   3978                     }
   3979                 }
   3980             }
   3981         }
   3982 
   3983         if (finalList != null) {
   3984             Collections.sort(finalList, mProviderInitOrderSorter);
   3985         }
   3986 
   3987         return finalList;
   3988     }
   3989 
   3990     @Override
   3991     public InstrumentationInfo getInstrumentationInfo(ComponentName name,
   3992             int flags) {
   3993         // reader
   3994         synchronized (mPackages) {
   3995             final PackageParser.Instrumentation i = mInstrumentation.get(name);
   3996             return PackageParser.generateInstrumentationInfo(i, flags);
   3997         }
   3998     }
   3999 
   4000     @Override
   4001     public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
   4002             int flags) {
   4003         ArrayList<InstrumentationInfo> finalList =
   4004             new ArrayList<InstrumentationInfo>();
   4005 
   4006         // reader
   4007         synchronized (mPackages) {
   4008             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
   4009             while (i.hasNext()) {
   4010                 final PackageParser.Instrumentation p = i.next();
   4011                 if (targetPackage == null
   4012                         || targetPackage.equals(p.info.targetPackage)) {
   4013                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
   4014                             flags);
   4015                     if (ii != null) {
   4016                         finalList.add(ii);
   4017                     }
   4018                 }
   4019             }
   4020         }
   4021 
   4022         return finalList;
   4023     }
   4024 
   4025     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
   4026         HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
   4027         if (overlays == null) {
   4028             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
   4029             return;
   4030         }
   4031         for (PackageParser.Package opkg : overlays.values()) {
   4032             // Not much to do if idmap fails: we already logged the error
   4033             // and we certainly don't want to abort installation of pkg simply
   4034             // because an overlay didn't fit properly. For these reasons,
   4035             // ignore the return value of createIdmapForPackagePairLI.
   4036             createIdmapForPackagePairLI(pkg, opkg);
   4037         }
   4038     }
   4039 
   4040     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
   4041             PackageParser.Package opkg) {
   4042         if (!opkg.mTrustedOverlay) {
   4043             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
   4044                     opkg.baseCodePath + ": overlay not trusted");
   4045             return false;
   4046         }
   4047         HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
   4048         if (overlaySet == null) {
   4049             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
   4050                     opkg.baseCodePath + " but target package has no known overlays");
   4051             return false;
   4052         }
   4053         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
   4054         // TODO: generate idmap for split APKs
   4055         if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
   4056             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
   4057                     + opkg.baseCodePath);
   4058             return false;
   4059         }
   4060         PackageParser.Package[] overlayArray =
   4061             overlaySet.values().toArray(new PackageParser.Package[0]);
   4062         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
   4063             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
   4064                 return p1.mOverlayPriority - p2.mOverlayPriority;
   4065             }
   4066         };
   4067         Arrays.sort(overlayArray, cmp);
   4068 
   4069         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
   4070         int i = 0;
   4071         for (PackageParser.Package p : overlayArray) {
   4072             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
   4073         }
   4074         return true;
   4075     }
   4076 
   4077     private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
   4078         final File[] files = dir.listFiles();
   4079         if (ArrayUtils.isEmpty(files)) {
   4080             Log.d(TAG, "No files in app dir " + dir);
   4081             return;
   4082         }
   4083 
   4084         if (DEBUG_PACKAGE_SCANNING) {
   4085             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
   4086                     + " flags=0x" + Integer.toHexString(parseFlags));
   4087         }
   4088 
   4089         for (File file : files) {
   4090             final boolean isPackage = (isApkFile(file) || file.isDirectory())
   4091                     && !PackageInstallerService.isStageName(file.getName());
   4092             if (!isPackage) {
   4093                 // Ignore entries which are not packages
   4094                 continue;
   4095             }
   4096             try {
   4097                 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
   4098                         scanFlags, currentTime, null);
   4099             } catch (PackageManagerException e) {
   4100                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
   4101 
   4102                 // Delete invalid userdata apps
   4103                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
   4104                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
   4105                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
   4106                     if (file.isDirectory()) {
   4107                         FileUtils.deleteContents(file);
   4108                     }
   4109                     file.delete();
   4110                 }
   4111             }
   4112         }
   4113     }
   4114 
   4115     private static File getSettingsProblemFile() {
   4116         File dataDir = Environment.getDataDirectory();
   4117         File systemDir = new File(dataDir, "system");
   4118         File fname = new File(systemDir, "uiderrors.txt");
   4119         return fname;
   4120     }
   4121 
   4122     static void reportSettingsProblem(int priority, String msg) {
   4123         logCriticalInfo(priority, msg);
   4124     }
   4125 
   4126     static void logCriticalInfo(int priority, String msg) {
   4127         Slog.println(priority, TAG, msg);
   4128         EventLogTags.writePmCriticalInfo(msg);
   4129         try {
   4130             File fname = getSettingsProblemFile();
   4131             FileOutputStream out = new FileOutputStream(fname, true);
   4132             PrintWriter pw = new FastPrintWriter(out);
   4133             SimpleDateFormat formatter = new SimpleDateFormat();
   4134             String dateString = formatter.format(new Date(System.currentTimeMillis()));
   4135             pw.println(dateString + ": " + msg);
   4136             pw.close();
   4137             FileUtils.setPermissions(
   4138                     fname.toString(),
   4139                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
   4140                     -1, -1);
   4141         } catch (java.io.IOException e) {
   4142         }
   4143     }
   4144 
   4145     private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
   4146             PackageParser.Package pkg, File srcFile, int parseFlags)
   4147             throws PackageManagerException {
   4148         if (ps != null
   4149                 && ps.codePath.equals(srcFile)
   4150                 && ps.timeStamp == srcFile.lastModified()
   4151                 && !isCompatSignatureUpdateNeeded(pkg)) {
   4152             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
   4153             if (ps.signatures.mSignatures != null
   4154                     && ps.signatures.mSignatures.length != 0
   4155                     && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
   4156                 // Optimization: reuse the existing cached certificates
   4157                 // if the package appears to be unchanged.
   4158                 pkg.mSignatures = ps.signatures.mSignatures;
   4159                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
   4160                 synchronized (mPackages) {
   4161                     pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
   4162                 }
   4163                 return;
   4164             }
   4165 
   4166             Slog.w(TAG, "PackageSetting for " + ps.name
   4167                     + " is missing signatures.  Collecting certs again to recover them.");
   4168         } else {
   4169             Log.i(TAG, srcFile.toString() + " changed; collecting certs");
   4170         }
   4171 
   4172         try {
   4173             pp.collectCertificates(pkg, parseFlags);
   4174             pp.collectManifestDigest(pkg);
   4175         } catch (PackageParserException e) {
   4176             throw PackageManagerException.from(e);
   4177         }
   4178     }
   4179 
   4180     /*
   4181      *  Scan a package and return the newly parsed package.
   4182      *  Returns null in case of errors and the error code is stored in mLastScanError
   4183      */
   4184     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
   4185             long currentTime, UserHandle user) throws PackageManagerException {
   4186         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
   4187         parseFlags |= mDefParseFlags;
   4188         PackageParser pp = new PackageParser();
   4189         pp.setSeparateProcesses(mSeparateProcesses);
   4190         pp.setOnlyCoreApps(mOnlyCore);
   4191         pp.setDisplayMetrics(mMetrics);
   4192 
   4193         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
   4194             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
   4195         }
   4196 
   4197         final PackageParser.Package pkg;
   4198         try {
   4199             pkg = pp.parsePackage(scanFile, parseFlags);
   4200         } catch (PackageParserException e) {
   4201             throw PackageManagerException.from(e);
   4202         }
   4203 
   4204         PackageSetting ps = null;
   4205         PackageSetting updatedPkg;
   4206         // reader
   4207         synchronized (mPackages) {
   4208             // Look to see if we already know about this package.
   4209             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
   4210             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
   4211                 // This package has been renamed to its original name.  Let's
   4212                 // use that.
   4213                 ps = mSettings.peekPackageLPr(oldName);
   4214             }
   4215             // If there was no original package, see one for the real package name.
   4216             if (ps == null) {
   4217                 ps = mSettings.peekPackageLPr(pkg.packageName);
   4218             }
   4219             // Check to see if this package could be hiding/updating a system
   4220             // package.  Must look for it either under the original or real
   4221             // package name depending on our state.
   4222             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
   4223             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
   4224         }
   4225         boolean updatedPkgBetter = false;
   4226         // First check if this is a system package that may involve an update
   4227         if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
   4228             if (ps != null && !ps.codePath.equals(scanFile)) {
   4229                 // The path has changed from what was last scanned...  check the
   4230                 // version of the new path against what we have stored to determine
   4231                 // what to do.
   4232                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
   4233                 if (pkg.mVersionCode < ps.versionCode) {
   4234                     // The system package has been updated and the code path does not match
   4235                     // Ignore entry. Skip it.
   4236                     logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
   4237                             + " ignored: updated version " + ps.versionCode
   4238                             + " better than this " + pkg.mVersionCode);
   4239                     if (!updatedPkg.codePath.equals(scanFile)) {
   4240                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
   4241                                 + ps.name + " changing from " + updatedPkg.codePathString
   4242                                 + " to " + scanFile);
   4243                         updatedPkg.codePath = scanFile;
   4244                         updatedPkg.codePathString = scanFile.toString();
   4245                         // This is the point at which we know that the system-disk APK
   4246                         // for this package has moved during a reboot (e.g. due to an OTA),
   4247                         // so we need to reevaluate it for privilege policy.
   4248                         if (locationIsPrivileged(scanFile)) {
   4249                             updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
   4250                         }
   4251                     }
   4252                     updatedPkg.pkg = pkg;
   4253                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
   4254                 } else {
   4255                     // The current app on the system partition is better than
   4256                     // what we have updated to on the data partition; switch
   4257                     // back to the system partition version.
   4258                     // At this point, its safely assumed that package installation for
   4259                     // apps in system partition will go through. If not there won't be a working
   4260                     // version of the app
   4261                     // writer
   4262                     synchronized (mPackages) {
   4263                         // Just remove the loaded entries from package lists.
   4264                         mPackages.remove(ps.name);
   4265                     }
   4266 
   4267                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
   4268                             + " reverting from " + ps.codePathString
   4269                             + ": new version " + pkg.mVersionCode
   4270                             + " better than installed " + ps.versionCode);
   4271 
   4272                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
   4273                             ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
   4274                             getAppDexInstructionSets(ps));
   4275                     synchronized (mInstallLock) {
   4276                         args.cleanUpResourcesLI();
   4277                     }
   4278                     synchronized (mPackages) {
   4279                         mSettings.enableSystemPackageLPw(ps.name);
   4280                     }
   4281                     updatedPkgBetter = true;
   4282                 }
   4283             }
   4284         }
   4285 
   4286         if (updatedPkg != null) {
   4287             // An updated system app will not have the PARSE_IS_SYSTEM flag set
   4288             // initially
   4289             parseFlags |= PackageParser.PARSE_IS_SYSTEM;
   4290 
   4291             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
   4292             // flag set initially
   4293             if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
   4294                 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
   4295             }
   4296         }
   4297 
   4298         // Verify certificates against what was last scanned
   4299         collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
   4300 
   4301         /*
   4302          * A new system app appeared, but we already had a non-system one of the
   4303          * same name installed earlier.
   4304          */
   4305         boolean shouldHideSystemApp = false;
   4306         if (updatedPkg == null && ps != null
   4307                 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
   4308             /*
   4309              * Check to make sure the signatures match first. If they don't,
   4310              * wipe the installed application and its data.
   4311              */
   4312             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
   4313                     != PackageManager.SIGNATURE_MATCH) {
   4314                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
   4315                         + " signatures don't match existing userdata copy; removing");
   4316                 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
   4317                 ps = null;
   4318             } else {
   4319                 /*
   4320                  * If the newly-added system app is an older version than the
   4321                  * already installed version, hide it. It will be scanned later
   4322                  * and re-added like an update.
   4323                  */
   4324                 if (pkg.mVersionCode < ps.versionCode) {
   4325                     shouldHideSystemApp = true;
   4326                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
   4327                             + " but new version " + pkg.mVersionCode + " better than installed "
   4328                             + ps.versionCode + "; hiding system");
   4329                 } else {
   4330                     /*
   4331                      * The newly found system app is a newer version that the
   4332                      * one previously installed. Simply remove the
   4333                      * already-installed application and replace it with our own
   4334                      * while keeping the application data.
   4335                      */
   4336                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
   4337                             + " reverting from " + ps.codePathString + ": new version "
   4338                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
   4339                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
   4340                             ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
   4341                             getAppDexInstructionSets(ps));
   4342                     synchronized (mInstallLock) {
   4343                         args.cleanUpResourcesLI();
   4344                     }
   4345                 }
   4346             }
   4347         }
   4348 
   4349         // The apk is forward locked (not public) if its code and resources
   4350         // are kept in different files. (except for app in either system or
   4351         // vendor path).
   4352         // TODO grab this value from PackageSettings
   4353         if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   4354             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
   4355                 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
   4356             }
   4357         }
   4358 
   4359         // TODO: extend to support forward-locked splits
   4360         String resourcePath = null;
   4361         String baseResourcePath = null;
   4362         if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
   4363             if (ps != null && ps.resourcePathString != null) {
   4364                 resourcePath = ps.resourcePathString;
   4365                 baseResourcePath = ps.resourcePathString;
   4366             } else {
   4367                 // Should not happen at all. Just log an error.
   4368                 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
   4369             }
   4370         } else {
   4371             resourcePath = pkg.codePath;
   4372             baseResourcePath = pkg.baseCodePath;
   4373         }
   4374 
   4375         // Set application objects path explicitly.
   4376         pkg.applicationInfo.setCodePath(pkg.codePath);
   4377         pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
   4378         pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
   4379         pkg.applicationInfo.setResourcePath(resourcePath);
   4380         pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
   4381         pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
   4382 
   4383         // Note that we invoke the following method only if we are about to unpack an application
   4384         PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
   4385                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
   4386 
   4387         /*
   4388          * If the system app should be overridden by a previously installed
   4389          * data, hide the system app now and let the /data/app scan pick it up
   4390          * again.
   4391          */
   4392         if (shouldHideSystemApp) {
   4393             synchronized (mPackages) {
   4394                 /*
   4395                  * We have to grant systems permissions before we hide, because
   4396                  * grantPermissions will assume the package update is trying to
   4397                  * expand its permissions.
   4398                  */
   4399                 grantPermissionsLPw(pkg, true, pkg.packageName);
   4400                 mSettings.disableSystemPackageLPw(pkg.packageName);
   4401             }
   4402         }
   4403 
   4404         return scannedPkg;
   4405     }
   4406 
   4407     private static String fixProcessName(String defProcessName,
   4408             String processName, int uid) {
   4409         if (processName == null) {
   4410             return defProcessName;
   4411         }
   4412         return processName;
   4413     }
   4414 
   4415     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
   4416             throws PackageManagerException {
   4417         if (pkgSetting.signatures.mSignatures != null) {
   4418             // Already existing package. Make sure signatures match
   4419             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
   4420                     == PackageManager.SIGNATURE_MATCH;
   4421             if (!match) {
   4422                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
   4423                         == PackageManager.SIGNATURE_MATCH;
   4424             }
   4425             if (!match) {
   4426                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
   4427                         + pkg.packageName + " signatures do not match the "
   4428                         + "previously installed version; ignoring!");
   4429             }
   4430         }
   4431 
   4432         // Check for shared user signatures
   4433         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
   4434             // Already existing package. Make sure signatures match
   4435             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
   4436                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
   4437             if (!match) {
   4438                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
   4439                         == PackageManager.SIGNATURE_MATCH;
   4440             }
   4441             if (!match) {
   4442                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
   4443                         "Package " + pkg.packageName
   4444                         + " has no signatures that match those in shared user "
   4445                         + pkgSetting.sharedUser.name + "; ignoring!");
   4446             }
   4447         }
   4448     }
   4449 
   4450     /**
   4451      * Enforces that only the system UID or root's UID can call a method exposed
   4452      * via Binder.
   4453      *
   4454      * @param message used as message if SecurityException is thrown
   4455      * @throws SecurityException if the caller is not system or root
   4456      */
   4457     private static final void enforceSystemOrRoot(String message) {
   4458         final int uid = Binder.getCallingUid();
   4459         if (uid != Process.SYSTEM_UID && uid != 0) {
   4460             throw new SecurityException(message);
   4461         }
   4462     }
   4463 
   4464     @Override
   4465     public void performBootDexOpt() {
   4466         enforceSystemOrRoot("Only the system can request dexopt be performed");
   4467 
   4468         final HashSet<PackageParser.Package> pkgs;
   4469         synchronized (mPackages) {
   4470             pkgs = mDeferredDexOpt;
   4471             mDeferredDexOpt = null;
   4472         }
   4473 
   4474         if (pkgs != null) {
   4475             // Sort apps by importance for dexopt ordering. Important apps are given more priority
   4476             // in case the device runs out of space.
   4477             ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
   4478             // Give priority to core apps.
   4479             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
   4480                 PackageParser.Package pkg = it.next();
   4481                 if (pkg.coreApp) {
   4482                     if (DEBUG_DEXOPT) {
   4483                         Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
   4484                     }
   4485                     sortedPkgs.add(pkg);
   4486                     it.remove();
   4487                 }
   4488             }
   4489             // Give priority to system apps that listen for pre boot complete.
   4490             Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
   4491             HashSet<String> pkgNames = getPackageNamesForIntent(intent);
   4492             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
   4493                 PackageParser.Package pkg = it.next();
   4494                 if (pkgNames.contains(pkg.packageName)) {
   4495                     if (DEBUG_DEXOPT) {
   4496                         Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
   4497                     }
   4498                     sortedPkgs.add(pkg);
   4499                     it.remove();
   4500                 }
   4501             }
   4502             // Give priority to system apps.
   4503             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
   4504                 PackageParser.Package pkg = it.next();
   4505                 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
   4506                     if (DEBUG_DEXOPT) {
   4507                         Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
   4508                     }
   4509                     sortedPkgs.add(pkg);
   4510                     it.remove();
   4511                 }
   4512             }
   4513             // Give priority to updated system apps.
   4514             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
   4515                 PackageParser.Package pkg = it.next();
   4516                 if (isUpdatedSystemApp(pkg)) {
   4517                     if (DEBUG_DEXOPT) {
   4518                         Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
   4519                     }
   4520                     sortedPkgs.add(pkg);
   4521                     it.remove();
   4522                 }
   4523             }
   4524             // Give priority to apps that listen for boot complete.
   4525             intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
   4526             pkgNames = getPackageNamesForIntent(intent);
   4527             for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
   4528                 PackageParser.Package pkg = it.next();
   4529                 if (pkgNames.contains(pkg.packageName)) {
   4530                     if (DEBUG_DEXOPT) {
   4531                         Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
   4532                     }
   4533                     sortedPkgs.add(pkg);
   4534                     it.remove();
   4535                 }
   4536             }
   4537             // Filter out packages that aren't recently used.
   4538             filterRecentlyUsedApps(pkgs);
   4539             // Add all remaining apps.
   4540             for (PackageParser.Package pkg : pkgs) {
   4541                 if (DEBUG_DEXOPT) {
   4542                     Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
   4543                 }
   4544                 sortedPkgs.add(pkg);
   4545             }
   4546 
   4547             int i = 0;
   4548             int total = sortedPkgs.size();
   4549             File dataDir = Environment.getDataDirectory();
   4550             long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
   4551             if (lowThreshold == 0) {
   4552                 throw new IllegalStateException("Invalid low memory threshold");
   4553             }
   4554             for (PackageParser.Package pkg : sortedPkgs) {
   4555                 long usableSpace = dataDir.getUsableSpace();
   4556                 if (usableSpace < lowThreshold) {
   4557                     Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
   4558                     break;
   4559                 }
   4560                 performBootDexOpt(pkg, ++i, total);
   4561             }
   4562         }
   4563     }
   4564 
   4565     private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) {
   4566         // Filter out packages that aren't recently used.
   4567         //
   4568         // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
   4569         // should do a full dexopt.
   4570         if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
   4571             // TODO: add a property to control this?
   4572             long dexOptLRUThresholdInMinutes;
   4573             if (mLazyDexOpt) {
   4574                 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
   4575             } else {
   4576                 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
   4577             }
   4578             long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
   4579 
   4580             int total = pkgs.size();
   4581             int skipped = 0;
   4582             long now = System.currentTimeMillis();
   4583             for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
   4584                 PackageParser.Package pkg = i.next();
   4585                 long then = pkg.mLastPackageUsageTimeInMills;
   4586                 if (then + dexOptLRUThresholdInMills < now) {
   4587                     if (DEBUG_DEXOPT) {
   4588                         Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
   4589                               ((then == 0) ? "never" : new Date(then)));
   4590                     }
   4591                     i.remove();
   4592                     skipped++;
   4593                 }
   4594             }
   4595             if (DEBUG_DEXOPT) {
   4596                 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
   4597             }
   4598         }
   4599     }
   4600 
   4601     private HashSet<String> getPackageNamesForIntent(Intent intent) {
   4602         List<ResolveInfo> ris = null;
   4603         try {
   4604             ris = AppGlobals.getPackageManager().queryIntentReceivers(
   4605                     intent, null, 0, UserHandle.USER_OWNER);
   4606         } catch (RemoteException e) {
   4607         }
   4608         HashSet<String> pkgNames = new HashSet<String>();
   4609         if (ris != null) {
   4610             for (ResolveInfo ri : ris) {
   4611                 pkgNames.add(ri.activityInfo.packageName);
   4612             }
   4613         }
   4614         return pkgNames;
   4615     }
   4616 
   4617     private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
   4618         if (DEBUG_DEXOPT) {
   4619             Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
   4620         }
   4621         if (!isFirstBoot()) {
   4622             try {
   4623                 ActivityManagerNative.getDefault().showBootMessage(
   4624                         mContext.getResources().getString(R.string.android_upgrading_apk,
   4625                                 curr, total), true);
   4626             } catch (RemoteException e) {
   4627             }
   4628         }
   4629         PackageParser.Package p = pkg;
   4630         synchronized (mInstallLock) {
   4631             performDexOptLI(p, null /* instruction sets */, false /* force dex */,
   4632                             false /* defer */, true /* include dependencies */);
   4633         }
   4634     }
   4635 
   4636     @Override
   4637     public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
   4638         return performDexOpt(packageName, instructionSet, false);
   4639     }
   4640 
   4641     private static String getPrimaryInstructionSet(ApplicationInfo info) {
   4642         if (info.primaryCpuAbi == null) {
   4643             return getPreferredInstructionSet();
   4644         }
   4645 
   4646         return VMRuntime.getInstructionSet(info.primaryCpuAbi);
   4647     }
   4648 
   4649     public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
   4650         boolean dexopt = mLazyDexOpt || backgroundDexopt;
   4651         boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
   4652         if (!dexopt && !updateUsage) {
   4653             // We aren't going to dexopt or update usage, so bail early.
   4654             return false;
   4655         }
   4656         PackageParser.Package p;
   4657         final String targetInstructionSet;
   4658         synchronized (mPackages) {
   4659             p = mPackages.get(packageName);
   4660             if (p == null) {
   4661                 return false;
   4662             }
   4663             if (updateUsage) {
   4664                 p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
   4665             }
   4666             mPackageUsage.write(false);
   4667             if (!dexopt) {
   4668                 // We aren't going to dexopt, so bail early.
   4669                 return false;
   4670             }
   4671 
   4672             targetInstructionSet = instructionSet != null ? instructionSet :
   4673                     getPrimaryInstructionSet(p.applicationInfo);
   4674             if (p.mDexOptPerformed.contains(targetInstructionSet)) {
   4675                 return false;
   4676             }
   4677         }
   4678 
   4679         synchronized (mInstallLock) {
   4680             final String[] instructionSets = new String[] { targetInstructionSet };
   4681             return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
   4682                     true /* include dependencies */) == DEX_OPT_PERFORMED;
   4683         }
   4684     }
   4685 
   4686     public HashSet<String> getPackagesThatNeedDexOpt() {
   4687         HashSet<String> pkgs = null;
   4688         synchronized (mPackages) {
   4689             for (PackageParser.Package p : mPackages.values()) {
   4690                 if (DEBUG_DEXOPT) {
   4691                     Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
   4692                 }
   4693                 if (!p.mDexOptPerformed.isEmpty()) {
   4694                     continue;
   4695                 }
   4696                 if (pkgs == null) {
   4697                     pkgs = new HashSet<String>();
   4698                 }
   4699                 pkgs.add(p.packageName);
   4700             }
   4701         }
   4702         return pkgs;
   4703     }
   4704 
   4705     public void shutdown() {
   4706         mPackageUsage.write(true);
   4707     }
   4708 
   4709     private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
   4710              boolean forceDex, boolean defer, HashSet<String> done) {
   4711         for (int i=0; i<libs.size(); i++) {
   4712             PackageParser.Package libPkg;
   4713             String libName;
   4714             synchronized (mPackages) {
   4715                 libName = libs.get(i);
   4716                 SharedLibraryEntry lib = mSharedLibraries.get(libName);
   4717                 if (lib != null && lib.apk != null) {
   4718                     libPkg = mPackages.get(lib.apk);
   4719                 } else {
   4720                     libPkg = null;
   4721                 }
   4722             }
   4723             if (libPkg != null && !done.contains(libName)) {
   4724                 performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
   4725             }
   4726         }
   4727     }
   4728 
   4729     static final int DEX_OPT_SKIPPED = 0;
   4730     static final int DEX_OPT_PERFORMED = 1;
   4731     static final int DEX_OPT_DEFERRED = 2;
   4732     static final int DEX_OPT_FAILED = -1;
   4733 
   4734     private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
   4735             boolean forceDex, boolean defer, HashSet<String> done) {
   4736         final String[] instructionSets = targetInstructionSets != null ?
   4737                 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
   4738 
   4739         if (done != null) {
   4740             done.add(pkg.packageName);
   4741             if (pkg.usesLibraries != null) {
   4742                 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
   4743             }
   4744             if (pkg.usesOptionalLibraries != null) {
   4745                 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
   4746             }
   4747         }
   4748 
   4749         if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
   4750             return DEX_OPT_SKIPPED;
   4751         }
   4752 
   4753         final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
   4754 
   4755         final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
   4756         boolean performedDexOpt = false;
   4757         // There are three basic cases here:
   4758         // 1.) we need to dexopt, either because we are forced or it is needed
   4759         // 2.) we are defering a needed dexopt
   4760         // 3.) we are skipping an unneeded dexopt
   4761         final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
   4762         for (String dexCodeInstructionSet : dexCodeInstructionSets) {
   4763             if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
   4764                 continue;
   4765             }
   4766 
   4767             for (String path : paths) {
   4768                 try {
   4769                     // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
   4770                     // patckage or the one we find does not match the image checksum (i.e. it was
   4771                     // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
   4772                     // odex file and it matches the checksum of the image but not its base address,
   4773                     // meaning we need to move it.
   4774                     final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
   4775                             pkg.packageName, dexCodeInstructionSet, defer);
   4776                     if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
   4777                         Log.i(TAG, "Running dexopt on: " + path + " pkg="
   4778                                 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
   4779                                 + " vmSafeMode=" + vmSafeMode);
   4780                         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
   4781                         final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
   4782                                 pkg.packageName, dexCodeInstructionSet, vmSafeMode);
   4783 
   4784                         if (ret < 0) {
   4785                             // Don't bother running dexopt again if we failed, it will probably
   4786                             // just result in an error again. Also, don't bother dexopting for other
   4787                             // paths & ISAs.
   4788                             return DEX_OPT_FAILED;
   4789                         }
   4790 
   4791                         performedDexOpt = true;
   4792                     } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
   4793                         Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
   4794                         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
   4795                         final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
   4796                                 pkg.packageName, dexCodeInstructionSet);
   4797 
   4798                         if (ret < 0) {
   4799                             // Don't bother running patchoat again if we failed, it will probably
   4800                             // just result in an error again. Also, don't bother dexopting for other
   4801                             // paths & ISAs.
   4802                             return DEX_OPT_FAILED;
   4803                         }
   4804 
   4805                         performedDexOpt = true;
   4806                     }
   4807 
   4808                     // We're deciding to defer a needed dexopt. Don't bother dexopting for other
   4809                     // paths and instruction sets. We'll deal with them all together when we process
   4810                     // our list of deferred dexopts.
   4811                     if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
   4812                         if (mDeferredDexOpt == null) {
   4813                             mDeferredDexOpt = new HashSet<PackageParser.Package>();
   4814                         }
   4815                         mDeferredDexOpt.add(pkg);
   4816                         return DEX_OPT_DEFERRED;
   4817                     }
   4818                 } catch (FileNotFoundException e) {
   4819                     Slog.w(TAG, "Apk not found for dexopt: " + path);
   4820                     return DEX_OPT_FAILED;
   4821                 } catch (IOException e) {
   4822                     Slog.w(TAG, "IOException reading apk: " + path, e);
   4823                     return DEX_OPT_FAILED;
   4824                 } catch (StaleDexCacheError e) {
   4825                     Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
   4826                     return DEX_OPT_FAILED;
   4827                 } catch (Exception e) {
   4828                     Slog.w(TAG, "Exception when doing dexopt : ", e);
   4829                     return DEX_OPT_FAILED;
   4830                 }
   4831             }
   4832 
   4833             // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
   4834             // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
   4835             // it isn't required. We therefore mark that this package doesn't need dexopt unless
   4836             // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
   4837             // it.
   4838             pkg.mDexOptPerformed.add(dexCodeInstructionSet);
   4839         }
   4840 
   4841         // If we've gotten here, we're sure that no error occurred and that we haven't
   4842         // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
   4843         // we've skipped all of them because they are up to date. In both cases this
   4844         // package doesn't need dexopt any longer.
   4845         return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
   4846     }
   4847 
   4848     private static String[] getAppDexInstructionSets(ApplicationInfo info) {
   4849         if (info.primaryCpuAbi != null) {
   4850             if (info.secondaryCpuAbi != null) {
   4851                 return new String[] {
   4852                         VMRuntime.getInstructionSet(info.primaryCpuAbi),
   4853                         VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
   4854             } else {
   4855                 return new String[] {
   4856                         VMRuntime.getInstructionSet(info.primaryCpuAbi) };
   4857             }
   4858         }
   4859 
   4860         return new String[] { getPreferredInstructionSet() };
   4861     }
   4862 
   4863     private static String[] getAppDexInstructionSets(PackageSetting ps) {
   4864         if (ps.primaryCpuAbiString != null) {
   4865             if (ps.secondaryCpuAbiString != null) {
   4866                 return new String[] {
   4867                         VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
   4868                         VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
   4869             } else {
   4870                 return new String[] {
   4871                         VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
   4872             }
   4873         }
   4874 
   4875         return new String[] { getPreferredInstructionSet() };
   4876     }
   4877 
   4878     private static String getPreferredInstructionSet() {
   4879         if (sPreferredInstructionSet == null) {
   4880             sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
   4881         }
   4882 
   4883         return sPreferredInstructionSet;
   4884     }
   4885 
   4886     private static List<String> getAllInstructionSets() {
   4887         final String[] allAbis = Build.SUPPORTED_ABIS;
   4888         final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
   4889 
   4890         for (String abi : allAbis) {
   4891             final String instructionSet = VMRuntime.getInstructionSet(abi);
   4892             if (!allInstructionSets.contains(instructionSet)) {
   4893                 allInstructionSets.add(instructionSet);
   4894             }
   4895         }
   4896 
   4897         return allInstructionSets;
   4898     }
   4899 
   4900     /**
   4901      * Returns the instruction set that should be used to compile dex code. In the presence of
   4902      * a native bridge this might be different than the one shared libraries use.
   4903      */
   4904     private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
   4905         String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
   4906         return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
   4907     }
   4908 
   4909     private static String[] getDexCodeInstructionSets(String[] instructionSets) {
   4910         HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
   4911         for (String instructionSet : instructionSets) {
   4912             dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
   4913         }
   4914         return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
   4915     }
   4916 
   4917     /**
   4918      * Returns deduplicated list of supported instructions for dex code.
   4919      */
   4920     public static String[] getAllDexCodeInstructionSets() {
   4921         String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
   4922         for (int i = 0; i < supportedInstructionSets.length; i++) {
   4923             String abi = Build.SUPPORTED_ABIS[i];
   4924             supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
   4925         }
   4926         return getDexCodeInstructionSets(supportedInstructionSets);
   4927     }
   4928 
   4929     @Override
   4930     public void forceDexOpt(String packageName) {
   4931         enforceSystemOrRoot("forceDexOpt");
   4932 
   4933         PackageParser.Package pkg;
   4934         synchronized (mPackages) {
   4935             pkg = mPackages.get(packageName);
   4936             if (pkg == null) {
   4937                 throw new IllegalArgumentException("Missing package: " + packageName);
   4938             }
   4939         }
   4940 
   4941         synchronized (mInstallLock) {
   4942             final String[] instructionSets = new String[] {
   4943                     getPrimaryInstructionSet(pkg.applicationInfo) };
   4944             final int res = performDexOptLI(pkg, instructionSets, true, false, true);
   4945             if (res != DEX_OPT_PERFORMED) {
   4946                 throw new IllegalStateException("Failed to dexopt: " + res);
   4947             }
   4948         }
   4949     }
   4950 
   4951     private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
   4952                                 boolean forceDex, boolean defer, boolean inclDependencies) {
   4953         HashSet<String> done;
   4954         if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
   4955             done = new HashSet<String>();
   4956             done.add(pkg.packageName);
   4957         } else {
   4958             done = null;
   4959         }
   4960         return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
   4961     }
   4962 
   4963     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
   4964         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
   4965             Slog.w(TAG, "Unable to update from " + oldPkg.name
   4966                     + " to " + newPkg.packageName
   4967                     + ": old package not in system partition");
   4968             return false;
   4969         } else if (mPackages.get(oldPkg.name) != null) {
   4970             Slog.w(TAG, "Unable to update from " + oldPkg.name
   4971                     + " to " + newPkg.packageName
   4972                     + ": old package still exists");
   4973             return false;
   4974         }
   4975         return true;
   4976     }
   4977 
   4978     File getDataPathForUser(int userId) {
   4979         return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
   4980     }
   4981 
   4982     private File getDataPathForPackage(String packageName, int userId) {
   4983         /*
   4984          * Until we fully support multiple users, return the directory we
   4985          * previously would have. The PackageManagerTests will need to be
   4986          * revised when this is changed back..
   4987          */
   4988         if (userId == 0) {
   4989             return new File(mAppDataDir, packageName);
   4990         } else {
   4991             return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
   4992                 + File.separator + packageName);
   4993         }
   4994     }
   4995 
   4996     private int createDataDirsLI(String packageName, int uid, String seinfo) {
   4997         int[] users = sUserManager.getUserIds();
   4998         int res = mInstaller.install(packageName, uid, uid, seinfo);
   4999         if (res < 0) {
   5000             return res;
   5001         }
   5002         for (int user : users) {
   5003             if (user != 0) {
   5004                 res = mInstaller.createUserData(packageName,
   5005                         UserHandle.getUid(user, uid), user, seinfo);
   5006                 if (res < 0) {
   5007                     return res;
   5008                 }
   5009             }
   5010         }
   5011         return res;
   5012     }
   5013 
   5014     private int removeDataDirsLI(String packageName) {
   5015         int[] users = sUserManager.getUserIds();
   5016         int res = 0;
   5017         for (int user : users) {
   5018             int resInner = mInstaller.remove(packageName, user);
   5019             if (resInner < 0) {
   5020                 res = resInner;
   5021             }
   5022         }
   5023 
   5024         return res;
   5025     }
   5026 
   5027     private int deleteCodeCacheDirsLI(String packageName) {
   5028         int[] users = sUserManager.getUserIds();
   5029         int res = 0;
   5030         for (int user : users) {
   5031             int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
   5032             if (resInner < 0) {
   5033                 res = resInner;
   5034             }
   5035         }
   5036         return res;
   5037     }
   5038 
   5039     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
   5040             PackageParser.Package changingLib) {
   5041         if (file.path != null) {
   5042             usesLibraryFiles.add(file.path);
   5043             return;
   5044         }
   5045         PackageParser.Package p = mPackages.get(file.apk);
   5046         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
   5047             // If we are doing this while in the middle of updating a library apk,
   5048             // then we need to make sure to use that new apk for determining the
   5049             // dependencies here.  (We haven't yet finished committing the new apk
   5050             // to the package manager state.)
   5051             if (p == null || p.packageName.equals(changingLib.packageName)) {
   5052                 p = changingLib;
   5053             }
   5054         }
   5055         if (p != null) {
   5056             usesLibraryFiles.addAll(p.getAllCodePaths());
   5057         }
   5058     }
   5059 
   5060     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
   5061             PackageParser.Package changingLib) throws PackageManagerException {
   5062         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
   5063             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
   5064             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
   5065             for (int i=0; i<N; i++) {
   5066                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
   5067                 if (file == null) {
   5068                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
   5069                             "Package " + pkg.packageName + " requires unavailable shared library "
   5070                             + pkg.usesLibraries.get(i) + "; failing!");
   5071                 }
   5072                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
   5073             }
   5074             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
   5075             for (int i=0; i<N; i++) {
   5076                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
   5077                 if (file == null) {
   5078                     Slog.w(TAG, "Package " + pkg.packageName
   5079                             + " desires unavailable shared library "
   5080                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
   5081                 } else {
   5082                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
   5083                 }
   5084             }
   5085             N = usesLibraryFiles.size();
   5086             if (N > 0) {
   5087                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
   5088             } else {
   5089                 pkg.usesLibraryFiles = null;
   5090             }
   5091         }
   5092     }
   5093 
   5094     private static boolean hasString(List<String> list, List<String> which) {
   5095         if (list == null) {
   5096             return false;
   5097         }
   5098         for (int i=list.size()-1; i>=0; i--) {
   5099             for (int j=which.size()-1; j>=0; j--) {
   5100                 if (which.get(j).equals(list.get(i))) {
   5101                     return true;
   5102                 }
   5103             }
   5104         }
   5105         return false;
   5106     }
   5107 
   5108     private void updateAllSharedLibrariesLPw() {
   5109         for (PackageParser.Package pkg : mPackages.values()) {
   5110             try {
   5111                 updateSharedLibrariesLPw(pkg, null);
   5112             } catch (PackageManagerException e) {
   5113                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
   5114             }
   5115         }
   5116     }
   5117 
   5118     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
   5119             PackageParser.Package changingPkg) {
   5120         ArrayList<PackageParser.Package> res = null;
   5121         for (PackageParser.Package pkg : mPackages.values()) {
   5122             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
   5123                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
   5124                 if (res == null) {
   5125                     res = new ArrayList<PackageParser.Package>();
   5126                 }
   5127                 res.add(pkg);
   5128                 try {
   5129                     updateSharedLibrariesLPw(pkg, changingPkg);
   5130                 } catch (PackageManagerException e) {
   5131                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
   5132                 }
   5133             }
   5134         }
   5135         return res;
   5136     }
   5137 
   5138     /**
   5139      * Derive the value of the {@code cpuAbiOverride} based on the provided
   5140      * value and an optional stored value from the package settings.
   5141      */
   5142     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
   5143         String cpuAbiOverride = null;
   5144 
   5145         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
   5146             cpuAbiOverride = null;
   5147         } else if (abiOverride != null) {
   5148             cpuAbiOverride = abiOverride;
   5149         } else if (settings != null) {
   5150             cpuAbiOverride = settings.cpuAbiOverrideString;
   5151         }
   5152 
   5153         return cpuAbiOverride;
   5154     }
   5155 
   5156     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
   5157             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
   5158         boolean success = false;
   5159         try {
   5160             final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
   5161                     currentTime, user);
   5162             success = true;
   5163             return res;
   5164         } finally {
   5165             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
   5166                 removeDataDirsLI(pkg.packageName);
   5167             }
   5168         }
   5169     }
   5170 
   5171     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
   5172             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
   5173         final File scanFile = new File(pkg.codePath);
   5174         if (pkg.applicationInfo.getCodePath() == null ||
   5175                 pkg.applicationInfo.getResourcePath() == null) {
   5176             // Bail out. The resource and code paths haven't been set.
   5177             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
   5178                     "Code and resource paths haven't been set correctly");
   5179         }
   5180 
   5181         if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
   5182             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
   5183         } else {
   5184             // Only allow system apps to be flagged as core apps.
   5185             pkg.coreApp = false;
   5186         }
   5187 
   5188         if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
   5189             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
   5190         }
   5191 
   5192         if (mCustomResolverComponentName != null &&
   5193                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
   5194             setUpCustomResolverActivity(pkg);
   5195         }
   5196 
   5197         if (pkg.packageName.equals("android")) {
   5198             synchronized (mPackages) {
   5199                 if (mAndroidApplication != null) {
   5200                     Slog.w(TAG, "*************************************************");
   5201                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
   5202                     Slog.w(TAG, " file=" + scanFile);
   5203                     Slog.w(TAG, "*************************************************");
   5204                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
   5205                             "Core android package being redefined.  Skipping.");
   5206                 }
   5207 
   5208                 // Set up information for our fall-back user intent resolution activity.
   5209                 mPlatformPackage = pkg;
   5210                 pkg.mVersionCode = mSdkVersion;
   5211                 mAndroidApplication = pkg.applicationInfo;
   5212 
   5213                 if (!mResolverReplaced) {
   5214                     mResolveActivity.applicationInfo = mAndroidApplication;
   5215                     mResolveActivity.name = ResolverActivity.class.getName();
   5216                     mResolveActivity.packageName = mAndroidApplication.packageName;
   5217                     mResolveActivity.processName = "system:ui";
   5218                     mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
   5219                     mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
   5220                     mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
   5221                     mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
   5222                     mResolveActivity.exported = true;
   5223                     mResolveActivity.enabled = true;
   5224                     mResolveInfo.activityInfo = mResolveActivity;
   5225                     mResolveInfo.priority = 0;
   5226                     mResolveInfo.preferredOrder = 0;
   5227                     mResolveInfo.match = 0;
   5228                     mResolveComponentName = new ComponentName(
   5229                             mAndroidApplication.packageName, mResolveActivity.name);
   5230                 }
   5231             }
   5232         }
   5233 
   5234         if (DEBUG_PACKAGE_SCANNING) {
   5235             if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
   5236                 Log.d(TAG, "Scanning package " + pkg.packageName);
   5237         }
   5238 
   5239         if (mPackages.containsKey(pkg.packageName)
   5240                 || mSharedLibraries.containsKey(pkg.packageName)) {
   5241             throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
   5242                     "Application package " + pkg.packageName
   5243                     + " already installed.  Skipping duplicate.");
   5244         }
   5245 
   5246         // Initialize package source and resource directories
   5247         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
   5248         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
   5249 
   5250         SharedUserSetting suid = null;
   5251         PackageSetting pkgSetting = null;
   5252 
   5253         if (!isSystemApp(pkg)) {
   5254             // Only system apps can use these features.
   5255             pkg.mOriginalPackages = null;
   5256             pkg.mRealPackage = null;
   5257             pkg.mAdoptPermissions = null;
   5258         }
   5259 
   5260         // writer
   5261         synchronized (mPackages) {
   5262             if (pkg.mSharedUserId != null) {
   5263                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
   5264                 if (suid == null) {
   5265                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
   5266                             "Creating application package " + pkg.packageName
   5267                             + " for shared user failed");
   5268                 }
   5269                 if (DEBUG_PACKAGE_SCANNING) {
   5270                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
   5271                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
   5272                                 + "): packages=" + suid.packages);
   5273                 }
   5274             }
   5275 
   5276             // Check if we are renaming from an original package name.
   5277             PackageSetting origPackage = null;
   5278             String realName = null;
   5279             if (pkg.mOriginalPackages != null) {
   5280                 // This package may need to be renamed to a previously
   5281                 // installed name.  Let's check on that...
   5282                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
   5283                 if (pkg.mOriginalPackages.contains(renamed)) {
   5284                     // This package had originally been installed as the
   5285                     // original name, and we have already taken care of
   5286                     // transitioning to the new one.  Just update the new
   5287                     // one to continue using the old name.
   5288                     realName = pkg.mRealPackage;
   5289                     if (!pkg.packageName.equals(renamed)) {
   5290                         // Callers into this function may have already taken
   5291                         // care of renaming the package; only do it here if
   5292                         // it is not already done.
   5293                         pkg.setPackageName(renamed);
   5294                     }
   5295 
   5296                 } else {
   5297                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
   5298                         if ((origPackage = mSettings.peekPackageLPr(
   5299                                 pkg.mOriginalPackages.get(i))) != null) {
   5300                             // We do have the package already installed under its
   5301                             // original name...  should we use it?
   5302                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
   5303                                 // New package is not compatible with original.
   5304                                 origPackage = null;
   5305                                 continue;
   5306                             } else if (origPackage.sharedUser != null) {
   5307                                 // Make sure uid is compatible between packages.
   5308                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
   5309                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
   5310                                             + " to " + pkg.packageName + ": old uid "
   5311                                             + origPackage.sharedUser.name
   5312                                             + " differs from " + pkg.mSharedUserId);
   5313                                     origPackage = null;
   5314                                     continue;
   5315                                 }
   5316                             } else {
   5317                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
   5318                                         + pkg.packageName + " to old name " + origPackage.name);
   5319                             }
   5320                             break;
   5321                         }
   5322                     }
   5323                 }
   5324             }
   5325 
   5326             if (mTransferedPackages.contains(pkg.packageName)) {
   5327                 Slog.w(TAG, "Package " + pkg.packageName
   5328                         + " was transferred to another, but its .apk remains");
   5329             }
   5330 
   5331             // Just create the setting, don't add it yet. For already existing packages
   5332             // the PkgSetting exists already and doesn't have to be created.
   5333             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
   5334                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
   5335                     pkg.applicationInfo.primaryCpuAbi,
   5336                     pkg.applicationInfo.secondaryCpuAbi,
   5337                     pkg.applicationInfo.flags, user, false);
   5338             if (pkgSetting == null) {
   5339                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
   5340                         "Creating application package " + pkg.packageName + " failed");
   5341             }
   5342 
   5343             if (pkgSetting.origPackage != null) {
   5344                 // If we are first transitioning from an original package,
   5345                 // fix up the new package's name now.  We need to do this after
   5346                 // looking up the package under its new name, so getPackageLP
   5347                 // can take care of fiddling things correctly.
   5348                 pkg.setPackageName(origPackage.name);
   5349 
   5350                 // File a report about this.
   5351                 String msg = "New package " + pkgSetting.realName
   5352                         + " renamed to replace old package " + pkgSetting.name;
   5353                 reportSettingsProblem(Log.WARN, msg);
   5354 
   5355                 // Make a note of it.
   5356                 mTransferedPackages.add(origPackage.name);
   5357 
   5358                 // No longer need to retain this.
   5359                 pkgSetting.origPackage = null;
   5360             }
   5361 
   5362             if (realName != null) {
   5363                 // Make a note of it.
   5364                 mTransferedPackages.add(pkg.packageName);
   5365             }
   5366 
   5367             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
   5368                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
   5369             }
   5370 
   5371             if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   5372                 // Check all shared libraries and map to their actual file path.
   5373                 // We only do this here for apps not on a system dir, because those
   5374                 // are the only ones that can fail an install due to this.  We
   5375                 // will take care of the system apps by updating all of their
   5376                 // library paths after the scan is done.
   5377                 updateSharedLibrariesLPw(pkg, null);
   5378             }
   5379 
   5380             if (mFoundPolicyFile) {
   5381                 SELinuxMMAC.assignSeinfoValue(pkg);
   5382             }
   5383 
   5384             pkg.applicationInfo.uid = pkgSetting.appId;
   5385             pkg.mExtras = pkgSetting;
   5386             if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
   5387                 try {
   5388                     verifySignaturesLP(pkgSetting, pkg);
   5389                 } catch (PackageManagerException e) {
   5390                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
   5391                         throw e;
   5392                     }
   5393                     // The signature has changed, but this package is in the system
   5394                     // image...  let's recover!
   5395                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
   5396                     // However...  if this package is part of a shared user, but it
   5397                     // doesn't match the signature of the shared user, let's fail.
   5398                     // What this means is that you can't change the signatures
   5399                     // associated with an overall shared user, which doesn't seem all
   5400                     // that unreasonable.
   5401                     if (pkgSetting.sharedUser != null) {
   5402                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
   5403                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
   5404                             throw new PackageManagerException(
   5405                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
   5406                                             "Signature mismatch for shared user : "
   5407                                             + pkgSetting.sharedUser);
   5408                         }
   5409                     }
   5410                     // File a report about this.
   5411                     String msg = "System package " + pkg.packageName
   5412                         + " signature changed; retaining data.";
   5413                     reportSettingsProblem(Log.WARN, msg);
   5414                 }
   5415             } else {
   5416                 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
   5417                     throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
   5418                             + pkg.packageName + " upgrade keys do not match the "
   5419                             + "previously installed version");
   5420                 } else {
   5421                     // signatures may have changed as result of upgrade
   5422                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
   5423                 }
   5424             }
   5425             // Verify that this new package doesn't have any content providers
   5426             // that conflict with existing packages.  Only do this if the
   5427             // package isn't already installed, since we don't want to break
   5428             // things that are installed.
   5429             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
   5430                 final int N = pkg.providers.size();
   5431                 int i;
   5432                 for (i=0; i<N; i++) {
   5433                     PackageParser.Provider p = pkg.providers.get(i);
   5434                     if (p.info.authority != null) {
   5435                         String names[] = p.info.authority.split(";");
   5436                         for (int j = 0; j < names.length; j++) {
   5437                             if (mProvidersByAuthority.containsKey(names[j])) {
   5438                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
   5439                                 final String otherPackageName =
   5440                                         ((other != null && other.getComponentName() != null) ?
   5441                                                 other.getComponentName().getPackageName() : "?");
   5442                                 throw new PackageManagerException(
   5443                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
   5444                                                 "Can't install because provider name " + names[j]
   5445                                                 + " (in package " + pkg.applicationInfo.packageName
   5446                                                 + ") is already used by " + otherPackageName);
   5447                             }
   5448                         }
   5449                     }
   5450                 }
   5451             }
   5452 
   5453             if (pkg.mAdoptPermissions != null) {
   5454                 // This package wants to adopt ownership of permissions from
   5455                 // another package.
   5456                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
   5457                     final String origName = pkg.mAdoptPermissions.get(i);
   5458                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
   5459                     if (orig != null) {
   5460                         if (verifyPackageUpdateLPr(orig, pkg)) {
   5461                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
   5462                                     + pkg.packageName);
   5463                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
   5464                         }
   5465                     }
   5466                 }
   5467             }
   5468         }
   5469 
   5470         final String pkgName = pkg.packageName;
   5471 
   5472         final long scanFileTime = scanFile.lastModified();
   5473         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
   5474         pkg.applicationInfo.processName = fixProcessName(
   5475                 pkg.applicationInfo.packageName,
   5476                 pkg.applicationInfo.processName,
   5477                 pkg.applicationInfo.uid);
   5478 
   5479         File dataPath;
   5480         if (mPlatformPackage == pkg) {
   5481             // The system package is special.
   5482             dataPath = new File(Environment.getDataDirectory(), "system");
   5483 
   5484             pkg.applicationInfo.dataDir = dataPath.getPath();
   5485 
   5486         } else {
   5487             // This is a normal package, need to make its data directory.
   5488             dataPath = getDataPathForPackage(pkg.packageName, 0);
   5489 
   5490             boolean uidError = false;
   5491             if (dataPath.exists()) {
   5492                 int currentUid = 0;
   5493                 try {
   5494                     StructStat stat = Os.stat(dataPath.getPath());
   5495                     currentUid = stat.st_uid;
   5496                 } catch (ErrnoException e) {
   5497                     Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
   5498                 }
   5499 
   5500                 // If we have mismatched owners for the data path, we have a problem.
   5501                 if (currentUid != pkg.applicationInfo.uid) {
   5502                     boolean recovered = false;
   5503                     if (currentUid == 0) {
   5504                         // The directory somehow became owned by root.  Wow.
   5505                         // This is probably because the system was stopped while
   5506                         // installd was in the middle of messing with its libs
   5507                         // directory.  Ask installd to fix that.
   5508                         int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
   5509                                 pkg.applicationInfo.uid);
   5510                         if (ret >= 0) {
   5511                             recovered = true;
   5512                             String msg = "Package " + pkg.packageName
   5513                                     + " unexpectedly changed to uid 0; recovered to " +
   5514                                     + pkg.applicationInfo.uid;
   5515                             reportSettingsProblem(Log.WARN, msg);
   5516                         }
   5517                     }
   5518                     if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
   5519                             || (scanFlags&SCAN_BOOTING) != 0)) {
   5520                         // If this is a system app, we can at least delete its
   5521                         // current data so the application will still work.
   5522                         int ret = removeDataDirsLI(pkgName);
   5523                         if (ret >= 0) {
   5524                             // TODO: Kill the processes first
   5525                             // Old data gone!
   5526                             String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
   5527                                     ? "System package " : "Third party package ";
   5528                             String msg = prefix + pkg.packageName
   5529                                     + " has changed from uid: "
   5530                                     + currentUid + " to "
   5531                                     + pkg.applicationInfo.uid + "; old data erased";
   5532                             reportSettingsProblem(Log.WARN, msg);
   5533                             recovered = true;
   5534 
   5535                             // And now re-install the app.
   5536                             ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
   5537                                                    pkg.applicationInfo.seinfo);
   5538                             if (ret == -1) {
   5539                                 // Ack should not happen!
   5540                                 msg = prefix + pkg.packageName
   5541                                         + " could not have data directory re-created after delete.";
   5542                                 reportSettingsProblem(Log.WARN, msg);
   5543                                 throw new PackageManagerException(
   5544                                         INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
   5545                             }
   5546                         }
   5547                         if (!recovered) {
   5548                             mHasSystemUidErrors = true;
   5549                         }
   5550                     } else if (!recovered) {
   5551                         // If we allow this install to proceed, we will be broken.
   5552                         // Abort, abort!
   5553                         throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
   5554                                 "scanPackageLI");
   5555                     }
   5556                     if (!recovered) {
   5557                         pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
   5558                             + pkg.applicationInfo.uid + "/fs_"
   5559                             + currentUid;
   5560                         pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
   5561                         pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
   5562                         String msg = "Package " + pkg.packageName
   5563                                 + " has mismatched uid: "
   5564                                 + currentUid + " on disk, "
   5565                                 + pkg.applicationInfo.uid + " in settings";
   5566                         // writer
   5567                         synchronized (mPackages) {
   5568                             mSettings.mReadMessages.append(msg);
   5569                             mSettings.mReadMessages.append('\n');
   5570                             uidError = true;
   5571                             if (!pkgSetting.uidError) {
   5572                                 reportSettingsProblem(Log.ERROR, msg);
   5573                             }
   5574                         }
   5575                     }
   5576                 }
   5577                 pkg.applicationInfo.dataDir = dataPath.getPath();
   5578                 if (mShouldRestoreconData) {
   5579                     Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
   5580                     mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
   5581                                 pkg.applicationInfo.uid);
   5582                 }
   5583             } else {
   5584                 if (DEBUG_PACKAGE_SCANNING) {
   5585                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
   5586                         Log.v(TAG, "Want this data dir: " + dataPath);
   5587                 }
   5588                 //invoke installer to do the actual installation
   5589                 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
   5590                                            pkg.applicationInfo.seinfo);
   5591                 if (ret < 0) {
   5592                     // Error from installer
   5593                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
   5594                             "Unable to create data dirs [errorCode=" + ret + "]");
   5595                 }
   5596 
   5597                 if (dataPath.exists()) {
   5598                     pkg.applicationInfo.dataDir = dataPath.getPath();
   5599                 } else {
   5600                     Slog.w(TAG, "Unable to create data directory: " + dataPath);
   5601                     pkg.applicationInfo.dataDir = null;
   5602                 }
   5603             }
   5604 
   5605             pkgSetting.uidError = uidError;
   5606         }
   5607 
   5608         final String path = scanFile.getPath();
   5609         final String codePath = pkg.applicationInfo.getCodePath();
   5610         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
   5611         if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
   5612             setBundledAppAbisAndRoots(pkg, pkgSetting);
   5613 
   5614             // If we haven't found any native libraries for the app, check if it has
   5615             // renderscript code. We'll need to force the app to 32 bit if it has
   5616             // renderscript bitcode.
   5617             if (pkg.applicationInfo.primaryCpuAbi == null
   5618                     && pkg.applicationInfo.secondaryCpuAbi == null
   5619                     && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
   5620                 NativeLibraryHelper.Handle handle = null;
   5621                 try {
   5622                     handle = NativeLibraryHelper.Handle.create(scanFile);
   5623                     if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
   5624                         pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   5625                     }
   5626                 } catch (IOException ioe) {
   5627                     Slog.w(TAG, "Error scanning system app : " + ioe);
   5628                 } finally {
   5629                     IoUtils.closeQuietly(handle);
   5630                 }
   5631             }
   5632 
   5633             setNativeLibraryPaths(pkg);
   5634         } else {
   5635             // TODO: We can probably be smarter about this stuff. For installed apps,
   5636             // we can calculate this information at install time once and for all. For
   5637             // system apps, we can probably assume that this information doesn't change
   5638             // after the first boot scan. As things stand, we do lots of unnecessary work.
   5639 
   5640             // Give ourselves some initial paths; we'll come back for another
   5641             // pass once we've determined ABI below.
   5642             setNativeLibraryPaths(pkg);
   5643 
   5644             final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
   5645             final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
   5646             final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
   5647 
   5648             NativeLibraryHelper.Handle handle = null;
   5649             try {
   5650                 handle = NativeLibraryHelper.Handle.create(scanFile);
   5651                 // TODO(multiArch): This can be null for apps that didn't go through the
   5652                 // usual installation process. We can calculate it again, like we
   5653                 // do during install time.
   5654                 //
   5655                 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
   5656                 // unnecessary.
   5657                 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
   5658 
   5659                 // Null out the abis so that they can be recalculated.
   5660                 pkg.applicationInfo.primaryCpuAbi = null;
   5661                 pkg.applicationInfo.secondaryCpuAbi = null;
   5662                 if (isMultiArch(pkg.applicationInfo)) {
   5663                     // Warn if we've set an abiOverride for multi-lib packages..
   5664                     // By definition, we need to copy both 32 and 64 bit libraries for
   5665                     // such packages.
   5666                     if (pkg.cpuAbiOverride != null
   5667                             && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
   5668                         Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
   5669                     }
   5670 
   5671                     int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
   5672                     int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
   5673                     if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
   5674                         if (isAsec) {
   5675                             abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
   5676                         } else {
   5677                             abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
   5678                                     nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
   5679                                     useIsaSpecificSubdirs);
   5680                         }
   5681                     }
   5682 
   5683                     maybeThrowExceptionForMultiArchCopy(
   5684                             "Error unpackaging 32 bit native libs for multiarch app.", abi32);
   5685 
   5686                     if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
   5687                         if (isAsec) {
   5688                             abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
   5689                         } else {
   5690                             abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
   5691                                     nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
   5692                                     useIsaSpecificSubdirs);
   5693                         }
   5694                     }
   5695 
   5696                     maybeThrowExceptionForMultiArchCopy(
   5697                             "Error unpackaging 64 bit native libs for multiarch app.", abi64);
   5698 
   5699                     if (abi64 >= 0) {
   5700                         pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
   5701                     }
   5702 
   5703                     if (abi32 >= 0) {
   5704                         final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
   5705                         if (abi64 >= 0) {
   5706                             pkg.applicationInfo.secondaryCpuAbi = abi;
   5707                         } else {
   5708                             pkg.applicationInfo.primaryCpuAbi = abi;
   5709                         }
   5710                     }
   5711                 } else {
   5712                     String[] abiList = (cpuAbiOverride != null) ?
   5713                             new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
   5714 
   5715                     // Enable gross and lame hacks for apps that are built with old
   5716                     // SDK tools. We must scan their APKs for renderscript bitcode and
   5717                     // not launch them if it's present. Don't bother checking on devices
   5718                     // that don't have 64 bit support.
   5719                     boolean needsRenderScriptOverride = false;
   5720                     if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
   5721                             NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
   5722                         abiList = Build.SUPPORTED_32_BIT_ABIS;
   5723                         needsRenderScriptOverride = true;
   5724                     }
   5725 
   5726                     final int copyRet;
   5727                     if (isAsec) {
   5728                         copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
   5729                     } else {
   5730                         copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
   5731                                 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
   5732                     }
   5733 
   5734                     if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
   5735                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
   5736                                 "Error unpackaging native libs for app, errorCode=" + copyRet);
   5737                     }
   5738 
   5739                     if (copyRet >= 0) {
   5740                         pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
   5741                     } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
   5742                         pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
   5743                     } else if (needsRenderScriptOverride) {
   5744                         pkg.applicationInfo.primaryCpuAbi = abiList[0];
   5745                     }
   5746                 }
   5747             } catch (IOException ioe) {
   5748                 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
   5749             } finally {
   5750                 IoUtils.closeQuietly(handle);
   5751             }
   5752 
   5753             // Now that we've calculated the ABIs and determined if it's an internal app,
   5754             // we will go ahead and populate the nativeLibraryPath.
   5755             setNativeLibraryPaths(pkg);
   5756 
   5757             if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
   5758             final int[] userIds = sUserManager.getUserIds();
   5759             synchronized (mInstallLock) {
   5760                 // Create a native library symlink only if we have native libraries
   5761                 // and if the native libraries are 32 bit libraries. We do not provide
   5762                 // this symlink for 64 bit libraries.
   5763                 if (pkg.applicationInfo.primaryCpuAbi != null &&
   5764                         !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
   5765                     final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
   5766                     for (int userId : userIds) {
   5767                         if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
   5768                             throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
   5769                                     "Failed linking native library dir (user=" + userId + ")");
   5770                         }
   5771                     }
   5772                 }
   5773             }
   5774         }
   5775 
   5776         // This is a special case for the "system" package, where the ABI is
   5777         // dictated by the zygote configuration (and init.rc). We should keep track
   5778         // of this ABI so that we can deal with "normal" applications that run under
   5779         // the same UID correctly.
   5780         if (mPlatformPackage == pkg) {
   5781             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
   5782                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
   5783         }
   5784 
   5785         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
   5786         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
   5787         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
   5788         // Copy the derived override back to the parsed package, so that we can
   5789         // update the package settings accordingly.
   5790         pkg.cpuAbiOverride = cpuAbiOverride;
   5791 
   5792         if (DEBUG_ABI_SELECTION) {
   5793             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
   5794                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
   5795                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
   5796         }
   5797 
   5798         // Push the derived path down into PackageSettings so we know what to
   5799         // clean up at uninstall time.
   5800         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
   5801 
   5802         if (DEBUG_ABI_SELECTION) {
   5803             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
   5804                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
   5805                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
   5806         }
   5807 
   5808         if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
   5809             // We don't do this here during boot because we can do it all
   5810             // at once after scanning all existing packages.
   5811             //
   5812             // We also do this *before* we perform dexopt on this package, so that
   5813             // we can avoid redundant dexopts, and also to make sure we've got the
   5814             // code and package path correct.
   5815             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
   5816                     pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
   5817         }
   5818 
   5819         if ((scanFlags & SCAN_NO_DEX) == 0) {
   5820             if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
   5821                     (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
   5822                 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
   5823             }
   5824         }
   5825 
   5826         if (mFactoryTest && pkg.requestedPermissions.contains(
   5827                 android.Manifest.permission.FACTORY_TEST)) {
   5828             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
   5829         }
   5830 
   5831         ArrayList<PackageParser.Package> clientLibPkgs = null;
   5832 
   5833         // writer
   5834         synchronized (mPackages) {
   5835             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
   5836                 // Only system apps can add new shared libraries.
   5837                 if (pkg.libraryNames != null) {
   5838                     for (int i=0; i<pkg.libraryNames.size(); i++) {
   5839                         String name = pkg.libraryNames.get(i);
   5840                         boolean allowed = false;
   5841                         if (isUpdatedSystemApp(pkg)) {
   5842                             // New library entries can only be added through the
   5843                             // system image.  This is important to get rid of a lot
   5844                             // of nasty edge cases: for example if we allowed a non-
   5845                             // system update of the app to add a library, then uninstalling
   5846                             // the update would make the library go away, and assumptions
   5847                             // we made such as through app install filtering would now
   5848                             // have allowed apps on the device which aren't compatible
   5849                             // with it.  Better to just have the restriction here, be
   5850                             // conservative, and create many fewer cases that can negatively
   5851                             // impact the user experience.
   5852                             final PackageSetting sysPs = mSettings
   5853                                     .getDisabledSystemPkgLPr(pkg.packageName);
   5854                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
   5855                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
   5856                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
   5857                                         allowed = true;
   5858                                         allowed = true;
   5859                                         break;
   5860                                     }
   5861                                 }
   5862                             }
   5863                         } else {
   5864                             allowed = true;
   5865                         }
   5866                         if (allowed) {
   5867                             if (!mSharedLibraries.containsKey(name)) {
   5868                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
   5869                             } else if (!name.equals(pkg.packageName)) {
   5870                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
   5871                                         + name + " already exists; skipping");
   5872                             }
   5873                         } else {
   5874                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
   5875                                     + name + " that is not declared on system image; skipping");
   5876                         }
   5877                     }
   5878                     if ((scanFlags&SCAN_BOOTING) == 0) {
   5879                         // If we are not booting, we need to update any applications
   5880                         // that are clients of our shared library.  If we are booting,
   5881                         // this will all be done once the scan is complete.
   5882                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
   5883                     }
   5884                 }
   5885             }
   5886         }
   5887 
   5888         // We also need to dexopt any apps that are dependent on this library.  Note that
   5889         // if these fail, we should abort the install since installing the library will
   5890         // result in some apps being broken.
   5891         if (clientLibPkgs != null) {
   5892             if ((scanFlags & SCAN_NO_DEX) == 0) {
   5893                 for (int i = 0; i < clientLibPkgs.size(); i++) {
   5894                     PackageParser.Package clientPkg = clientLibPkgs.get(i);
   5895                     if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
   5896                             (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
   5897                         throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
   5898                                 "scanPackageLI failed to dexopt clientLibPkgs");
   5899                     }
   5900                 }
   5901             }
   5902         }
   5903 
   5904         // Request the ActivityManager to kill the process(only for existing packages)
   5905         // so that we do not end up in a confused state while the user is still using the older
   5906         // version of the application while the new one gets installed.
   5907         if ((scanFlags & SCAN_REPLACING) != 0) {
   5908             killApplication(pkg.applicationInfo.packageName,
   5909                         pkg.applicationInfo.uid, "update pkg");
   5910         }
   5911 
   5912         // Also need to kill any apps that are dependent on the library.
   5913         if (clientLibPkgs != null) {
   5914             for (int i=0; i<clientLibPkgs.size(); i++) {
   5915                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
   5916                 killApplication(clientPkg.applicationInfo.packageName,
   5917                         clientPkg.applicationInfo.uid, "update lib");
   5918             }
   5919         }
   5920 
   5921         // writer
   5922         synchronized (mPackages) {
   5923             // We don't expect installation to fail beyond this point
   5924 
   5925             // Add the new setting to mSettings
   5926             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
   5927             // Add the new setting to mPackages
   5928             mPackages.put(pkg.applicationInfo.packageName, pkg);
   5929             // Make sure we don't accidentally delete its data.
   5930             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
   5931             while (iter.hasNext()) {
   5932                 PackageCleanItem item = iter.next();
   5933                 if (pkgName.equals(item.packageName)) {
   5934                     iter.remove();
   5935                 }
   5936             }
   5937 
   5938             // Take care of first install / last update times.
   5939             if (currentTime != 0) {
   5940                 if (pkgSetting.firstInstallTime == 0) {
   5941                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
   5942                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
   5943                     pkgSetting.lastUpdateTime = currentTime;
   5944                 }
   5945             } else if (pkgSetting.firstInstallTime == 0) {
   5946                 // We need *something*.  Take time time stamp of the file.
   5947                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
   5948             } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
   5949                 if (scanFileTime != pkgSetting.timeStamp) {
   5950                     // A package on the system image has changed; consider this
   5951                     // to be an update.
   5952                     pkgSetting.lastUpdateTime = scanFileTime;
   5953                 }
   5954             }
   5955 
   5956             // Add the package's KeySets to the global KeySetManagerService
   5957             KeySetManagerService ksms = mSettings.mKeySetManagerService;
   5958             try {
   5959                 // Old KeySetData no longer valid.
   5960                 ksms.removeAppKeySetDataLPw(pkg.packageName);
   5961                 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
   5962                 if (pkg.mKeySetMapping != null) {
   5963                     for (Map.Entry<String, ArraySet<PublicKey>> entry :
   5964                             pkg.mKeySetMapping.entrySet()) {
   5965                         if (entry.getValue() != null) {
   5966                             ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
   5967                                                           entry.getValue(), entry.getKey());
   5968                         }
   5969                     }
   5970                     if (pkg.mUpgradeKeySets != null) {
   5971                         for (String upgradeAlias : pkg.mUpgradeKeySets) {
   5972                             ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
   5973                         }
   5974                     }
   5975                 }
   5976             } catch (NullPointerException e) {
   5977                 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
   5978             } catch (IllegalArgumentException e) {
   5979                 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
   5980             }
   5981 
   5982             int N = pkg.providers.size();
   5983             StringBuilder r = null;
   5984             int i;
   5985             for (i=0; i<N; i++) {
   5986                 PackageParser.Provider p = pkg.providers.get(i);
   5987                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
   5988                         p.info.processName, pkg.applicationInfo.uid);
   5989                 mProviders.addProvider(p);
   5990                 p.syncable = p.info.isSyncable;
   5991                 if (p.info.authority != null) {
   5992                     String names[] = p.info.authority.split(";");
   5993                     p.info.authority = null;
   5994                     for (int j = 0; j < names.length; j++) {
   5995                         if (j == 1 && p.syncable) {
   5996                             // We only want the first authority for a provider to possibly be
   5997                             // syncable, so if we already added this provider using a different
   5998                             // authority clear the syncable flag. We copy the provider before
   5999                             // changing it because the mProviders object contains a reference
   6000                             // to a provider that we don't want to change.
   6001                             // Only do this for the second authority since the resulting provider
   6002                             // object can be the same for all future authorities for this provider.
   6003                             p = new PackageParser.Provider(p);
   6004                             p.syncable = false;
   6005                         }
   6006                         if (!mProvidersByAuthority.containsKey(names[j])) {
   6007                             mProvidersByAuthority.put(names[j], p);
   6008                             if (p.info.authority == null) {
   6009                                 p.info.authority = names[j];
   6010                             } else {
   6011                                 p.info.authority = p.info.authority + ";" + names[j];
   6012                             }
   6013                             if (DEBUG_PACKAGE_SCANNING) {
   6014                                 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
   6015                                     Log.d(TAG, "Registered content provider: " + names[j]
   6016                                             + ", className = " + p.info.name + ", isSyncable = "
   6017                                             + p.info.isSyncable);
   6018                             }
   6019                         } else {
   6020                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
   6021                             Slog.w(TAG, "Skipping provider name " + names[j] +
   6022                                     " (in package " + pkg.applicationInfo.packageName +
   6023                                     "): name already used by "
   6024                                     + ((other != null && other.getComponentName() != null)
   6025                                             ? other.getComponentName().getPackageName() : "?"));
   6026                         }
   6027                     }
   6028                 }
   6029                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6030                     if (r == null) {
   6031                         r = new StringBuilder(256);
   6032                     } else {
   6033                         r.append(' ');
   6034                     }
   6035                     r.append(p.info.name);
   6036                 }
   6037             }
   6038             if (r != null) {
   6039                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
   6040             }
   6041 
   6042             N = pkg.services.size();
   6043             r = null;
   6044             for (i=0; i<N; i++) {
   6045                 PackageParser.Service s = pkg.services.get(i);
   6046                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
   6047                         s.info.processName, pkg.applicationInfo.uid);
   6048                 mServices.addService(s);
   6049                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6050                     if (r == null) {
   6051                         r = new StringBuilder(256);
   6052                     } else {
   6053                         r.append(' ');
   6054                     }
   6055                     r.append(s.info.name);
   6056                 }
   6057             }
   6058             if (r != null) {
   6059                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
   6060             }
   6061 
   6062             N = pkg.receivers.size();
   6063             r = null;
   6064             for (i=0; i<N; i++) {
   6065                 PackageParser.Activity a = pkg.receivers.get(i);
   6066                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
   6067                         a.info.processName, pkg.applicationInfo.uid);
   6068                 mReceivers.addActivity(a, "receiver");
   6069                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6070                     if (r == null) {
   6071                         r = new StringBuilder(256);
   6072                     } else {
   6073                         r.append(' ');
   6074                     }
   6075                     r.append(a.info.name);
   6076                 }
   6077             }
   6078             if (r != null) {
   6079                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
   6080             }
   6081 
   6082             N = pkg.activities.size();
   6083             r = null;
   6084             for (i=0; i<N; i++) {
   6085                 PackageParser.Activity a = pkg.activities.get(i);
   6086                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
   6087                         a.info.processName, pkg.applicationInfo.uid);
   6088                 mActivities.addActivity(a, "activity");
   6089                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6090                     if (r == null) {
   6091                         r = new StringBuilder(256);
   6092                     } else {
   6093                         r.append(' ');
   6094                     }
   6095                     r.append(a.info.name);
   6096                 }
   6097             }
   6098             if (r != null) {
   6099                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
   6100             }
   6101 
   6102             N = pkg.permissionGroups.size();
   6103             r = null;
   6104             for (i=0; i<N; i++) {
   6105                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
   6106                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
   6107                 if (cur == null) {
   6108                     mPermissionGroups.put(pg.info.name, pg);
   6109                     if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6110                         if (r == null) {
   6111                             r = new StringBuilder(256);
   6112                         } else {
   6113                             r.append(' ');
   6114                         }
   6115                         r.append(pg.info.name);
   6116                     }
   6117                 } else {
   6118                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
   6119                             + pg.info.packageName + " ignored: original from "
   6120                             + cur.info.packageName);
   6121                     if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6122                         if (r == null) {
   6123                             r = new StringBuilder(256);
   6124                         } else {
   6125                             r.append(' ');
   6126                         }
   6127                         r.append("DUP:");
   6128                         r.append(pg.info.name);
   6129                     }
   6130                 }
   6131             }
   6132             if (r != null) {
   6133                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
   6134             }
   6135 
   6136             N = pkg.permissions.size();
   6137             r = null;
   6138             for (i=0; i<N; i++) {
   6139                 PackageParser.Permission p = pkg.permissions.get(i);
   6140                 HashMap<String, BasePermission> permissionMap =
   6141                         p.tree ? mSettings.mPermissionTrees
   6142                         : mSettings.mPermissions;
   6143                 p.group = mPermissionGroups.get(p.info.group);
   6144                 if (p.info.group == null || p.group != null) {
   6145                     BasePermission bp = permissionMap.get(p.info.name);
   6146 
   6147                     // Allow system apps to redefine non-system permissions
   6148                     if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
   6149                         final boolean currentOwnerIsSystem = (bp.perm != null
   6150                                 && isSystemApp(bp.perm.owner));
   6151                         if (isSystemApp(p.owner)) {
   6152                             if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
   6153                                 // It's a built-in permission and no owner, take ownership now
   6154                                 bp.packageSetting = pkgSetting;
   6155                                 bp.perm = p;
   6156                                 bp.uid = pkg.applicationInfo.uid;
   6157                                 bp.sourcePackage = p.info.packageName;
   6158                             } else if (!currentOwnerIsSystem) {
   6159                                 String msg = "New decl " + p.owner + " of permission  "
   6160                                         + p.info.name + " is system; overriding " + bp.sourcePackage;
   6161                                 reportSettingsProblem(Log.WARN, msg);
   6162                                 bp = null;
   6163                             }
   6164                         }
   6165                     }
   6166 
   6167                     if (bp == null) {
   6168                         bp = new BasePermission(p.info.name, p.info.packageName,
   6169                                 BasePermission.TYPE_NORMAL);
   6170                         permissionMap.put(p.info.name, bp);
   6171                     }
   6172 
   6173                     if (bp.perm == null) {
   6174                         if (bp.sourcePackage == null
   6175                                 || bp.sourcePackage.equals(p.info.packageName)) {
   6176                             BasePermission tree = findPermissionTreeLP(p.info.name);
   6177                             if (tree == null
   6178                                     || tree.sourcePackage.equals(p.info.packageName)) {
   6179                                 bp.packageSetting = pkgSetting;
   6180                                 bp.perm = p;
   6181                                 bp.uid = pkg.applicationInfo.uid;
   6182                                 bp.sourcePackage = p.info.packageName;
   6183                                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6184                                     if (r == null) {
   6185                                         r = new StringBuilder(256);
   6186                                     } else {
   6187                                         r.append(' ');
   6188                                     }
   6189                                     r.append(p.info.name);
   6190                                 }
   6191                             } else {
   6192                                 Slog.w(TAG, "Permission " + p.info.name + " from package "
   6193                                         + p.info.packageName + " ignored: base tree "
   6194                                         + tree.name + " is from package "
   6195                                         + tree.sourcePackage);
   6196                             }
   6197                         } else {
   6198                             Slog.w(TAG, "Permission " + p.info.name + " from package "
   6199                                     + p.info.packageName + " ignored: original from "
   6200                                     + bp.sourcePackage);
   6201                         }
   6202                     } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6203                         if (r == null) {
   6204                             r = new StringBuilder(256);
   6205                         } else {
   6206                             r.append(' ');
   6207                         }
   6208                         r.append("DUP:");
   6209                         r.append(p.info.name);
   6210                     }
   6211                     if (bp.perm == p) {
   6212                         bp.protectionLevel = p.info.protectionLevel;
   6213                     }
   6214                 } else {
   6215                     Slog.w(TAG, "Permission " + p.info.name + " from package "
   6216                             + p.info.packageName + " ignored: no group "
   6217                             + p.group);
   6218                 }
   6219             }
   6220             if (r != null) {
   6221                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
   6222             }
   6223 
   6224             N = pkg.instrumentation.size();
   6225             r = null;
   6226             for (i=0; i<N; i++) {
   6227                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
   6228                 a.info.packageName = pkg.applicationInfo.packageName;
   6229                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
   6230                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
   6231                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
   6232                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
   6233                 a.info.dataDir = pkg.applicationInfo.dataDir;
   6234 
   6235                 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
   6236                 // need other information about the application, like the ABI and what not ?
   6237                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
   6238                 mInstrumentation.put(a.getComponentName(), a);
   6239                 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
   6240                     if (r == null) {
   6241                         r = new StringBuilder(256);
   6242                     } else {
   6243                         r.append(' ');
   6244                     }
   6245                     r.append(a.info.name);
   6246                 }
   6247             }
   6248             if (r != null) {
   6249                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
   6250             }
   6251 
   6252             if (pkg.protectedBroadcasts != null) {
   6253                 N = pkg.protectedBroadcasts.size();
   6254                 for (i=0; i<N; i++) {
   6255                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
   6256                 }
   6257             }
   6258 
   6259             pkgSetting.setTimeStamp(scanFileTime);
   6260 
   6261             // Create idmap files for pairs of (packages, overlay packages).
   6262             // Note: "android", ie framework-res.apk, is handled by native layers.
   6263             if (pkg.mOverlayTarget != null) {
   6264                 // This is an overlay package.
   6265                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
   6266                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
   6267                         mOverlays.put(pkg.mOverlayTarget,
   6268                                 new HashMap<String, PackageParser.Package>());
   6269                     }
   6270                     HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
   6271                     map.put(pkg.packageName, pkg);
   6272                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
   6273                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
   6274                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
   6275                                 "scanPackageLI failed to createIdmap");
   6276                     }
   6277                 }
   6278             } else if (mOverlays.containsKey(pkg.packageName) &&
   6279                     !pkg.packageName.equals("android")) {
   6280                 // This is a regular package, with one or more known overlay packages.
   6281                 createIdmapsForPackageLI(pkg);
   6282             }
   6283         }
   6284 
   6285         return pkg;
   6286     }
   6287 
   6288     /**
   6289      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
   6290      * i.e, so that all packages can be run inside a single process if required.
   6291      *
   6292      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
   6293      * this function will either try and make the ABI for all packages in {@code packagesForUser}
   6294      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
   6295      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
   6296      * updating a package that belongs to a shared user.
   6297      *
   6298      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
   6299      * adds unnecessary complexity.
   6300      */
   6301     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
   6302             PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
   6303         String requiredInstructionSet = null;
   6304         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
   6305             requiredInstructionSet = VMRuntime.getInstructionSet(
   6306                      scannedPackage.applicationInfo.primaryCpuAbi);
   6307         }
   6308 
   6309         PackageSetting requirer = null;
   6310         for (PackageSetting ps : packagesForUser) {
   6311             // If packagesForUser contains scannedPackage, we skip it. This will happen
   6312             // when scannedPackage is an update of an existing package. Without this check,
   6313             // we will never be able to change the ABI of any package belonging to a shared
   6314             // user, even if it's compatible with other packages.
   6315             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
   6316                 if (ps.primaryCpuAbiString == null) {
   6317                     continue;
   6318                 }
   6319 
   6320                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
   6321                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
   6322                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
   6323                     // this but there's not much we can do.
   6324                     String errorMessage = "Instruction set mismatch, "
   6325                             + ((requirer == null) ? "[caller]" : requirer)
   6326                             + " requires " + requiredInstructionSet + " whereas " + ps
   6327                             + " requires " + instructionSet;
   6328                     Slog.w(TAG, errorMessage);
   6329                 }
   6330 
   6331                 if (requiredInstructionSet == null) {
   6332                     requiredInstructionSet = instructionSet;
   6333                     requirer = ps;
   6334                 }
   6335             }
   6336         }
   6337 
   6338         if (requiredInstructionSet != null) {
   6339             String adjustedAbi;
   6340             if (requirer != null) {
   6341                 // requirer != null implies that either scannedPackage was null or that scannedPackage
   6342                 // did not require an ABI, in which case we have to adjust scannedPackage to match
   6343                 // the ABI of the set (which is the same as requirer's ABI)
   6344                 adjustedAbi = requirer.primaryCpuAbiString;
   6345                 if (scannedPackage != null) {
   6346                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
   6347                 }
   6348             } else {
   6349                 // requirer == null implies that we're updating all ABIs in the set to
   6350                 // match scannedPackage.
   6351                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
   6352             }
   6353 
   6354             for (PackageSetting ps : packagesForUser) {
   6355                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
   6356                     if (ps.primaryCpuAbiString != null) {
   6357                         continue;
   6358                     }
   6359 
   6360                     ps.primaryCpuAbiString = adjustedAbi;
   6361                     if (ps.pkg != null && ps.pkg.applicationInfo != null) {
   6362                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
   6363                         Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
   6364 
   6365                         if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
   6366                                 deferDexOpt, true) == DEX_OPT_FAILED) {
   6367                             ps.primaryCpuAbiString = null;
   6368                             ps.pkg.applicationInfo.primaryCpuAbi = null;
   6369                             return;
   6370                         } else {
   6371                             mInstaller.rmdex(ps.codePathString,
   6372                                              getDexCodeInstructionSet(getPreferredInstructionSet()));
   6373                         }
   6374                     }
   6375                 }
   6376             }
   6377         }
   6378     }
   6379 
   6380     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
   6381         synchronized (mPackages) {
   6382             mResolverReplaced = true;
   6383             // Set up information for custom user intent resolution activity.
   6384             mResolveActivity.applicationInfo = pkg.applicationInfo;
   6385             mResolveActivity.name = mCustomResolverComponentName.getClassName();
   6386             mResolveActivity.packageName = pkg.applicationInfo.packageName;
   6387             mResolveActivity.processName = null;
   6388             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
   6389             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
   6390                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
   6391             mResolveActivity.theme = 0;
   6392             mResolveActivity.exported = true;
   6393             mResolveActivity.enabled = true;
   6394             mResolveInfo.activityInfo = mResolveActivity;
   6395             mResolveInfo.priority = 0;
   6396             mResolveInfo.preferredOrder = 0;
   6397             mResolveInfo.match = 0;
   6398             mResolveComponentName = mCustomResolverComponentName;
   6399             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
   6400                     mResolveComponentName);
   6401         }
   6402     }
   6403 
   6404     private static String calculateBundledApkRoot(final String codePathString) {
   6405         final File codePath = new File(codePathString);
   6406         final File codeRoot;
   6407         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
   6408             codeRoot = Environment.getRootDirectory();
   6409         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
   6410             codeRoot = Environment.getOemDirectory();
   6411         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
   6412             codeRoot = Environment.getVendorDirectory();
   6413         } else {
   6414             // Unrecognized code path; take its top real segment as the apk root:
   6415             // e.g. /something/app/blah.apk => /something
   6416             try {
   6417                 File f = codePath.getCanonicalFile();
   6418                 File parent = f.getParentFile();    // non-null because codePath is a file
   6419                 File tmp;
   6420                 while ((tmp = parent.getParentFile()) != null) {
   6421                     f = parent;
   6422                     parent = tmp;
   6423                 }
   6424                 codeRoot = f;
   6425                 Slog.w(TAG, "Unrecognized code path "
   6426                         + codePath + " - using " + codeRoot);
   6427             } catch (IOException e) {
   6428                 // Can't canonicalize the code path -- shenanigans?
   6429                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
   6430                 return Environment.getRootDirectory().getPath();
   6431             }
   6432         }
   6433         return codeRoot.getPath();
   6434     }
   6435 
   6436     /**
   6437      * Derive and set the location of native libraries for the given package,
   6438      * which varies depending on where and how the package was installed.
   6439      */
   6440     private void setNativeLibraryPaths(PackageParser.Package pkg) {
   6441         final ApplicationInfo info = pkg.applicationInfo;
   6442         final String codePath = pkg.codePath;
   6443         final File codeFile = new File(codePath);
   6444         final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
   6445         final boolean asecApp = isForwardLocked(info) || isExternal(info);
   6446 
   6447         info.nativeLibraryRootDir = null;
   6448         info.nativeLibraryRootRequiresIsa = false;
   6449         info.nativeLibraryDir = null;
   6450         info.secondaryNativeLibraryDir = null;
   6451 
   6452         if (isApkFile(codeFile)) {
   6453             // Monolithic install
   6454             if (bundledApp) {
   6455                 // If "/system/lib64/apkname" exists, assume that is the per-package
   6456                 // native library directory to use; otherwise use "/system/lib/apkname".
   6457                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
   6458                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
   6459                         getPrimaryInstructionSet(info));
   6460 
   6461                 // This is a bundled system app so choose the path based on the ABI.
   6462                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
   6463                 // is just the default path.
   6464                 final String apkName = deriveCodePathName(codePath);
   6465                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
   6466                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
   6467                         apkName).getAbsolutePath();
   6468 
   6469                 if (info.secondaryCpuAbi != null) {
   6470                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
   6471                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
   6472                             secondaryLibDir, apkName).getAbsolutePath();
   6473                 }
   6474             } else if (asecApp) {
   6475                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
   6476                         .getAbsolutePath();
   6477             } else {
   6478                 final String apkName = deriveCodePathName(codePath);
   6479                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
   6480                         .getAbsolutePath();
   6481             }
   6482 
   6483             info.nativeLibraryRootRequiresIsa = false;
   6484             info.nativeLibraryDir = info.nativeLibraryRootDir;
   6485         } else {
   6486             // Cluster install
   6487             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
   6488             info.nativeLibraryRootRequiresIsa = true;
   6489 
   6490             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
   6491                     getPrimaryInstructionSet(info)).getAbsolutePath();
   6492 
   6493             if (info.secondaryCpuAbi != null) {
   6494                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
   6495                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
   6496             }
   6497         }
   6498     }
   6499 
   6500     /**
   6501      * Calculate the abis and roots for a bundled app. These can uniquely
   6502      * be determined from the contents of the system partition, i.e whether
   6503      * it contains 64 or 32 bit shared libraries etc. We do not validate any
   6504      * of this information, and instead assume that the system was built
   6505      * sensibly.
   6506      */
   6507     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
   6508                                            PackageSetting pkgSetting) {
   6509         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
   6510 
   6511         // If "/system/lib64/apkname" exists, assume that is the per-package
   6512         // native library directory to use; otherwise use "/system/lib/apkname".
   6513         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
   6514         setBundledAppAbi(pkg, apkRoot, apkName);
   6515         // pkgSetting might be null during rescan following uninstall of updates
   6516         // to a bundled app, so accommodate that possibility.  The settings in
   6517         // that case will be established later from the parsed package.
   6518         //
   6519         // If the settings aren't null, sync them up with what we've just derived.
   6520         // note that apkRoot isn't stored in the package settings.
   6521         if (pkgSetting != null) {
   6522             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
   6523             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
   6524         }
   6525     }
   6526 
   6527     /**
   6528      * Deduces the ABI of a bundled app and sets the relevant fields on the
   6529      * parsed pkg object.
   6530      *
   6531      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
   6532      *        under which system libraries are installed.
   6533      * @param apkName the name of the installed package.
   6534      */
   6535     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
   6536         final File codeFile = new File(pkg.codePath);
   6537 
   6538         final boolean has64BitLibs;
   6539         final boolean has32BitLibs;
   6540         if (isApkFile(codeFile)) {
   6541             // Monolithic install
   6542             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
   6543             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
   6544         } else {
   6545             // Cluster install
   6546             final File rootDir = new File(codeFile, LIB_DIR_NAME);
   6547             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
   6548                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
   6549                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
   6550                 has64BitLibs = (new File(rootDir, isa)).exists();
   6551             } else {
   6552                 has64BitLibs = false;
   6553             }
   6554             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
   6555                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
   6556                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
   6557                 has32BitLibs = (new File(rootDir, isa)).exists();
   6558             } else {
   6559                 has32BitLibs = false;
   6560             }
   6561         }
   6562 
   6563         if (has64BitLibs && !has32BitLibs) {
   6564             // The package has 64 bit libs, but not 32 bit libs. Its primary
   6565             // ABI should be 64 bit. We can safely assume here that the bundled
   6566             // native libraries correspond to the most preferred ABI in the list.
   6567 
   6568             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
   6569             pkg.applicationInfo.secondaryCpuAbi = null;
   6570         } else if (has32BitLibs && !has64BitLibs) {
   6571             // The package has 32 bit libs but not 64 bit libs. Its primary
   6572             // ABI should be 32 bit.
   6573 
   6574             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   6575             pkg.applicationInfo.secondaryCpuAbi = null;
   6576         } else if (has32BitLibs && has64BitLibs) {
   6577             // The application has both 64 and 32 bit bundled libraries. We check
   6578             // here that the app declares multiArch support, and warn if it doesn't.
   6579             //
   6580             // We will be lenient here and record both ABIs. The primary will be the
   6581             // ABI that's higher on the list, i.e, a device that's configured to prefer
   6582             // 64 bit apps will see a 64 bit primary ABI,
   6583 
   6584             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
   6585                 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
   6586             }
   6587 
   6588             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
   6589                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
   6590                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   6591             } else {
   6592                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
   6593                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
   6594             }
   6595         } else {
   6596             pkg.applicationInfo.primaryCpuAbi = null;
   6597             pkg.applicationInfo.secondaryCpuAbi = null;
   6598         }
   6599     }
   6600 
   6601     private void killApplication(String pkgName, int appId, String reason) {
   6602         // Request the ActivityManager to kill the process(only for existing packages)
   6603         // so that we do not end up in a confused state while the user is still using the older
   6604         // version of the application while the new one gets installed.
   6605         IActivityManager am = ActivityManagerNative.getDefault();
   6606         if (am != null) {
   6607             try {
   6608                 am.killApplicationWithAppId(pkgName, appId, reason);
   6609             } catch (RemoteException e) {
   6610             }
   6611         }
   6612     }
   6613 
   6614     void removePackageLI(PackageSetting ps, boolean chatty) {
   6615         if (DEBUG_INSTALL) {
   6616             if (chatty)
   6617                 Log.d(TAG, "Removing package " + ps.name);
   6618         }
   6619 
   6620         // writer
   6621         synchronized (mPackages) {
   6622             mPackages.remove(ps.name);
   6623             final PackageParser.Package pkg = ps.pkg;
   6624             if (pkg != null) {
   6625                 cleanPackageDataStructuresLILPw(pkg, chatty);
   6626             }
   6627         }
   6628     }
   6629 
   6630     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
   6631         if (DEBUG_INSTALL) {
   6632             if (chatty)
   6633                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
   6634         }
   6635 
   6636         // writer
   6637         synchronized (mPackages) {
   6638             mPackages.remove(pkg.applicationInfo.packageName);
   6639             cleanPackageDataStructuresLILPw(pkg, chatty);
   6640         }
   6641     }
   6642 
   6643     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
   6644         int N = pkg.providers.size();
   6645         StringBuilder r = null;
   6646         int i;
   6647         for (i=0; i<N; i++) {
   6648             PackageParser.Provider p = pkg.providers.get(i);
   6649             mProviders.removeProvider(p);
   6650             if (p.info.authority == null) {
   6651 
   6652                 /* There was another ContentProvider with this authority when
   6653                  * this app was installed so this authority is null,
   6654                  * Ignore it as we don't have to unregister the provider.
   6655                  */
   6656                 continue;
   6657             }
   6658             String names[] = p.info.authority.split(";");
   6659             for (int j = 0; j < names.length; j++) {
   6660                 if (mProvidersByAuthority.get(names[j]) == p) {
   6661                     mProvidersByAuthority.remove(names[j]);
   6662                     if (DEBUG_REMOVE) {
   6663                         if (chatty)
   6664                             Log.d(TAG, "Unregistered content provider: " + names[j]
   6665                                     + ", className = " + p.info.name + ", isSyncable = "
   6666                                     + p.info.isSyncable);
   6667                     }
   6668                 }
   6669             }
   6670             if (DEBUG_REMOVE && chatty) {
   6671                 if (r == null) {
   6672                     r = new StringBuilder(256);
   6673                 } else {
   6674                     r.append(' ');
   6675                 }
   6676                 r.append(p.info.name);
   6677             }
   6678         }
   6679         if (r != null) {
   6680             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
   6681         }
   6682 
   6683         N = pkg.services.size();
   6684         r = null;
   6685         for (i=0; i<N; i++) {
   6686             PackageParser.Service s = pkg.services.get(i);
   6687             mServices.removeService(s);
   6688             if (chatty) {
   6689                 if (r == null) {
   6690                     r = new StringBuilder(256);
   6691                 } else {
   6692                     r.append(' ');
   6693                 }
   6694                 r.append(s.info.name);
   6695             }
   6696         }
   6697         if (r != null) {
   6698             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
   6699         }
   6700 
   6701         N = pkg.receivers.size();
   6702         r = null;
   6703         for (i=0; i<N; i++) {
   6704             PackageParser.Activity a = pkg.receivers.get(i);
   6705             mReceivers.removeActivity(a, "receiver");
   6706             if (DEBUG_REMOVE && chatty) {
   6707                 if (r == null) {
   6708                     r = new StringBuilder(256);
   6709                 } else {
   6710                     r.append(' ');
   6711                 }
   6712                 r.append(a.info.name);
   6713             }
   6714         }
   6715         if (r != null) {
   6716             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
   6717         }
   6718 
   6719         N = pkg.activities.size();
   6720         r = null;
   6721         for (i=0; i<N; i++) {
   6722             PackageParser.Activity a = pkg.activities.get(i);
   6723             mActivities.removeActivity(a, "activity");
   6724             if (DEBUG_REMOVE && chatty) {
   6725                 if (r == null) {
   6726                     r = new StringBuilder(256);
   6727                 } else {
   6728                     r.append(' ');
   6729                 }
   6730                 r.append(a.info.name);
   6731             }
   6732         }
   6733         if (r != null) {
   6734             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
   6735         }
   6736 
   6737         N = pkg.permissions.size();
   6738         r = null;
   6739         for (i=0; i<N; i++) {
   6740             PackageParser.Permission p = pkg.permissions.get(i);
   6741             BasePermission bp = mSettings.mPermissions.get(p.info.name);
   6742             if (bp == null) {
   6743                 bp = mSettings.mPermissionTrees.get(p.info.name);
   6744             }
   6745             if (bp != null && bp.perm == p) {
   6746                 bp.perm = null;
   6747                 if (DEBUG_REMOVE && chatty) {
   6748                     if (r == null) {
   6749                         r = new StringBuilder(256);
   6750                     } else {
   6751                         r.append(' ');
   6752                     }
   6753                     r.append(p.info.name);
   6754                 }
   6755             }
   6756             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
   6757                 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
   6758                 if (appOpPerms != null) {
   6759                     appOpPerms.remove(pkg.packageName);
   6760                 }
   6761             }
   6762         }
   6763         if (r != null) {
   6764             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
   6765         }
   6766 
   6767         N = pkg.requestedPermissions.size();
   6768         r = null;
   6769         for (i=0; i<N; i++) {
   6770             String perm = pkg.requestedPermissions.get(i);
   6771             BasePermission bp = mSettings.mPermissions.get(perm);
   6772             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
   6773                 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
   6774                 if (appOpPerms != null) {
   6775                     appOpPerms.remove(pkg.packageName);
   6776                     if (appOpPerms.isEmpty()) {
   6777                         mAppOpPermissionPackages.remove(perm);
   6778                     }
   6779                 }
   6780             }
   6781         }
   6782         if (r != null) {
   6783             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
   6784         }
   6785 
   6786         N = pkg.instrumentation.size();
   6787         r = null;
   6788         for (i=0; i<N; i++) {
   6789             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
   6790             mInstrumentation.remove(a.getComponentName());
   6791             if (DEBUG_REMOVE && chatty) {
   6792                 if (r == null) {
   6793                     r = new StringBuilder(256);
   6794                 } else {
   6795                     r.append(' ');
   6796                 }
   6797                 r.append(a.info.name);
   6798             }
   6799         }
   6800         if (r != null) {
   6801             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
   6802         }
   6803 
   6804         r = null;
   6805         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
   6806             // Only system apps can hold shared libraries.
   6807             if (pkg.libraryNames != null) {
   6808                 for (i=0; i<pkg.libraryNames.size(); i++) {
   6809                     String name = pkg.libraryNames.get(i);
   6810                     SharedLibraryEntry cur = mSharedLibraries.get(name);
   6811                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
   6812                         mSharedLibraries.remove(name);
   6813                         if (DEBUG_REMOVE && chatty) {
   6814                             if (r == null) {
   6815                                 r = new StringBuilder(256);
   6816                             } else {
   6817                                 r.append(' ');
   6818                             }
   6819                             r.append(name);
   6820                         }
   6821                     }
   6822                 }
   6823             }
   6824         }
   6825         if (r != null) {
   6826             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
   6827         }
   6828     }
   6829 
   6830     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
   6831         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
   6832             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
   6833                 return true;
   6834             }
   6835         }
   6836         return false;
   6837     }
   6838 
   6839     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
   6840     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
   6841     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
   6842 
   6843     private void updatePermissionsLPw(String changingPkg,
   6844             PackageParser.Package pkgInfo, int flags) {
   6845         // Make sure there are no dangling permission trees.
   6846         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
   6847         while (it.hasNext()) {
   6848             final BasePermission bp = it.next();
   6849             if (bp.packageSetting == null) {
   6850                 // We may not yet have parsed the package, so just see if
   6851                 // we still know about its settings.
   6852                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
   6853             }
   6854             if (bp.packageSetting == null) {
   6855                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
   6856                         + " from package " + bp.sourcePackage);
   6857                 it.remove();
   6858             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
   6859                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
   6860                     Slog.i(TAG, "Removing old permission tree: " + bp.name
   6861                             + " from package " + bp.sourcePackage);
   6862                     flags |= UPDATE_PERMISSIONS_ALL;
   6863                     it.remove();
   6864                 }
   6865             }
   6866         }
   6867 
   6868         // Make sure all dynamic permissions have been assigned to a package,
   6869         // and make sure there are no dangling permissions.
   6870         it = mSettings.mPermissions.values().iterator();
   6871         while (it.hasNext()) {
   6872             final BasePermission bp = it.next();
   6873             if (bp.type == BasePermission.TYPE_DYNAMIC) {
   6874                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
   6875                         + bp.name + " pkg=" + bp.sourcePackage
   6876                         + " info=" + bp.pendingInfo);
   6877                 if (bp.packageSetting == null && bp.pendingInfo != null) {
   6878                     final BasePermission tree = findPermissionTreeLP(bp.name);
   6879                     if (tree != null && tree.perm != null) {
   6880                         bp.packageSetting = tree.packageSetting;
   6881                         bp.perm = new PackageParser.Permission(tree.perm.owner,
   6882                                 new PermissionInfo(bp.pendingInfo));
   6883                         bp.perm.info.packageName = tree.perm.info.packageName;
   6884                         bp.perm.info.name = bp.name;
   6885                         bp.uid = tree.uid;
   6886                     }
   6887                 }
   6888             }
   6889             if (bp.packageSetting == null) {
   6890                 // We may not yet have parsed the package, so just see if
   6891                 // we still know about its settings.
   6892                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
   6893             }
   6894             if (bp.packageSetting == null) {
   6895                 Slog.w(TAG, "Removing dangling permission: " + bp.name
   6896                         + " from package " + bp.sourcePackage);
   6897                 it.remove();
   6898             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
   6899                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
   6900                     Slog.i(TAG, "Removing old permission: " + bp.name
   6901                             + " from package " + bp.sourcePackage);
   6902                     flags |= UPDATE_PERMISSIONS_ALL;
   6903                     it.remove();
   6904                 }
   6905             }
   6906         }
   6907 
   6908         // Now update the permissions for all packages, in particular
   6909         // replace the granted permissions of the system packages.
   6910         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
   6911             for (PackageParser.Package pkg : mPackages.values()) {
   6912                 if (pkg != pkgInfo) {
   6913                     grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
   6914                             changingPkg);
   6915                 }
   6916             }
   6917         }
   6918 
   6919         if (pkgInfo != null) {
   6920             grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
   6921         }
   6922     }
   6923 
   6924     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
   6925             String packageOfInterest) {
   6926         final PackageSetting ps = (PackageSetting) pkg.mExtras;
   6927         if (ps == null) {
   6928             return;
   6929         }
   6930         final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
   6931         HashSet<String> origPermissions = gp.grantedPermissions;
   6932         boolean changedPermission = false;
   6933 
   6934         if (replace) {
   6935             ps.permissionsFixed = false;
   6936             if (gp == ps) {
   6937                 origPermissions = new HashSet<String>(gp.grantedPermissions);
   6938                 gp.grantedPermissions.clear();
   6939                 gp.gids = mGlobalGids;
   6940             }
   6941         }
   6942 
   6943         if (gp.gids == null) {
   6944             gp.gids = mGlobalGids;
   6945         }
   6946 
   6947         final int N = pkg.requestedPermissions.size();
   6948         for (int i=0; i<N; i++) {
   6949             final String name = pkg.requestedPermissions.get(i);
   6950             final boolean required = pkg.requestedPermissionsRequired.get(i);
   6951             final BasePermission bp = mSettings.mPermissions.get(name);
   6952             if (DEBUG_INSTALL) {
   6953                 if (gp != ps) {
   6954                     Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
   6955                 }
   6956             }
   6957 
   6958             if (bp == null || bp.packageSetting == null) {
   6959                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
   6960                     Slog.w(TAG, "Unknown permission " + name
   6961                             + " in package " + pkg.packageName);
   6962                 }
   6963                 continue;
   6964             }
   6965 
   6966             final String perm = bp.name;
   6967             boolean allowed;
   6968             boolean allowedSig = false;
   6969             if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
   6970                 // Keep track of app op permissions.
   6971                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
   6972                 if (pkgs == null) {
   6973                     pkgs = new ArraySet<>();
   6974                     mAppOpPermissionPackages.put(bp.name, pkgs);
   6975                 }
   6976                 pkgs.add(pkg.packageName);
   6977             }
   6978             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
   6979             if (level == PermissionInfo.PROTECTION_NORMAL
   6980                     || level == PermissionInfo.PROTECTION_DANGEROUS) {
   6981                 // We grant a normal or dangerous permission if any of the following
   6982                 // are true:
   6983                 // 1) The permission is required
   6984                 // 2) The permission is optional, but was granted in the past
   6985                 // 3) The permission is optional, but was requested by an
   6986                 //    app in /system (not /data)
   6987                 //
   6988                 // Otherwise, reject the permission.
   6989                 allowed = (required || origPermissions.contains(perm)
   6990                         || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
   6991             } else if (bp.packageSetting == null) {
   6992                 // This permission is invalid; skip it.
   6993                 allowed = false;
   6994             } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
   6995                 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
   6996                 if (allowed) {
   6997                     allowedSig = true;
   6998                 }
   6999             } else {
   7000                 allowed = false;
   7001             }
   7002             if (DEBUG_INSTALL) {
   7003                 if (gp != ps) {
   7004                     Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
   7005                 }
   7006             }
   7007             if (allowed) {
   7008                 if (!isSystemApp(ps) && ps.permissionsFixed) {
   7009                     // If this is an existing, non-system package, then
   7010                     // we can't add any new permissions to it.
   7011                     if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
   7012                         // Except...  if this is a permission that was added
   7013                         // to the platform (note: need to only do this when
   7014                         // updating the platform).
   7015                         allowed = isNewPlatformPermissionForPackage(perm, pkg);
   7016                     }
   7017                 }
   7018                 if (allowed) {
   7019                     if (!gp.grantedPermissions.contains(perm)) {
   7020                         changedPermission = true;
   7021                         gp.grantedPermissions.add(perm);
   7022                         gp.gids = appendInts(gp.gids, bp.gids);
   7023                     } else if (!ps.haveGids) {
   7024                         gp.gids = appendInts(gp.gids, bp.gids);
   7025                     }
   7026                 } else {
   7027                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
   7028                         Slog.w(TAG, "Not granting permission " + perm
   7029                                 + " to package " + pkg.packageName
   7030                                 + " because it was previously installed without");
   7031                     }
   7032                 }
   7033             } else {
   7034                 if (gp.grantedPermissions.remove(perm)) {
   7035                     changedPermission = true;
   7036                     gp.gids = removeInts(gp.gids, bp.gids);
   7037                     Slog.i(TAG, "Un-granting permission " + perm
   7038                             + " from package " + pkg.packageName
   7039                             + " (protectionLevel=" + bp.protectionLevel
   7040                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
   7041                             + ")");
   7042                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
   7043                     // Don't print warning for app op permissions, since it is fine for them
   7044                     // not to be granted, there is a UI for the user to decide.
   7045                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
   7046                         Slog.w(TAG, "Not granting permission " + perm
   7047                                 + " to package " + pkg.packageName
   7048                                 + " (protectionLevel=" + bp.protectionLevel
   7049                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
   7050                                 + ")");
   7051                     }
   7052                 }
   7053             }
   7054         }
   7055 
   7056         if ((changedPermission || replace) && !ps.permissionsFixed &&
   7057                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
   7058             // This is the first that we have heard about this package, so the
   7059             // permissions we have now selected are fixed until explicitly
   7060             // changed.
   7061             ps.permissionsFixed = true;
   7062         }
   7063         ps.haveGids = true;
   7064     }
   7065 
   7066     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
   7067         boolean allowed = false;
   7068         final int NP = PackageParser.NEW_PERMISSIONS.length;
   7069         for (int ip=0; ip<NP; ip++) {
   7070             final PackageParser.NewPermissionInfo npi
   7071                     = PackageParser.NEW_PERMISSIONS[ip];
   7072             if (npi.name.equals(perm)
   7073                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
   7074                 allowed = true;
   7075                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
   7076                         + pkg.packageName);
   7077                 break;
   7078             }
   7079         }
   7080         return allowed;
   7081     }
   7082 
   7083     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
   7084                                           BasePermission bp, HashSet<String> origPermissions) {
   7085         boolean allowed;
   7086         allowed = (compareSignatures(
   7087                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
   7088                         == PackageManager.SIGNATURE_MATCH)
   7089                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
   7090                         == PackageManager.SIGNATURE_MATCH);
   7091         if (!allowed && (bp.protectionLevel
   7092                 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
   7093             if (isSystemApp(pkg)) {
   7094                 // For updated system applications, a system permission
   7095                 // is granted only if it had been defined by the original application.
   7096                 if (isUpdatedSystemApp(pkg)) {
   7097                     final PackageSetting sysPs = mSettings
   7098                             .getDisabledSystemPkgLPr(pkg.packageName);
   7099                     final GrantedPermissions origGp = sysPs.sharedUser != null
   7100                             ? sysPs.sharedUser : sysPs;
   7101 
   7102                     if (origGp.grantedPermissions.contains(perm)) {
   7103                         // If the original was granted this permission, we take
   7104                         // that grant decision as read and propagate it to the
   7105                         // update.
   7106                         allowed = true;
   7107                     } else {
   7108                         // The system apk may have been updated with an older
   7109                         // version of the one on the data partition, but which
   7110                         // granted a new system permission that it didn't have
   7111                         // before.  In this case we do want to allow the app to
   7112                         // now get the new permission if the ancestral apk is
   7113                         // privileged to get it.
   7114                         if (sysPs.pkg != null && sysPs.isPrivileged()) {
   7115                             for (int j=0;
   7116                                     j<sysPs.pkg.requestedPermissions.size(); j++) {
   7117                                 if (perm.equals(
   7118                                         sysPs.pkg.requestedPermissions.get(j))) {
   7119                                     allowed = true;
   7120                                     break;
   7121                                 }
   7122                             }
   7123                         }
   7124                     }
   7125                 } else {
   7126                     allowed = isPrivilegedApp(pkg);
   7127                 }
   7128             }
   7129         }
   7130         if (!allowed && (bp.protectionLevel
   7131                 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
   7132             // For development permissions, a development permission
   7133             // is granted only if it was already granted.
   7134             allowed = origPermissions.contains(perm);
   7135         }
   7136         return allowed;
   7137     }
   7138 
   7139     final class ActivityIntentResolver
   7140             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
   7141         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
   7142                 boolean defaultOnly, int userId) {
   7143             if (!sUserManager.exists(userId)) return null;
   7144             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
   7145             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
   7146         }
   7147 
   7148         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
   7149                 int userId) {
   7150             if (!sUserManager.exists(userId)) return null;
   7151             mFlags = flags;
   7152             return super.queryIntent(intent, resolvedType,
   7153                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
   7154         }
   7155 
   7156         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
   7157                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
   7158             if (!sUserManager.exists(userId)) return null;
   7159             if (packageActivities == null) {
   7160                 return null;
   7161             }
   7162             mFlags = flags;
   7163             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
   7164             final int N = packageActivities.size();
   7165             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
   7166                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
   7167 
   7168             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
   7169             for (int i = 0; i < N; ++i) {
   7170                 intentFilters = packageActivities.get(i).intents;
   7171                 if (intentFilters != null && intentFilters.size() > 0) {
   7172                     PackageParser.ActivityIntentInfo[] array =
   7173                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
   7174                     intentFilters.toArray(array);
   7175                     listCut.add(array);
   7176                 }
   7177             }
   7178             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
   7179         }
   7180 
   7181         public final void addActivity(PackageParser.Activity a, String type) {
   7182             final boolean systemApp = isSystemApp(a.info.applicationInfo);
   7183             mActivities.put(a.getComponentName(), a);
   7184             if (DEBUG_SHOW_INFO)
   7185                 Log.v(
   7186                 TAG, "  " + type + " " +
   7187                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
   7188             if (DEBUG_SHOW_INFO)
   7189                 Log.v(TAG, "    Class=" + a.info.name);
   7190             final int NI = a.intents.size();
   7191             for (int j=0; j<NI; j++) {
   7192                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
   7193                 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
   7194                     intent.setPriority(0);
   7195                     Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
   7196                             + a.className + " with priority > 0, forcing to 0");
   7197                 }
   7198                 if (DEBUG_SHOW_INFO) {
   7199                     Log.v(TAG, "    IntentFilter:");
   7200                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   7201                 }
   7202                 if (!intent.debugCheck()) {
   7203                     Log.w(TAG, "==> For Activity " + a.info.name);
   7204                 }
   7205                 addFilter(intent);
   7206             }
   7207         }
   7208 
   7209         public final void removeActivity(PackageParser.Activity a, String type) {
   7210             mActivities.remove(a.getComponentName());
   7211             if (DEBUG_SHOW_INFO) {
   7212                 Log.v(TAG, "  " + type + " "
   7213                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
   7214                                 : a.info.name) + ":");
   7215                 Log.v(TAG, "    Class=" + a.info.name);
   7216             }
   7217             final int NI = a.intents.size();
   7218             for (int j=0; j<NI; j++) {
   7219                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
   7220                 if (DEBUG_SHOW_INFO) {
   7221                     Log.v(TAG, "    IntentFilter:");
   7222                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   7223                 }
   7224                 removeFilter(intent);
   7225             }
   7226         }
   7227 
   7228         @Override
   7229         protected boolean allowFilterResult(
   7230                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
   7231             ActivityInfo filterAi = filter.activity.info;
   7232             for (int i=dest.size()-1; i>=0; i--) {
   7233                 ActivityInfo destAi = dest.get(i).activityInfo;
   7234                 if (destAi.name == filterAi.name
   7235                         && destAi.packageName == filterAi.packageName) {
   7236                     return false;
   7237                 }
   7238             }
   7239             return true;
   7240         }
   7241 
   7242         @Override
   7243         protected ActivityIntentInfo[] newArray(int size) {
   7244             return new ActivityIntentInfo[size];
   7245         }
   7246 
   7247         @Override
   7248         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
   7249             if (!sUserManager.exists(userId)) return true;
   7250             PackageParser.Package p = filter.activity.owner;
   7251             if (p != null) {
   7252                 PackageSetting ps = (PackageSetting)p.mExtras;
   7253                 if (ps != null) {
   7254                     // System apps are never considered stopped for purposes of
   7255                     // filtering, because there may be no way for the user to
   7256                     // actually re-launch them.
   7257                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
   7258                             && ps.getStopped(userId);
   7259                 }
   7260             }
   7261             return false;
   7262         }
   7263 
   7264         @Override
   7265         protected boolean isPackageForFilter(String packageName,
   7266                 PackageParser.ActivityIntentInfo info) {
   7267             return packageName.equals(info.activity.owner.packageName);
   7268         }
   7269 
   7270         @Override
   7271         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
   7272                 int match, int userId) {
   7273             if (!sUserManager.exists(userId)) return null;
   7274             if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
   7275                 return null;
   7276             }
   7277             final PackageParser.Activity activity = info.activity;
   7278             if (mSafeMode && (activity.info.applicationInfo.flags
   7279                     &ApplicationInfo.FLAG_SYSTEM) == 0) {
   7280                 return null;
   7281             }
   7282             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
   7283             if (ps == null) {
   7284                 return null;
   7285             }
   7286             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
   7287                     ps.readUserState(userId), userId);
   7288             if (ai == null) {
   7289                 return null;
   7290             }
   7291             final ResolveInfo res = new ResolveInfo();
   7292             res.activityInfo = ai;
   7293             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
   7294                 res.filter = info;
   7295             }
   7296             res.priority = info.getPriority();
   7297             res.preferredOrder = activity.owner.mPreferredOrder;
   7298             //System.out.println("Result: " + res.activityInfo.className +
   7299             //                   " = " + res.priority);
   7300             res.match = match;
   7301             res.isDefault = info.hasDefault;
   7302             res.labelRes = info.labelRes;
   7303             res.nonLocalizedLabel = info.nonLocalizedLabel;
   7304             if (userNeedsBadging(userId)) {
   7305                 res.noResourceId = true;
   7306             } else {
   7307                 res.icon = info.icon;
   7308             }
   7309             res.system = isSystemApp(res.activityInfo.applicationInfo);
   7310             return res;
   7311         }
   7312 
   7313         @Override
   7314         protected void sortResults(List<ResolveInfo> results) {
   7315             Collections.sort(results, mResolvePrioritySorter);
   7316         }
   7317 
   7318         @Override
   7319         protected void dumpFilter(PrintWriter out, String prefix,
   7320                 PackageParser.ActivityIntentInfo filter) {
   7321             out.print(prefix); out.print(
   7322                     Integer.toHexString(System.identityHashCode(filter.activity)));
   7323                     out.print(' ');
   7324                     filter.activity.printComponentShortName(out);
   7325                     out.print(" filter ");
   7326                     out.println(Integer.toHexString(System.identityHashCode(filter)));
   7327         }
   7328 
   7329 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
   7330 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
   7331 //            final List<ResolveInfo> retList = Lists.newArrayList();
   7332 //            while (i.hasNext()) {
   7333 //                final ResolveInfo resolveInfo = i.next();
   7334 //                if (isEnabledLP(resolveInfo.activityInfo)) {
   7335 //                    retList.add(resolveInfo);
   7336 //                }
   7337 //            }
   7338 //            return retList;
   7339 //        }
   7340 
   7341         // Keys are String (activity class name), values are Activity.
   7342         private final HashMap<ComponentName, PackageParser.Activity> mActivities
   7343                 = new HashMap<ComponentName, PackageParser.Activity>();
   7344         private int mFlags;
   7345     }
   7346 
   7347     private final class ServiceIntentResolver
   7348             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
   7349         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
   7350                 boolean defaultOnly, int userId) {
   7351             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
   7352             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
   7353         }
   7354 
   7355         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
   7356                 int userId) {
   7357             if (!sUserManager.exists(userId)) return null;
   7358             mFlags = flags;
   7359             return super.queryIntent(intent, resolvedType,
   7360                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
   7361         }
   7362 
   7363         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
   7364                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
   7365             if (!sUserManager.exists(userId)) return null;
   7366             if (packageServices == null) {
   7367                 return null;
   7368             }
   7369             mFlags = flags;
   7370             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
   7371             final int N = packageServices.size();
   7372             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
   7373                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
   7374 
   7375             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
   7376             for (int i = 0; i < N; ++i) {
   7377                 intentFilters = packageServices.get(i).intents;
   7378                 if (intentFilters != null && intentFilters.size() > 0) {
   7379                     PackageParser.ServiceIntentInfo[] array =
   7380                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
   7381                     intentFilters.toArray(array);
   7382                     listCut.add(array);
   7383                 }
   7384             }
   7385             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
   7386         }
   7387 
   7388         public final void addService(PackageParser.Service s) {
   7389             mServices.put(s.getComponentName(), s);
   7390             if (DEBUG_SHOW_INFO) {
   7391                 Log.v(TAG, "  "
   7392                         + (s.info.nonLocalizedLabel != null
   7393                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
   7394                 Log.v(TAG, "    Class=" + s.info.name);
   7395             }
   7396             final int NI = s.intents.size();
   7397             int j;
   7398             for (j=0; j<NI; j++) {
   7399                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
   7400                 if (DEBUG_SHOW_INFO) {
   7401                     Log.v(TAG, "    IntentFilter:");
   7402                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   7403                 }
   7404                 if (!intent.debugCheck()) {
   7405                     Log.w(TAG, "==> For Service " + s.info.name);
   7406                 }
   7407                 addFilter(intent);
   7408             }
   7409         }
   7410 
   7411         public final void removeService(PackageParser.Service s) {
   7412             mServices.remove(s.getComponentName());
   7413             if (DEBUG_SHOW_INFO) {
   7414                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
   7415                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
   7416                 Log.v(TAG, "    Class=" + s.info.name);
   7417             }
   7418             final int NI = s.intents.size();
   7419             int j;
   7420             for (j=0; j<NI; j++) {
   7421                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
   7422                 if (DEBUG_SHOW_INFO) {
   7423                     Log.v(TAG, "    IntentFilter:");
   7424                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   7425                 }
   7426                 removeFilter(intent);
   7427             }
   7428         }
   7429 
   7430         @Override
   7431         protected boolean allowFilterResult(
   7432                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
   7433             ServiceInfo filterSi = filter.service.info;
   7434             for (int i=dest.size()-1; i>=0; i--) {
   7435                 ServiceInfo destAi = dest.get(i).serviceInfo;
   7436                 if (destAi.name == filterSi.name
   7437                         && destAi.packageName == filterSi.packageName) {
   7438                     return false;
   7439                 }
   7440             }
   7441             return true;
   7442         }
   7443 
   7444         @Override
   7445         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
   7446             return new PackageParser.ServiceIntentInfo[size];
   7447         }
   7448 
   7449         @Override
   7450         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
   7451             if (!sUserManager.exists(userId)) return true;
   7452             PackageParser.Package p = filter.service.owner;
   7453             if (p != null) {
   7454                 PackageSetting ps = (PackageSetting)p.mExtras;
   7455                 if (ps != null) {
   7456                     // System apps are never considered stopped for purposes of
   7457                     // filtering, because there may be no way for the user to
   7458                     // actually re-launch them.
   7459                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
   7460                             && ps.getStopped(userId);
   7461                 }
   7462             }
   7463             return false;
   7464         }
   7465 
   7466         @Override
   7467         protected boolean isPackageForFilter(String packageName,
   7468                 PackageParser.ServiceIntentInfo info) {
   7469             return packageName.equals(info.service.owner.packageName);
   7470         }
   7471 
   7472         @Override
   7473         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
   7474                 int match, int userId) {
   7475             if (!sUserManager.exists(userId)) return null;
   7476             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
   7477             if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
   7478                 return null;
   7479             }
   7480             final PackageParser.Service service = info.service;
   7481             if (mSafeMode && (service.info.applicationInfo.flags
   7482                     &ApplicationInfo.FLAG_SYSTEM) == 0) {
   7483                 return null;
   7484             }
   7485             PackageSetting ps = (PackageSetting) service.owner.mExtras;
   7486             if (ps == null) {
   7487                 return null;
   7488             }
   7489             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
   7490                     ps.readUserState(userId), userId);
   7491             if (si == null) {
   7492                 return null;
   7493             }
   7494             final ResolveInfo res = new ResolveInfo();
   7495             res.serviceInfo = si;
   7496             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
   7497                 res.filter = filter;
   7498             }
   7499             res.priority = info.getPriority();
   7500             res.preferredOrder = service.owner.mPreferredOrder;
   7501             //System.out.println("Result: " + res.activityInfo.className +
   7502             //                   " = " + res.priority);
   7503             res.match = match;
   7504             res.isDefault = info.hasDefault;
   7505             res.labelRes = info.labelRes;
   7506             res.nonLocalizedLabel = info.nonLocalizedLabel;
   7507             res.icon = info.icon;
   7508             res.system = isSystemApp(res.serviceInfo.applicationInfo);
   7509             return res;
   7510         }
   7511 
   7512         @Override
   7513         protected void sortResults(List<ResolveInfo> results) {
   7514             Collections.sort(results, mResolvePrioritySorter);
   7515         }
   7516 
   7517         @Override
   7518         protected void dumpFilter(PrintWriter out, String prefix,
   7519                 PackageParser.ServiceIntentInfo filter) {
   7520             out.print(prefix); out.print(
   7521                     Integer.toHexString(System.identityHashCode(filter.service)));
   7522                     out.print(' ');
   7523                     filter.service.printComponentShortName(out);
   7524                     out.print(" filter ");
   7525                     out.println(Integer.toHexString(System.identityHashCode(filter)));
   7526         }
   7527 
   7528 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
   7529 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
   7530 //            final List<ResolveInfo> retList = Lists.newArrayList();
   7531 //            while (i.hasNext()) {
   7532 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
   7533 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
   7534 //                    retList.add(resolveInfo);
   7535 //                }
   7536 //            }
   7537 //            return retList;
   7538 //        }
   7539 
   7540         // Keys are String (activity class name), values are Activity.
   7541         private final HashMap<ComponentName, PackageParser.Service> mServices
   7542                 = new HashMap<ComponentName, PackageParser.Service>();
   7543         private int mFlags;
   7544     };
   7545 
   7546     private final class ProviderIntentResolver
   7547             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
   7548         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
   7549                 boolean defaultOnly, int userId) {
   7550             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
   7551             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
   7552         }
   7553 
   7554         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
   7555                 int userId) {
   7556             if (!sUserManager.exists(userId))
   7557                 return null;
   7558             mFlags = flags;
   7559             return super.queryIntent(intent, resolvedType,
   7560                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
   7561         }
   7562 
   7563         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
   7564                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
   7565             if (!sUserManager.exists(userId))
   7566                 return null;
   7567             if (packageProviders == null) {
   7568                 return null;
   7569             }
   7570             mFlags = flags;
   7571             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
   7572             final int N = packageProviders.size();
   7573             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
   7574                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
   7575 
   7576             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
   7577             for (int i = 0; i < N; ++i) {
   7578                 intentFilters = packageProviders.get(i).intents;
   7579                 if (intentFilters != null && intentFilters.size() > 0) {
   7580                     PackageParser.ProviderIntentInfo[] array =
   7581                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
   7582                     intentFilters.toArray(array);
   7583                     listCut.add(array);
   7584                 }
   7585             }
   7586             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
   7587         }
   7588 
   7589         public final void addProvider(PackageParser.Provider p) {
   7590             if (mProviders.containsKey(p.getComponentName())) {
   7591                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
   7592                 return;
   7593             }
   7594 
   7595             mProviders.put(p.getComponentName(), p);
   7596             if (DEBUG_SHOW_INFO) {
   7597                 Log.v(TAG, "  "
   7598                         + (p.info.nonLocalizedLabel != null
   7599                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
   7600                 Log.v(TAG, "    Class=" + p.info.name);
   7601             }
   7602             final int NI = p.intents.size();
   7603             int j;
   7604             for (j = 0; j < NI; j++) {
   7605                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
   7606                 if (DEBUG_SHOW_INFO) {
   7607                     Log.v(TAG, "    IntentFilter:");
   7608                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   7609                 }
   7610                 if (!intent.debugCheck()) {
   7611                     Log.w(TAG, "==> For Provider " + p.info.name);
   7612                 }
   7613                 addFilter(intent);
   7614             }
   7615         }
   7616 
   7617         public final void removeProvider(PackageParser.Provider p) {
   7618             mProviders.remove(p.getComponentName());
   7619             if (DEBUG_SHOW_INFO) {
   7620                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
   7621                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
   7622                 Log.v(TAG, "    Class=" + p.info.name);
   7623             }
   7624             final int NI = p.intents.size();
   7625             int j;
   7626             for (j = 0; j < NI; j++) {
   7627                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
   7628                 if (DEBUG_SHOW_INFO) {
   7629                     Log.v(TAG, "    IntentFilter:");
   7630                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
   7631                 }
   7632                 removeFilter(intent);
   7633             }
   7634         }
   7635 
   7636         @Override
   7637         protected boolean allowFilterResult(
   7638                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
   7639             ProviderInfo filterPi = filter.provider.info;
   7640             for (int i = dest.size() - 1; i >= 0; i--) {
   7641                 ProviderInfo destPi = dest.get(i).providerInfo;
   7642                 if (destPi.name == filterPi.name
   7643                         && destPi.packageName == filterPi.packageName) {
   7644                     return false;
   7645                 }
   7646             }
   7647             return true;
   7648         }
   7649 
   7650         @Override
   7651         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
   7652             return new PackageParser.ProviderIntentInfo[size];
   7653         }
   7654 
   7655         @Override
   7656         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
   7657             if (!sUserManager.exists(userId))
   7658                 return true;
   7659             PackageParser.Package p = filter.provider.owner;
   7660             if (p != null) {
   7661                 PackageSetting ps = (PackageSetting) p.mExtras;
   7662                 if (ps != null) {
   7663                     // System apps are never considered stopped for purposes of
   7664                     // filtering, because there may be no way for the user to
   7665                     // actually re-launch them.
   7666                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
   7667                             && ps.getStopped(userId);
   7668                 }
   7669             }
   7670             return false;
   7671         }
   7672 
   7673         @Override
   7674         protected boolean isPackageForFilter(String packageName,
   7675                 PackageParser.ProviderIntentInfo info) {
   7676             return packageName.equals(info.provider.owner.packageName);
   7677         }
   7678 
   7679         @Override
   7680         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
   7681                 int match, int userId) {
   7682             if (!sUserManager.exists(userId))
   7683                 return null;
   7684             final PackageParser.ProviderIntentInfo info = filter;
   7685             if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
   7686                 return null;
   7687             }
   7688             final PackageParser.Provider provider = info.provider;
   7689             if (mSafeMode && (provider.info.applicationInfo.flags
   7690                     & ApplicationInfo.FLAG_SYSTEM) == 0) {
   7691                 return null;
   7692             }
   7693             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
   7694             if (ps == null) {
   7695                 return null;
   7696             }
   7697             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
   7698                     ps.readUserState(userId), userId);
   7699             if (pi == null) {
   7700                 return null;
   7701             }
   7702             final ResolveInfo res = new ResolveInfo();
   7703             res.providerInfo = pi;
   7704             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
   7705                 res.filter = filter;
   7706             }
   7707             res.priority = info.getPriority();
   7708             res.preferredOrder = provider.owner.mPreferredOrder;
   7709             res.match = match;
   7710             res.isDefault = info.hasDefault;
   7711             res.labelRes = info.labelRes;
   7712             res.nonLocalizedLabel = info.nonLocalizedLabel;
   7713             res.icon = info.icon;
   7714             res.system = isSystemApp(res.providerInfo.applicationInfo);
   7715             return res;
   7716         }
   7717 
   7718         @Override
   7719         protected void sortResults(List<ResolveInfo> results) {
   7720             Collections.sort(results, mResolvePrioritySorter);
   7721         }
   7722 
   7723         @Override
   7724         protected void dumpFilter(PrintWriter out, String prefix,
   7725                 PackageParser.ProviderIntentInfo filter) {
   7726             out.print(prefix);
   7727             out.print(
   7728                     Integer.toHexString(System.identityHashCode(filter.provider)));
   7729             out.print(' ');
   7730             filter.provider.printComponentShortName(out);
   7731             out.print(" filter ");
   7732             out.println(Integer.toHexString(System.identityHashCode(filter)));
   7733         }
   7734 
   7735         private final HashMap<ComponentName, PackageParser.Provider> mProviders
   7736                 = new HashMap<ComponentName, PackageParser.Provider>();
   7737         private int mFlags;
   7738     };
   7739 
   7740     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
   7741             new Comparator<ResolveInfo>() {
   7742         public int compare(ResolveInfo r1, ResolveInfo r2) {
   7743             int v1 = r1.priority;
   7744             int v2 = r2.priority;
   7745             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
   7746             if (v1 != v2) {
   7747                 return (v1 > v2) ? -1 : 1;
   7748             }
   7749             v1 = r1.preferredOrder;
   7750             v2 = r2.preferredOrder;
   7751             if (v1 != v2) {
   7752                 return (v1 > v2) ? -1 : 1;
   7753             }
   7754             if (r1.isDefault != r2.isDefault) {
   7755                 return r1.isDefault ? -1 : 1;
   7756             }
   7757             v1 = r1.match;
   7758             v2 = r2.match;
   7759             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
   7760             if (v1 != v2) {
   7761                 return (v1 > v2) ? -1 : 1;
   7762             }
   7763             if (r1.system != r2.system) {
   7764                 return r1.system ? -1 : 1;
   7765             }
   7766             return 0;
   7767         }
   7768     };
   7769 
   7770     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
   7771             new Comparator<ProviderInfo>() {
   7772         public int compare(ProviderInfo p1, ProviderInfo p2) {
   7773             final int v1 = p1.initOrder;
   7774             final int v2 = p2.initOrder;
   7775             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
   7776         }
   7777     };
   7778 
   7779     static final void sendPackageBroadcast(String action, String pkg,
   7780             Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
   7781             int[] userIds) {
   7782         IActivityManager am = ActivityManagerNative.getDefault();
   7783         if (am != null) {
   7784             try {
   7785                 if (userIds == null) {
   7786                     userIds = am.getRunningUserIds();
   7787                 }
   7788                 for (int id : userIds) {
   7789                     final Intent intent = new Intent(action,
   7790                             pkg != null ? Uri.fromParts("package", pkg, null) : null);
   7791                     if (extras != null) {
   7792                         intent.putExtras(extras);
   7793                     }
   7794                     if (targetPkg != null) {
   7795                         intent.setPackage(targetPkg);
   7796                     }
   7797                     // Modify the UID when posting to other users
   7798                     int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
   7799                     if (uid > 0 && UserHandle.getUserId(uid) != id) {
   7800                         uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
   7801                         intent.putExtra(Intent.EXTRA_UID, uid);
   7802                     }
   7803                     intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
   7804                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
   7805                     if (DEBUG_BROADCASTS) {
   7806                         RuntimeException here = new RuntimeException("here");
   7807                         here.fillInStackTrace();
   7808                         Slog.d(TAG, "Sending to user " + id + ": "
   7809                                 + intent.toShortString(false, true, false, false)
   7810                                 + " " + intent.getExtras(), here);
   7811                     }
   7812                     am.broadcastIntent(null, intent, null, finishedReceiver,
   7813                             0, null, null, null, android.app.AppOpsManager.OP_NONE,
   7814                             finishedReceiver != null, false, id);
   7815                 }
   7816             } catch (RemoteException ex) {
   7817             }
   7818         }
   7819     }
   7820 
   7821     /**
   7822      * Check if the external storage media is available. This is true if there
   7823      * is a mounted external storage medium or if the external storage is
   7824      * emulated.
   7825      */
   7826     private boolean isExternalMediaAvailable() {
   7827         return mMediaMounted || Environment.isExternalStorageEmulated();
   7828     }
   7829 
   7830     @Override
   7831     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
   7832         // writer
   7833         synchronized (mPackages) {
   7834             if (!isExternalMediaAvailable()) {
   7835                 // If the external storage is no longer mounted at this point,
   7836                 // the caller may not have been able to delete all of this
   7837                 // packages files and can not delete any more.  Bail.
   7838                 return null;
   7839             }
   7840             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
   7841             if (lastPackage != null) {
   7842                 pkgs.remove(lastPackage);
   7843             }
   7844             if (pkgs.size() > 0) {
   7845                 return pkgs.get(0);
   7846             }
   7847         }
   7848         return null;
   7849     }
   7850 
   7851     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
   7852         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
   7853                 userId, andCode ? 1 : 0, packageName);
   7854         if (mSystemReady) {
   7855             msg.sendToTarget();
   7856         } else {
   7857             if (mPostSystemReadyMessages == null) {
   7858                 mPostSystemReadyMessages = new ArrayList<>();
   7859             }
   7860             mPostSystemReadyMessages.add(msg);
   7861         }
   7862     }
   7863 
   7864     void startCleaningPackages() {
   7865         // reader
   7866         synchronized (mPackages) {
   7867             if (!isExternalMediaAvailable()) {
   7868                 return;
   7869             }
   7870             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
   7871                 return;
   7872             }
   7873         }
   7874         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
   7875         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
   7876         IActivityManager am = ActivityManagerNative.getDefault();
   7877         if (am != null) {
   7878             try {
   7879                 am.startService(null, intent, null, UserHandle.USER_OWNER);
   7880             } catch (RemoteException e) {
   7881             }
   7882         }
   7883     }
   7884 
   7885     @Override
   7886     public void installPackage(String originPath, IPackageInstallObserver2 observer,
   7887             int installFlags, String installerPackageName, VerificationParams verificationParams,
   7888             String packageAbiOverride) {
   7889         installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
   7890                 packageAbiOverride, UserHandle.getCallingUserId());
   7891     }
   7892 
   7893     @Override
   7894     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
   7895             int installFlags, String installerPackageName, VerificationParams verificationParams,
   7896             String packageAbiOverride, int userId) {
   7897         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
   7898 
   7899         final int callingUid = Binder.getCallingUid();
   7900         enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
   7901 
   7902         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
   7903             try {
   7904                 if (observer != null) {
   7905                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
   7906                 }
   7907             } catch (RemoteException re) {
   7908             }
   7909             return;
   7910         }
   7911 
   7912         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
   7913             installFlags |= PackageManager.INSTALL_FROM_ADB;
   7914 
   7915         } else {
   7916             // Caller holds INSTALL_PACKAGES permission, so we're less strict
   7917             // about installerPackageName.
   7918 
   7919             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
   7920             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
   7921         }
   7922 
   7923         UserHandle user;
   7924         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
   7925             user = UserHandle.ALL;
   7926         } else {
   7927             user = new UserHandle(userId);
   7928         }
   7929 
   7930         verificationParams.setInstallerUid(callingUid);
   7931 
   7932         final File originFile = new File(originPath);
   7933         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
   7934 
   7935         final Message msg = mHandler.obtainMessage(INIT_COPY);
   7936         msg.obj = new InstallParams(origin, observer, installFlags,
   7937                 installerPackageName, verificationParams, user, packageAbiOverride);
   7938         mHandler.sendMessage(msg);
   7939     }
   7940 
   7941     void installStage(String packageName, File stagedDir, String stagedCid,
   7942             IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
   7943             String installerPackageName, int installerUid, UserHandle user) {
   7944         final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
   7945                 params.referrerUri, installerUid, null);
   7946 
   7947         final OriginInfo origin;
   7948         if (stagedDir != null) {
   7949             origin = OriginInfo.fromStagedFile(stagedDir);
   7950         } else {
   7951             origin = OriginInfo.fromStagedContainer(stagedCid);
   7952         }
   7953 
   7954         final Message msg = mHandler.obtainMessage(INIT_COPY);
   7955         msg.obj = new InstallParams(origin, observer, params.installFlags,
   7956                 installerPackageName, verifParams, user, params.abiOverride);
   7957         mHandler.sendMessage(msg);
   7958     }
   7959 
   7960     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
   7961         Bundle extras = new Bundle(1);
   7962         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
   7963 
   7964         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
   7965                 packageName, extras, null, null, new int[] {userId});
   7966         try {
   7967             IActivityManager am = ActivityManagerNative.getDefault();
   7968             final boolean isSystem =
   7969                     isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
   7970             if (isSystem && am.isUserRunning(userId, false)) {
   7971                 // The just-installed/enabled app is bundled on the system, so presumed
   7972                 // to be able to run automatically without needing an explicit launch.
   7973                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
   7974                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
   7975                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
   7976                         .setPackage(packageName);
   7977                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
   7978                         android.app.AppOpsManager.OP_NONE, false, false, userId);
   7979             }
   7980         } catch (RemoteException e) {
   7981             // shouldn't happen
   7982             Slog.w(TAG, "Unable to bootstrap installed package", e);
   7983         }
   7984     }
   7985 
   7986     @Override
   7987     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
   7988             int userId) {
   7989         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   7990         PackageSetting pkgSetting;
   7991         final int uid = Binder.getCallingUid();
   7992         enforceCrossUserPermission(uid, userId, true, true,
   7993                 "setApplicationHiddenSetting for user " + userId);
   7994 
   7995         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
   7996             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
   7997             return false;
   7998         }
   7999 
   8000         long callingId = Binder.clearCallingIdentity();
   8001         try {
   8002             boolean sendAdded = false;
   8003             boolean sendRemoved = false;
   8004             // writer
   8005             synchronized (mPackages) {
   8006                 pkgSetting = mSettings.mPackages.get(packageName);
   8007                 if (pkgSetting == null) {
   8008                     return false;
   8009                 }
   8010                 if (pkgSetting.getHidden(userId) != hidden) {
   8011                     pkgSetting.setHidden(hidden, userId);
   8012                     mSettings.writePackageRestrictionsLPr(userId);
   8013                     if (hidden) {
   8014                         sendRemoved = true;
   8015                     } else {
   8016                         sendAdded = true;
   8017                     }
   8018                 }
   8019             }
   8020             if (sendAdded) {
   8021                 sendPackageAddedForUser(packageName, pkgSetting, userId);
   8022                 return true;
   8023             }
   8024             if (sendRemoved) {
   8025                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
   8026                         "hiding pkg");
   8027                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
   8028             }
   8029         } finally {
   8030             Binder.restoreCallingIdentity(callingId);
   8031         }
   8032         return false;
   8033     }
   8034 
   8035     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
   8036             int userId) {
   8037         final PackageRemovedInfo info = new PackageRemovedInfo();
   8038         info.removedPackage = packageName;
   8039         info.removedUsers = new int[] {userId};
   8040         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
   8041         info.sendBroadcast(false, false, false);
   8042     }
   8043 
   8044     /**
   8045      * Returns true if application is not found or there was an error. Otherwise it returns
   8046      * the hidden state of the package for the given user.
   8047      */
   8048     @Override
   8049     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
   8050         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
   8051         enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
   8052                 false, "getApplicationHidden for user " + userId);
   8053         PackageSetting pkgSetting;
   8054         long callingId = Binder.clearCallingIdentity();
   8055         try {
   8056             // writer
   8057             synchronized (mPackages) {
   8058                 pkgSetting = mSettings.mPackages.get(packageName);
   8059                 if (pkgSetting == null) {
   8060                     return true;
   8061                 }
   8062                 return pkgSetting.getHidden(userId);
   8063             }
   8064         } finally {
   8065             Binder.restoreCallingIdentity(callingId);
   8066         }
   8067     }
   8068 
   8069     /**
   8070      * @hide
   8071      */
   8072     @Override
   8073     public int installExistingPackageAsUser(String packageName, int userId) {
   8074         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
   8075                 null);
   8076         PackageSetting pkgSetting;
   8077         final int uid = Binder.getCallingUid();
   8078         enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
   8079                 + userId);
   8080         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
   8081             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
   8082         }
   8083 
   8084         long callingId = Binder.clearCallingIdentity();
   8085         try {
   8086             boolean sendAdded = false;
   8087             Bundle extras = new Bundle(1);
   8088 
   8089             // writer
   8090             synchronized (mPackages) {
   8091                 pkgSetting = mSettings.mPackages.get(packageName);
   8092                 if (pkgSetting == null) {
   8093                     return PackageManager.INSTALL_FAILED_INVALID_URI;
   8094                 }
   8095                 if (!pkgSetting.getInstalled(userId)) {
   8096                     pkgSetting.setInstalled(true, userId);
   8097                     pkgSetting.setHidden(false, userId);
   8098                     mSettings.writePackageRestrictionsLPr(userId);
   8099                     sendAdded = true;
   8100                 }
   8101             }
   8102 
   8103             if (sendAdded) {
   8104                 sendPackageAddedForUser(packageName, pkgSetting, userId);
   8105             }
   8106         } finally {
   8107             Binder.restoreCallingIdentity(callingId);
   8108         }
   8109 
   8110         return PackageManager.INSTALL_SUCCEEDED;
   8111     }
   8112 
   8113     boolean isUserRestricted(int userId, String restrictionKey) {
   8114         Bundle restrictions = sUserManager.getUserRestrictions(userId);
   8115         if (restrictions.getBoolean(restrictionKey, false)) {
   8116             Log.w(TAG, "User is restricted: " + restrictionKey);
   8117             return true;
   8118         }
   8119         return false;
   8120     }
   8121 
   8122     @Override
   8123     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
   8124         mContext.enforceCallingOrSelfPermission(
   8125                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   8126                 "Only package verification agents can verify applications");
   8127 
   8128         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
   8129         final PackageVerificationResponse response = new PackageVerificationResponse(
   8130                 verificationCode, Binder.getCallingUid());
   8131         msg.arg1 = id;
   8132         msg.obj = response;
   8133         mHandler.sendMessage(msg);
   8134     }
   8135 
   8136     @Override
   8137     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
   8138             long millisecondsToDelay) {
   8139         mContext.enforceCallingOrSelfPermission(
   8140                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   8141                 "Only package verification agents can extend verification timeouts");
   8142 
   8143         final PackageVerificationState state = mPendingVerification.get(id);
   8144         final PackageVerificationResponse response = new PackageVerificationResponse(
   8145                 verificationCodeAtTimeout, Binder.getCallingUid());
   8146 
   8147         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
   8148             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
   8149         }
   8150         if (millisecondsToDelay < 0) {
   8151             millisecondsToDelay = 0;
   8152         }
   8153         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
   8154                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
   8155             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
   8156         }
   8157 
   8158         if ((state != null) && !state.timeoutExtended()) {
   8159             state.extendTimeout();
   8160 
   8161             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
   8162             msg.arg1 = id;
   8163             msg.obj = response;
   8164             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
   8165         }
   8166     }
   8167 
   8168     private void broadcastPackageVerified(int verificationId, Uri packageUri,
   8169             int verificationCode, UserHandle user) {
   8170         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
   8171         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
   8172         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   8173         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
   8174         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
   8175 
   8176         mContext.sendBroadcastAsUser(intent, user,
   8177                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
   8178     }
   8179 
   8180     private ComponentName matchComponentForVerifier(String packageName,
   8181             List<ResolveInfo> receivers) {
   8182         ActivityInfo targetReceiver = null;
   8183 
   8184         final int NR = receivers.size();
   8185         for (int i = 0; i < NR; i++) {
   8186             final ResolveInfo info = receivers.get(i);
   8187             if (info.activityInfo == null) {
   8188                 continue;
   8189             }
   8190 
   8191             if (packageName.equals(info.activityInfo.packageName)) {
   8192                 targetReceiver = info.activityInfo;
   8193                 break;
   8194             }
   8195         }
   8196 
   8197         if (targetReceiver == null) {
   8198             return null;
   8199         }
   8200 
   8201         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
   8202     }
   8203 
   8204     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
   8205             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
   8206         if (pkgInfo.verifiers.length == 0) {
   8207             return null;
   8208         }
   8209 
   8210         final int N = pkgInfo.verifiers.length;
   8211         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
   8212         for (int i = 0; i < N; i++) {
   8213             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
   8214 
   8215             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
   8216                     receivers);
   8217             if (comp == null) {
   8218                 continue;
   8219             }
   8220 
   8221             final int verifierUid = getUidForVerifier(verifierInfo);
   8222             if (verifierUid == -1) {
   8223                 continue;
   8224             }
   8225 
   8226             if (DEBUG_VERIFY) {
   8227                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
   8228                         + " with the correct signature");
   8229             }
   8230             sufficientVerifiers.add(comp);
   8231             verificationState.addSufficientVerifier(verifierUid);
   8232         }
   8233 
   8234         return sufficientVerifiers;
   8235     }
   8236 
   8237     private int getUidForVerifier(VerifierInfo verifierInfo) {
   8238         synchronized (mPackages) {
   8239             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
   8240             if (pkg == null) {
   8241                 return -1;
   8242             } else if (pkg.mSignatures.length != 1) {
   8243                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
   8244                         + " has more than one signature; ignoring");
   8245                 return -1;
   8246             }
   8247 
   8248             /*
   8249              * If the public key of the package's signature does not match
   8250              * our expected public key, then this is a different package and
   8251              * we should skip.
   8252              */
   8253 
   8254             final byte[] expectedPublicKey;
   8255             try {
   8256                 final Signature verifierSig = pkg.mSignatures[0];
   8257                 final PublicKey publicKey = verifierSig.getPublicKey();
   8258                 expectedPublicKey = publicKey.getEncoded();
   8259             } catch (CertificateException e) {
   8260                 return -1;
   8261             }
   8262 
   8263             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
   8264 
   8265             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
   8266                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
   8267                         + " does not have the expected public key; ignoring");
   8268                 return -1;
   8269             }
   8270 
   8271             return pkg.applicationInfo.uid;
   8272         }
   8273     }
   8274 
   8275     @Override
   8276     public void finishPackageInstall(int token) {
   8277         enforceSystemOrRoot("Only the system is allowed to finish installs");
   8278 
   8279         if (DEBUG_INSTALL) {
   8280             Slog.v(TAG, "BM finishing package install for " + token);
   8281         }
   8282 
   8283         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
   8284         mHandler.sendMessage(msg);
   8285     }
   8286 
   8287     /**
   8288      * Get the verification agent timeout.
   8289      *
   8290      * @return verification timeout in milliseconds
   8291      */
   8292     private long getVerificationTimeout() {
   8293         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
   8294                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
   8295                 DEFAULT_VERIFICATION_TIMEOUT);
   8296     }
   8297 
   8298     /**
   8299      * Get the default verification agent response code.
   8300      *
   8301      * @return default verification response code
   8302      */
   8303     private int getDefaultVerificationResponse() {
   8304         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   8305                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
   8306                 DEFAULT_VERIFICATION_RESPONSE);
   8307     }
   8308 
   8309     /**
   8310      * Check whether or not package verification has been enabled.
   8311      *
   8312      * @return true if verification should be performed
   8313      */
   8314     private boolean isVerificationEnabled(int userId, int installFlags) {
   8315         if (!DEFAULT_VERIFY_ENABLE) {
   8316             return false;
   8317         }
   8318 
   8319         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
   8320 
   8321         // Check if installing from ADB
   8322         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
   8323             // Do not run verification in a test harness environment
   8324             if (ActivityManager.isRunningInTestHarness()) {
   8325                 return false;
   8326             }
   8327             if (ensureVerifyAppsEnabled) {
   8328                 return true;
   8329             }
   8330             // Check if the developer does not want package verification for ADB installs
   8331             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   8332                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
   8333                 return false;
   8334             }
   8335         }
   8336 
   8337         if (ensureVerifyAppsEnabled) {
   8338             return true;
   8339         }
   8340 
   8341         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   8342                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
   8343     }
   8344 
   8345     /**
   8346      * Get the "allow unknown sources" setting.
   8347      *
   8348      * @return the current "allow unknown sources" setting
   8349      */
   8350     private int getUnknownSourcesSettings() {
   8351         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   8352                 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
   8353                 -1);
   8354     }
   8355 
   8356     @Override
   8357     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
   8358         final int uid = Binder.getCallingUid();
   8359         // writer
   8360         synchronized (mPackages) {
   8361             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
   8362             if (targetPackageSetting == null) {
   8363                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
   8364             }
   8365 
   8366             PackageSetting installerPackageSetting;
   8367             if (installerPackageName != null) {
   8368                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
   8369                 if (installerPackageSetting == null) {
   8370                     throw new IllegalArgumentException("Unknown installer package: "
   8371                             + installerPackageName);
   8372                 }
   8373             } else {
   8374                 installerPackageSetting = null;
   8375             }
   8376 
   8377             Signature[] callerSignature;
   8378             Object obj = mSettings.getUserIdLPr(uid);
   8379             if (obj != null) {
   8380                 if (obj instanceof SharedUserSetting) {
   8381                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
   8382                 } else if (obj instanceof PackageSetting) {
   8383                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
   8384                 } else {
   8385                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
   8386                 }
   8387             } else {
   8388                 throw new SecurityException("Unknown calling uid " + uid);
   8389             }
   8390 
   8391             // Verify: can't set installerPackageName to a package that is
   8392             // not signed with the same cert as the caller.
   8393             if (installerPackageSetting != null) {
   8394                 if (compareSignatures(callerSignature,
   8395                         installerPackageSetting.signatures.mSignatures)
   8396                         != PackageManager.SIGNATURE_MATCH) {
   8397                     throw new SecurityException(
   8398                             "Caller does not have same cert as new installer package "
   8399                             + installerPackageName);
   8400                 }
   8401             }
   8402 
   8403             // Verify: if target already has an installer package, it must
   8404             // be signed with the same cert as the caller.
   8405             if (targetPackageSetting.installerPackageName != null) {
   8406                 PackageSetting setting = mSettings.mPackages.get(
   8407                         targetPackageSetting.installerPackageName);
   8408                 // If the currently set package isn't valid, then it's always
   8409                 // okay to change it.
   8410                 if (setting != null) {
   8411                     if (compareSignatures(callerSignature,
   8412                             setting.signatures.mSignatures)
   8413                             != PackageManager.SIGNATURE_MATCH) {
   8414                         throw new SecurityException(
   8415                                 "Caller does not have same cert as old installer package "
   8416                                 + targetPackageSetting.installerPackageName);
   8417                     }
   8418                 }
   8419             }
   8420 
   8421             // Okay!
   8422             targetPackageSetting.installerPackageName = installerPackageName;
   8423             scheduleWriteSettingsLocked();
   8424         }
   8425     }
   8426 
   8427     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
   8428         // Queue up an async operation since the package installation may take a little while.
   8429         mHandler.post(new Runnable() {
   8430             public void run() {
   8431                 mHandler.removeCallbacks(this);
   8432                  // Result object to be returned
   8433                 PackageInstalledInfo res = new PackageInstalledInfo();
   8434                 res.returnCode = currentStatus;
   8435                 res.uid = -1;
   8436                 res.pkg = null;
   8437                 res.removedInfo = new PackageRemovedInfo();
   8438                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   8439                     args.doPreInstall(res.returnCode);
   8440                     synchronized (mInstallLock) {
   8441                         installPackageLI(args, res);
   8442                     }
   8443                     args.doPostInstall(res.returnCode, res.uid);
   8444                 }
   8445 
   8446                 // A restore should be performed at this point if (a) the install
   8447                 // succeeded, (b) the operation is not an update, and (c) the new
   8448                 // package has not opted out of backup participation.
   8449                 final boolean update = res.removedInfo.removedPackage != null;
   8450                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
   8451                 boolean doRestore = !update
   8452                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
   8453 
   8454                 // Set up the post-install work request bookkeeping.  This will be used
   8455                 // and cleaned up by the post-install event handling regardless of whether
   8456                 // there's a restore pass performed.  Token values are >= 1.
   8457                 int token;
   8458                 if (mNextInstallToken < 0) mNextInstallToken = 1;
   8459                 token = mNextInstallToken++;
   8460 
   8461                 PostInstallData data = new PostInstallData(args, res);
   8462                 mRunningInstalls.put(token, data);
   8463                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
   8464 
   8465                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
   8466                     // Pass responsibility to the Backup Manager.  It will perform a
   8467                     // restore if appropriate, then pass responsibility back to the
   8468                     // Package Manager to run the post-install observer callbacks
   8469                     // and broadcasts.
   8470                     IBackupManager bm = IBackupManager.Stub.asInterface(
   8471                             ServiceManager.getService(Context.BACKUP_SERVICE));
   8472                     if (bm != null) {
   8473                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
   8474                                 + " to BM for possible restore");
   8475                         try {
   8476                             bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
   8477                         } catch (RemoteException e) {
   8478                             // can't happen; the backup manager is local
   8479                         } catch (Exception e) {
   8480                             Slog.e(TAG, "Exception trying to enqueue restore", e);
   8481                             doRestore = false;
   8482                         }
   8483                     } else {
   8484                         Slog.e(TAG, "Backup Manager not found!");
   8485                         doRestore = false;
   8486                     }
   8487                 }
   8488 
   8489                 if (!doRestore) {
   8490                     // No restore possible, or the Backup Manager was mysteriously not
   8491                     // available -- just fire the post-install work request directly.
   8492                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
   8493                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
   8494                     mHandler.sendMessage(msg);
   8495                 }
   8496             }
   8497         });
   8498     }
   8499 
   8500     private abstract class HandlerParams {
   8501         private static final int MAX_RETRIES = 4;
   8502 
   8503         /**
   8504          * Number of times startCopy() has been attempted and had a non-fatal
   8505          * error.
   8506          */
   8507         private int mRetries = 0;
   8508 
   8509         /** User handle for the user requesting the information or installation. */
   8510         private final UserHandle mUser;
   8511 
   8512         HandlerParams(UserHandle user) {
   8513             mUser = user;
   8514         }
   8515 
   8516         UserHandle getUser() {
   8517             return mUser;
   8518         }
   8519 
   8520         final boolean startCopy() {
   8521             boolean res;
   8522             try {
   8523                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
   8524 
   8525                 if (++mRetries > MAX_RETRIES) {
   8526                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
   8527                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
   8528                     handleServiceError();
   8529                     return false;
   8530                 } else {
   8531                     handleStartCopy();
   8532                     res = true;
   8533                 }
   8534             } catch (RemoteException e) {
   8535                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
   8536                 mHandler.sendEmptyMessage(MCS_RECONNECT);
   8537                 res = false;
   8538             }
   8539             handleReturnCode();
   8540             return res;
   8541         }
   8542 
   8543         final void serviceError() {
   8544             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
   8545             handleServiceError();
   8546             handleReturnCode();
   8547         }
   8548 
   8549         abstract void handleStartCopy() throws RemoteException;
   8550         abstract void handleServiceError();
   8551         abstract void handleReturnCode();
   8552     }
   8553 
   8554     class MeasureParams extends HandlerParams {
   8555         private final PackageStats mStats;
   8556         private boolean mSuccess;
   8557 
   8558         private final IPackageStatsObserver mObserver;
   8559 
   8560         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
   8561             super(new UserHandle(stats.userHandle));
   8562             mObserver = observer;
   8563             mStats = stats;
   8564         }
   8565 
   8566         @Override
   8567         public String toString() {
   8568             return "MeasureParams{"
   8569                 + Integer.toHexString(System.identityHashCode(this))
   8570                 + " " + mStats.packageName + "}";
   8571         }
   8572 
   8573         @Override
   8574         void handleStartCopy() throws RemoteException {
   8575             synchronized (mInstallLock) {
   8576                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
   8577             }
   8578 
   8579             if (mSuccess) {
   8580                 final boolean mounted;
   8581                 if (Environment.isExternalStorageEmulated()) {
   8582                     mounted = true;
   8583                 } else {
   8584                     final String status = Environment.getExternalStorageState();
   8585                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
   8586                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
   8587                 }
   8588 
   8589                 if (mounted) {
   8590                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
   8591 
   8592                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
   8593                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
   8594 
   8595                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
   8596                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
   8597 
   8598                     // Always subtract cache size, since it's a subdirectory
   8599                     mStats.externalDataSize -= mStats.externalCacheSize;
   8600 
   8601                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
   8602                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
   8603 
   8604                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
   8605                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
   8606                 }
   8607             }
   8608         }
   8609 
   8610         @Override
   8611         void handleReturnCode() {
   8612             if (mObserver != null) {
   8613                 try {
   8614                     mObserver.onGetStatsCompleted(mStats, mSuccess);
   8615                 } catch (RemoteException e) {
   8616                     Slog.i(TAG, "Observer no longer exists.");
   8617                 }
   8618             }
   8619         }
   8620 
   8621         @Override
   8622         void handleServiceError() {
   8623             Slog.e(TAG, "Could not measure application " + mStats.packageName
   8624                             + " external storage");
   8625         }
   8626     }
   8627 
   8628     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
   8629             throws RemoteException {
   8630         long result = 0;
   8631         for (File path : paths) {
   8632             result += mcs.calculateDirectorySize(path.getAbsolutePath());
   8633         }
   8634         return result;
   8635     }
   8636 
   8637     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
   8638         for (File path : paths) {
   8639             try {
   8640                 mcs.clearDirectory(path.getAbsolutePath());
   8641             } catch (RemoteException e) {
   8642             }
   8643         }
   8644     }
   8645 
   8646     static class OriginInfo {
   8647         /**
   8648          * Location where install is coming from, before it has been
   8649          * copied/renamed into place. This could be a single monolithic APK
   8650          * file, or a cluster directory. This location may be untrusted.
   8651          */
   8652         final File file;
   8653         final String cid;
   8654 
   8655         /**
   8656          * Flag indicating that {@link #file} or {@link #cid} has already been
   8657          * staged, meaning downstream users don't need to defensively copy the
   8658          * contents.
   8659          */
   8660         final boolean staged;
   8661 
   8662         /**
   8663          * Flag indicating that {@link #file} or {@link #cid} is an already
   8664          * installed app that is being moved.
   8665          */
   8666         final boolean existing;
   8667 
   8668         final String resolvedPath;
   8669         final File resolvedFile;
   8670 
   8671         static OriginInfo fromNothing() {
   8672             return new OriginInfo(null, null, false, false);
   8673         }
   8674 
   8675         static OriginInfo fromUntrustedFile(File file) {
   8676             return new OriginInfo(file, null, false, false);
   8677         }
   8678 
   8679         static OriginInfo fromExistingFile(File file) {
   8680             return new OriginInfo(file, null, false, true);
   8681         }
   8682 
   8683         static OriginInfo fromStagedFile(File file) {
   8684             return new OriginInfo(file, null, true, false);
   8685         }
   8686 
   8687         static OriginInfo fromStagedContainer(String cid) {
   8688             return new OriginInfo(null, cid, true, false);
   8689         }
   8690 
   8691         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
   8692             this.file = file;
   8693             this.cid = cid;
   8694             this.staged = staged;
   8695             this.existing = existing;
   8696 
   8697             if (cid != null) {
   8698                 resolvedPath = PackageHelper.getSdDir(cid);
   8699                 resolvedFile = new File(resolvedPath);
   8700             } else if (file != null) {
   8701                 resolvedPath = file.getAbsolutePath();
   8702                 resolvedFile = file;
   8703             } else {
   8704                 resolvedPath = null;
   8705                 resolvedFile = null;
   8706             }
   8707         }
   8708     }
   8709 
   8710     class InstallParams extends HandlerParams {
   8711         final OriginInfo origin;
   8712         final IPackageInstallObserver2 observer;
   8713         int installFlags;
   8714         final String installerPackageName;
   8715         final VerificationParams verificationParams;
   8716         private InstallArgs mArgs;
   8717         private int mRet;
   8718         final String packageAbiOverride;
   8719 
   8720         InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
   8721                 String installerPackageName, VerificationParams verificationParams, UserHandle user,
   8722                 String packageAbiOverride) {
   8723             super(user);
   8724             this.origin = origin;
   8725             this.observer = observer;
   8726             this.installFlags = installFlags;
   8727             this.installerPackageName = installerPackageName;
   8728             this.verificationParams = verificationParams;
   8729             this.packageAbiOverride = packageAbiOverride;
   8730         }
   8731 
   8732         @Override
   8733         public String toString() {
   8734             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
   8735                     + " file=" + origin.file + " cid=" + origin.cid + "}";
   8736         }
   8737 
   8738         public ManifestDigest getManifestDigest() {
   8739             if (verificationParams == null) {
   8740                 return null;
   8741             }
   8742             return verificationParams.getManifestDigest();
   8743         }
   8744 
   8745         private int installLocationPolicy(PackageInfoLite pkgLite) {
   8746             String packageName = pkgLite.packageName;
   8747             int installLocation = pkgLite.installLocation;
   8748             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
   8749             // reader
   8750             synchronized (mPackages) {
   8751                 PackageParser.Package pkg = mPackages.get(packageName);
   8752                 if (pkg != null) {
   8753                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
   8754                         // Check for downgrading.
   8755                         if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
   8756                             if (pkgLite.versionCode < pkg.mVersionCode) {
   8757                                 Slog.w(TAG, "Can't install update of " + packageName
   8758                                         + " update version " + pkgLite.versionCode
   8759                                         + " is older than installed version "
   8760                                         + pkg.mVersionCode);
   8761                                 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
   8762                             }
   8763                         }
   8764                         // Check for updated system application.
   8765                         if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   8766                             if (onSd) {
   8767                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
   8768                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
   8769                             }
   8770                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
   8771                         } else {
   8772                             if (onSd) {
   8773                                 // Install flag overrides everything.
   8774                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
   8775                             }
   8776                             // If current upgrade specifies particular preference
   8777                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
   8778                                 // Application explicitly specified internal.
   8779                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
   8780                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
   8781                                 // App explictly prefers external. Let policy decide
   8782                             } else {
   8783                                 // Prefer previous location
   8784                                 if (isExternal(pkg)) {
   8785                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
   8786                                 }
   8787                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
   8788                             }
   8789                         }
   8790                     } else {
   8791                         // Invalid install. Return error code
   8792                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
   8793                     }
   8794                 }
   8795             }
   8796             // All the special cases have been taken care of.
   8797             // Return result based on recommended install location.
   8798             if (onSd) {
   8799                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
   8800             }
   8801             return pkgLite.recommendedInstallLocation;
   8802         }
   8803 
   8804         /*
   8805          * Invoke remote method to get package information and install
   8806          * location values. Override install location based on default
   8807          * policy if needed and then create install arguments based
   8808          * on the install location.
   8809          */
   8810         public void handleStartCopy() throws RemoteException {
   8811             int ret = PackageManager.INSTALL_SUCCEEDED;
   8812 
   8813             // If we're already staged, we've firmly committed to an install location
   8814             if (origin.staged) {
   8815                 if (origin.file != null) {
   8816                     installFlags |= PackageManager.INSTALL_INTERNAL;
   8817                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
   8818                 } else if (origin.cid != null) {
   8819                     installFlags |= PackageManager.INSTALL_EXTERNAL;
   8820                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
   8821                 } else {
   8822                     throw new IllegalStateException("Invalid stage location");
   8823                 }
   8824             }
   8825 
   8826             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
   8827             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
   8828 
   8829             PackageInfoLite pkgLite = null;
   8830 
   8831             if (onInt && onSd) {
   8832                 // Check if both bits are set.
   8833                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
   8834                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
   8835             } else {
   8836                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
   8837                         packageAbiOverride);
   8838 
   8839                 /*
   8840                  * If we have too little free space, try to free cache
   8841                  * before giving up.
   8842                  */
   8843                 if (!origin.staged && pkgLite.recommendedInstallLocation
   8844                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
   8845                     // TODO: focus freeing disk space on the target device
   8846                     final StorageManager storage = StorageManager.from(mContext);
   8847                     final long lowThreshold = storage.getStorageLowBytes(
   8848                             Environment.getDataDirectory());
   8849 
   8850                     final long sizeBytes = mContainerService.calculateInstalledSize(
   8851                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
   8852 
   8853                     if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
   8854                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
   8855                                 installFlags, packageAbiOverride);
   8856                     }
   8857 
   8858                     /*
   8859                      * The cache free must have deleted the file we
   8860                      * downloaded to install.
   8861                      *
   8862                      * TODO: fix the "freeCache" call to not delete
   8863                      *       the file we care about.
   8864                      */
   8865                     if (pkgLite.recommendedInstallLocation
   8866                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
   8867                         pkgLite.recommendedInstallLocation
   8868                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
   8869                     }
   8870                 }
   8871             }
   8872 
   8873             if (ret == PackageManager.INSTALL_SUCCEEDED) {
   8874                 int loc = pkgLite.recommendedInstallLocation;
   8875                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
   8876                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
   8877                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
   8878                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
   8879                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
   8880                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
   8881                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
   8882                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
   8883                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
   8884                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
   8885                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
   8886                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
   8887                 } else {
   8888                     // Override with defaults if needed.
   8889                     loc = installLocationPolicy(pkgLite);
   8890                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
   8891                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
   8892                     } else if (!onSd && !onInt) {
   8893                         // Override install location with flags
   8894                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
   8895                             // Set the flag to install on external media.
   8896                             installFlags |= PackageManager.INSTALL_EXTERNAL;
   8897                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
   8898                         } else {
   8899                             // Make sure the flag for installing on external
   8900                             // media is unset
   8901                             installFlags |= PackageManager.INSTALL_INTERNAL;
   8902                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
   8903                         }
   8904                     }
   8905                 }
   8906             }
   8907 
   8908             final InstallArgs args = createInstallArgs(this);
   8909             mArgs = args;
   8910 
   8911             if (ret == PackageManager.INSTALL_SUCCEEDED) {
   8912                  /*
   8913                  * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
   8914                  * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
   8915                  */
   8916                 int userIdentifier = getUser().getIdentifier();
   8917                 if (userIdentifier == UserHandle.USER_ALL
   8918                         && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
   8919                     userIdentifier = UserHandle.USER_OWNER;
   8920                 }
   8921 
   8922                 /*
   8923                  * Determine if we have any installed package verifiers. If we
   8924                  * do, then we'll defer to them to verify the packages.
   8925                  */
   8926                 final int requiredUid = mRequiredVerifierPackage == null ? -1
   8927                         : getPackageUid(mRequiredVerifierPackage, userIdentifier);
   8928                 if (!origin.existing && requiredUid != -1
   8929                         && isVerificationEnabled(userIdentifier, installFlags)) {
   8930                     final Intent verification = new Intent(
   8931                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
   8932                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
   8933                             PACKAGE_MIME_TYPE);
   8934                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   8935 
   8936                     final List<ResolveInfo> receivers = queryIntentReceivers(verification,
   8937                             PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
   8938                             0 /* TODO: Which userId? */);
   8939 
   8940                     if (DEBUG_VERIFY) {
   8941                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
   8942                                 + verification.toString() + " with " + pkgLite.verifiers.length
   8943                                 + " optional verifiers");
   8944                     }
   8945 
   8946                     final int verificationId = mPendingVerificationToken++;
   8947 
   8948                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
   8949 
   8950                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
   8951                             installerPackageName);
   8952 
   8953                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
   8954                             installFlags);
   8955 
   8956                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
   8957                             pkgLite.packageName);
   8958 
   8959                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
   8960                             pkgLite.versionCode);
   8961 
   8962                     if (verificationParams != null) {
   8963                         if (verificationParams.getVerificationURI() != null) {
   8964                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
   8965                                  verificationParams.getVerificationURI());
   8966                         }
   8967                         if (verificationParams.getOriginatingURI() != null) {
   8968                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
   8969                                   verificationParams.getOriginatingURI());
   8970                         }
   8971                         if (verificationParams.getReferrer() != null) {
   8972                             verification.putExtra(Intent.EXTRA_REFERRER,
   8973                                   verificationParams.getReferrer());
   8974                         }
   8975                         if (verificationParams.getOriginatingUid() >= 0) {
   8976                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
   8977                                   verificationParams.getOriginatingUid());
   8978                         }
   8979                         if (verificationParams.getInstallerUid() >= 0) {
   8980                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
   8981                                   verificationParams.getInstallerUid());
   8982                         }
   8983                     }
   8984 
   8985                     final PackageVerificationState verificationState = new PackageVerificationState(
   8986                             requiredUid, args);
   8987 
   8988                     mPendingVerification.append(verificationId, verificationState);
   8989 
   8990                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
   8991                             receivers, verificationState);
   8992 
   8993                     /*
   8994                      * If any sufficient verifiers were listed in the package
   8995                      * manifest, attempt to ask them.
   8996                      */
   8997                     if (sufficientVerifiers != null) {
   8998                         final int N = sufficientVerifiers.size();
   8999                         if (N == 0) {
   9000                             Slog.i(TAG, "Additional verifiers required, but none installed.");
   9001                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
   9002                         } else {
   9003                             for (int i = 0; i < N; i++) {
   9004                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
   9005 
   9006                                 final Intent sufficientIntent = new Intent(verification);
   9007                                 sufficientIntent.setComponent(verifierComponent);
   9008 
   9009                                 mContext.sendBroadcastAsUser(sufficientIntent, getUser());
   9010                             }
   9011                         }
   9012                     }
   9013 
   9014                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
   9015                             mRequiredVerifierPackage, receivers);
   9016                     if (ret == PackageManager.INSTALL_SUCCEEDED
   9017                             && mRequiredVerifierPackage != null) {
   9018                         /*
   9019                          * Send the intent to the required verification agent,
   9020                          * but only start the verification timeout after the
   9021                          * target BroadcastReceivers have run.
   9022                          */
   9023                         verification.setComponent(requiredVerifierComponent);
   9024                         mContext.sendOrderedBroadcastAsUser(verification, getUser(),
   9025                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   9026                                 new BroadcastReceiver() {
   9027                                     @Override
   9028                                     public void onReceive(Context context, Intent intent) {
   9029                                         final Message msg = mHandler
   9030                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
   9031                                         msg.arg1 = verificationId;
   9032                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
   9033                                     }
   9034                                 }, null, 0, null, null);
   9035 
   9036                         /*
   9037                          * We don't want the copy to proceed until verification
   9038                          * succeeds, so null out this field.
   9039                          */
   9040                         mArgs = null;
   9041                     }
   9042                 } else {
   9043                     /*
   9044                      * No package verification is enabled, so immediately start
   9045                      * the remote call to initiate copy using temporary file.
   9046                      */
   9047                     ret = args.copyApk(mContainerService, true);
   9048                 }
   9049             }
   9050 
   9051             mRet = ret;
   9052         }
   9053 
   9054         @Override
   9055         void handleReturnCode() {
   9056             // If mArgs is null, then MCS couldn't be reached. When it
   9057             // reconnects, it will try again to install. At that point, this
   9058             // will succeed.
   9059             if (mArgs != null) {
   9060                 processPendingInstall(mArgs, mRet);
   9061             }
   9062         }
   9063 
   9064         @Override
   9065         void handleServiceError() {
   9066             mArgs = createInstallArgs(this);
   9067             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   9068         }
   9069 
   9070         public boolean isForwardLocked() {
   9071             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
   9072         }
   9073     }
   9074 
   9075     /**
   9076      * Used during creation of InstallArgs
   9077      *
   9078      * @param installFlags package installation flags
   9079      * @return true if should be installed on external storage
   9080      */
   9081     private static boolean installOnSd(int installFlags) {
   9082         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
   9083             return false;
   9084         }
   9085         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
   9086             return true;
   9087         }
   9088         return false;
   9089     }
   9090 
   9091     /**
   9092      * Used during creation of InstallArgs
   9093      *
   9094      * @param installFlags package installation flags
   9095      * @return true if should be installed as forward locked
   9096      */
   9097     private static boolean installForwardLocked(int installFlags) {
   9098         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
   9099     }
   9100 
   9101     private InstallArgs createInstallArgs(InstallParams params) {
   9102         if (installOnSd(params.installFlags) || params.isForwardLocked()) {
   9103             return new AsecInstallArgs(params);
   9104         } else {
   9105             return new FileInstallArgs(params);
   9106         }
   9107     }
   9108 
   9109     /**
   9110      * Create args that describe an existing installed package. Typically used
   9111      * when cleaning up old installs, or used as a move source.
   9112      */
   9113     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
   9114             String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
   9115         final boolean isInAsec;
   9116         if (installOnSd(installFlags)) {
   9117             /* Apps on SD card are always in ASEC containers. */
   9118             isInAsec = true;
   9119         } else if (installForwardLocked(installFlags)
   9120                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
   9121             /*
   9122              * Forward-locked apps are only in ASEC containers if they're the
   9123              * new style
   9124              */
   9125             isInAsec = true;
   9126         } else {
   9127             isInAsec = false;
   9128         }
   9129 
   9130         if (isInAsec) {
   9131             return new AsecInstallArgs(codePath, instructionSets,
   9132                     installOnSd(installFlags), installForwardLocked(installFlags));
   9133         } else {
   9134             return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
   9135                     instructionSets);
   9136         }
   9137     }
   9138 
   9139     static abstract class InstallArgs {
   9140         /** @see InstallParams#origin */
   9141         final OriginInfo origin;
   9142 
   9143         final IPackageInstallObserver2 observer;
   9144         // Always refers to PackageManager flags only
   9145         final int installFlags;
   9146         final String installerPackageName;
   9147         final ManifestDigest manifestDigest;
   9148         final UserHandle user;
   9149         final String abiOverride;
   9150 
   9151         // The list of instruction sets supported by this app. This is currently
   9152         // only used during the rmdex() phase to clean up resources. We can get rid of this
   9153         // if we move dex files under the common app path.
   9154         /* nullable */ String[] instructionSets;
   9155 
   9156         InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
   9157                 String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
   9158                 String[] instructionSets, String abiOverride) {
   9159             this.origin = origin;
   9160             this.installFlags = installFlags;
   9161             this.observer = observer;
   9162             this.installerPackageName = installerPackageName;
   9163             this.manifestDigest = manifestDigest;
   9164             this.user = user;
   9165             this.instructionSets = instructionSets;
   9166             this.abiOverride = abiOverride;
   9167         }
   9168 
   9169         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
   9170         abstract int doPreInstall(int status);
   9171 
   9172         /**
   9173          * Rename package into final resting place. All paths on the given
   9174          * scanned package should be updated to reflect the rename.
   9175          */
   9176         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
   9177         abstract int doPostInstall(int status, int uid);
   9178 
   9179         /** @see PackageSettingBase#codePathString */
   9180         abstract String getCodePath();
   9181         /** @see PackageSettingBase#resourcePathString */
   9182         abstract String getResourcePath();
   9183         abstract String getLegacyNativeLibraryPath();
   9184 
   9185         // Need installer lock especially for dex file removal.
   9186         abstract void cleanUpResourcesLI();
   9187         abstract boolean doPostDeleteLI(boolean delete);
   9188         abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
   9189 
   9190         /**
   9191          * Called before the source arguments are copied. This is used mostly
   9192          * for MoveParams when it needs to read the source file to put it in the
   9193          * destination.
   9194          */
   9195         int doPreCopy() {
   9196             return PackageManager.INSTALL_SUCCEEDED;
   9197         }
   9198 
   9199         /**
   9200          * Called after the source arguments are copied. This is used mostly for
   9201          * MoveParams when it needs to read the source file to put it in the
   9202          * destination.
   9203          *
   9204          * @return
   9205          */
   9206         int doPostCopy(int uid) {
   9207             return PackageManager.INSTALL_SUCCEEDED;
   9208         }
   9209 
   9210         protected boolean isFwdLocked() {
   9211             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
   9212         }
   9213 
   9214         protected boolean isExternal() {
   9215             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
   9216         }
   9217 
   9218         UserHandle getUser() {
   9219             return user;
   9220         }
   9221     }
   9222 
   9223     /**
   9224      * Logic to handle installation of non-ASEC applications, including copying
   9225      * and renaming logic.
   9226      */
   9227     class FileInstallArgs extends InstallArgs {
   9228         private File codeFile;
   9229         private File resourceFile;
   9230         private File legacyNativeLibraryPath;
   9231 
   9232         // Example topology:
   9233         // /data/app/com.example/base.apk
   9234         // /data/app/com.example/split_foo.apk
   9235         // /data/app/com.example/lib/arm/libfoo.so
   9236         // /data/app/com.example/lib/arm64/libfoo.so
   9237         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
   9238 
   9239         /** New install */
   9240         FileInstallArgs(InstallParams params) {
   9241             super(params.origin, params.observer, params.installFlags,
   9242                     params.installerPackageName, params.getManifestDigest(), params.getUser(),
   9243                     null /* instruction sets */, params.packageAbiOverride);
   9244             if (isFwdLocked()) {
   9245                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
   9246             }
   9247         }
   9248 
   9249         /** Existing install */
   9250         FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
   9251                 String[] instructionSets) {
   9252             super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
   9253             this.codeFile = (codePath != null) ? new File(codePath) : null;
   9254             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
   9255             this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
   9256                     new File(legacyNativeLibraryPath) : null;
   9257         }
   9258 
   9259         boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
   9260             final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
   9261                     isFwdLocked(), abiOverride);
   9262 
   9263             final StorageManager storage = StorageManager.from(mContext);
   9264             return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
   9265         }
   9266 
   9267         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
   9268             if (origin.staged) {
   9269                 Slog.d(TAG, origin.file + " already staged; skipping copy");
   9270                 codeFile = origin.file;
   9271                 resourceFile = origin.file;
   9272                 return PackageManager.INSTALL_SUCCEEDED;
   9273             }
   9274 
   9275             try {
   9276                 final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
   9277                 codeFile = tempDir;
   9278                 resourceFile = tempDir;
   9279             } catch (IOException e) {
   9280                 Slog.w(TAG, "Failed to create copy file: " + e);
   9281                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
   9282             }
   9283 
   9284             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
   9285                 @Override
   9286                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
   9287                     if (!FileUtils.isValidExtFilename(name)) {
   9288                         throw new IllegalArgumentException("Invalid filename: " + name);
   9289                     }
   9290                     try {
   9291                         final File file = new File(codeFile, name);
   9292                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
   9293                                 O_RDWR | O_CREAT, 0644);
   9294                         Os.chmod(file.getAbsolutePath(), 0644);
   9295                         return new ParcelFileDescriptor(fd);
   9296                     } catch (ErrnoException e) {
   9297                         throw new RemoteException("Failed to open: " + e.getMessage());
   9298                     }
   9299                 }
   9300             };
   9301 
   9302             int ret = PackageManager.INSTALL_SUCCEEDED;
   9303             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
   9304             if (ret != PackageManager.INSTALL_SUCCEEDED) {
   9305                 Slog.e(TAG, "Failed to copy package");
   9306                 return ret;
   9307             }
   9308 
   9309             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
   9310             NativeLibraryHelper.Handle handle = null;
   9311             try {
   9312                 handle = NativeLibraryHelper.Handle.create(codeFile);
   9313                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
   9314                         abiOverride);
   9315             } catch (IOException e) {
   9316                 Slog.e(TAG, "Copying native libraries failed", e);
   9317                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
   9318             } finally {
   9319                 IoUtils.closeQuietly(handle);
   9320             }
   9321 
   9322             return ret;
   9323         }
   9324 
   9325         int doPreInstall(int status) {
   9326             if (status != PackageManager.INSTALL_SUCCEEDED) {
   9327                 cleanUp();
   9328             }
   9329             return status;
   9330         }
   9331 
   9332         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
   9333             if (status != PackageManager.INSTALL_SUCCEEDED) {
   9334                 cleanUp();
   9335                 return false;
   9336             } else {
   9337                 final File beforeCodeFile = codeFile;
   9338                 final File afterCodeFile = getNextCodePath(pkg.packageName);
   9339 
   9340                 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
   9341                 try {
   9342                     Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
   9343                 } catch (ErrnoException e) {
   9344                     Slog.d(TAG, "Failed to rename", e);
   9345                     return false;
   9346                 }
   9347 
   9348                 if (!SELinux.restoreconRecursive(afterCodeFile)) {
   9349                     Slog.d(TAG, "Failed to restorecon");
   9350                     return false;
   9351                 }
   9352 
   9353                 // Reflect the rename internally
   9354                 codeFile = afterCodeFile;
   9355                 resourceFile = afterCodeFile;
   9356 
   9357                 // Reflect the rename in scanned details
   9358                 pkg.codePath = afterCodeFile.getAbsolutePath();
   9359                 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
   9360                         pkg.baseCodePath);
   9361                 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
   9362                         pkg.splitCodePaths);
   9363 
   9364                 // Reflect the rename in app info
   9365                 pkg.applicationInfo.setCodePath(pkg.codePath);
   9366                 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
   9367                 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
   9368                 pkg.applicationInfo.setResourcePath(pkg.codePath);
   9369                 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
   9370                 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
   9371 
   9372                 return true;
   9373             }
   9374         }
   9375 
   9376         int doPostInstall(int status, int uid) {
   9377             if (status != PackageManager.INSTALL_SUCCEEDED) {
   9378                 cleanUp();
   9379             }
   9380             return status;
   9381         }
   9382 
   9383         @Override
   9384         String getCodePath() {
   9385             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
   9386         }
   9387 
   9388         @Override
   9389         String getResourcePath() {
   9390             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
   9391         }
   9392 
   9393         @Override
   9394         String getLegacyNativeLibraryPath() {
   9395             return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
   9396         }
   9397 
   9398         private boolean cleanUp() {
   9399             if (codeFile == null || !codeFile.exists()) {
   9400                 return false;
   9401             }
   9402 
   9403             if (codeFile.isDirectory()) {
   9404                 FileUtils.deleteContents(codeFile);
   9405             }
   9406             codeFile.delete();
   9407 
   9408             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
   9409                 resourceFile.delete();
   9410             }
   9411 
   9412             if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
   9413                 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
   9414                     Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
   9415                 }
   9416                 legacyNativeLibraryPath.delete();
   9417             }
   9418 
   9419             return true;
   9420         }
   9421 
   9422         void cleanUpResourcesLI() {
   9423             // Try enumerating all code paths before deleting
   9424             List<String> allCodePaths = Collections.EMPTY_LIST;
   9425             if (codeFile != null && codeFile.exists()) {
   9426                 try {
   9427                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
   9428                     allCodePaths = pkg.getAllCodePaths();
   9429                 } catch (PackageParserException e) {
   9430                     // Ignored; we tried our best
   9431                 }
   9432             }
   9433 
   9434             cleanUp();
   9435 
   9436             if (!allCodePaths.isEmpty()) {
   9437                 if (instructionSets == null) {
   9438                     throw new IllegalStateException("instructionSet == null");
   9439                 }
   9440                 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
   9441                 for (String codePath : allCodePaths) {
   9442                     for (String dexCodeInstructionSet : dexCodeInstructionSets) {
   9443                         int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
   9444                         if (retCode < 0) {
   9445                             Slog.w(TAG, "Couldn't remove dex file for package: "
   9446                                     + " at location " + codePath + ", retcode=" + retCode);
   9447                             // we don't consider this to be a failure of the core package deletion
   9448                         }
   9449                     }
   9450                 }
   9451             }
   9452         }
   9453 
   9454         boolean doPostDeleteLI(boolean delete) {
   9455             // XXX err, shouldn't we respect the delete flag?
   9456             cleanUpResourcesLI();
   9457             return true;
   9458         }
   9459     }
   9460 
   9461     private boolean isAsecExternal(String cid) {
   9462         final String asecPath = PackageHelper.getSdFilesystem(cid);
   9463         return !asecPath.startsWith(mAsecInternalPath);
   9464     }
   9465 
   9466     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
   9467             PackageManagerException {
   9468         if (copyRet < 0) {
   9469             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
   9470                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
   9471                 throw new PackageManagerException(copyRet, message);
   9472             }
   9473         }
   9474     }
   9475 
   9476     /**
   9477      * Extract the MountService "container ID" from the full code path of an
   9478      * .apk.
   9479      */
   9480     static String cidFromCodePath(String fullCodePath) {
   9481         int eidx = fullCodePath.lastIndexOf("/");
   9482         String subStr1 = fullCodePath.substring(0, eidx);
   9483         int sidx = subStr1.lastIndexOf("/");
   9484         return subStr1.substring(sidx+1, eidx);
   9485     }
   9486 
   9487     /**
   9488      * Logic to handle installation of ASEC applications, including copying and
   9489      * renaming logic.
   9490      */
   9491     class AsecInstallArgs extends InstallArgs {
   9492         static final String RES_FILE_NAME = "pkg.apk";
   9493         static final String PUBLIC_RES_FILE_NAME = "res.zip";
   9494 
   9495         String cid;
   9496         String packagePath;
   9497         String resourcePath;
   9498         String legacyNativeLibraryDir;
   9499 
   9500         /** New install */
   9501         AsecInstallArgs(InstallParams params) {
   9502             super(params.origin, params.observer, params.installFlags,
   9503                     params.installerPackageName, params.getManifestDigest(),
   9504                     params.getUser(), null /* instruction sets */,
   9505                     params.packageAbiOverride);
   9506         }
   9507 
   9508         /** Existing install */
   9509         AsecInstallArgs(String fullCodePath, String[] instructionSets,
   9510                         boolean isExternal, boolean isForwardLocked) {
   9511             super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
   9512                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
   9513                     instructionSets, null);
   9514             // Hackily pretend we're still looking at a full code path
   9515             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
   9516                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
   9517             }
   9518 
   9519             // Extract cid from fullCodePath
   9520             int eidx = fullCodePath.lastIndexOf("/");
   9521             String subStr1 = fullCodePath.substring(0, eidx);
   9522             int sidx = subStr1.lastIndexOf("/");
   9523             cid = subStr1.substring(sidx+1, eidx);
   9524             setMountPath(subStr1);
   9525         }
   9526 
   9527         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
   9528             super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
   9529                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
   9530                     instructionSets, null);
   9531             this.cid = cid;
   9532             setMountPath(PackageHelper.getSdDir(cid));
   9533         }
   9534 
   9535         void createCopyFile() {
   9536             cid = mInstallerService.allocateExternalStageCidLegacy();
   9537         }
   9538 
   9539         boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
   9540             final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
   9541                     abiOverride);
   9542 
   9543             final File target;
   9544             if (isExternal()) {
   9545                 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
   9546             } else {
   9547                 target = Environment.getDataDirectory();
   9548             }
   9549 
   9550             final StorageManager storage = StorageManager.from(mContext);
   9551             return (sizeBytes <= storage.getStorageBytesUntilLow(target));
   9552         }
   9553 
   9554         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
   9555             if (origin.staged) {
   9556                 Slog.d(TAG, origin.cid + " already staged; skipping copy");
   9557                 cid = origin.cid;
   9558                 setMountPath(PackageHelper.getSdDir(cid));
   9559                 return PackageManager.INSTALL_SUCCEEDED;
   9560             }
   9561 
   9562             if (temp) {
   9563                 createCopyFile();
   9564             } else {
   9565                 /*
   9566                  * Pre-emptively destroy the container since it's destroyed if
   9567                  * copying fails due to it existing anyway.
   9568                  */
   9569                 PackageHelper.destroySdDir(cid);
   9570             }
   9571 
   9572             final String newMountPath = imcs.copyPackageToContainer(
   9573                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
   9574                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
   9575 
   9576             if (newMountPath != null) {
   9577                 setMountPath(newMountPath);
   9578                 return PackageManager.INSTALL_SUCCEEDED;
   9579             } else {
   9580                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
   9581             }
   9582         }
   9583 
   9584         @Override
   9585         String getCodePath() {
   9586             return packagePath;
   9587         }
   9588 
   9589         @Override
   9590         String getResourcePath() {
   9591             return resourcePath;
   9592         }
   9593 
   9594         @Override
   9595         String getLegacyNativeLibraryPath() {
   9596             return legacyNativeLibraryDir;
   9597         }
   9598 
   9599         int doPreInstall(int status) {
   9600             if (status != PackageManager.INSTALL_SUCCEEDED) {
   9601                 // Destroy container
   9602                 PackageHelper.destroySdDir(cid);
   9603             } else {
   9604                 boolean mounted = PackageHelper.isContainerMounted(cid);
   9605                 if (!mounted) {
   9606                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
   9607                             Process.SYSTEM_UID);
   9608                     if (newMountPath != null) {
   9609                         setMountPath(newMountPath);
   9610                     } else {
   9611                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
   9612                     }
   9613                 }
   9614             }
   9615             return status;
   9616         }
   9617 
   9618         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
   9619             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
   9620             String newMountPath = null;
   9621             if (PackageHelper.isContainerMounted(cid)) {
   9622                 // Unmount the container
   9623                 if (!PackageHelper.unMountSdDir(cid)) {
   9624                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
   9625                     return false;
   9626                 }
   9627             }
   9628             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
   9629                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
   9630                         " which might be stale. Will try to clean up.");
   9631                 // Clean up the stale container and proceed to recreate.
   9632                 if (!PackageHelper.destroySdDir(newCacheId)) {
   9633                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
   9634                     return false;
   9635                 }
   9636                 // Successfully cleaned up stale container. Try to rename again.
   9637                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
   9638                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
   9639                             + " inspite of cleaning it up.");
   9640                     return false;
   9641                 }
   9642             }
   9643             if (!PackageHelper.isContainerMounted(newCacheId)) {
   9644                 Slog.w(TAG, "Mounting container " + newCacheId);
   9645                 newMountPath = PackageHelper.mountSdDir(newCacheId,
   9646                         getEncryptKey(), Process.SYSTEM_UID);
   9647             } else {
   9648                 newMountPath = PackageHelper.getSdDir(newCacheId);
   9649             }
   9650             if (newMountPath == null) {
   9651                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
   9652                 return false;
   9653             }
   9654             Log.i(TAG, "Succesfully renamed " + cid +
   9655                     " to " + newCacheId +
   9656                     " at new path: " + newMountPath);
   9657             cid = newCacheId;
   9658 
   9659             final File beforeCodeFile = new File(packagePath);
   9660             setMountPath(newMountPath);
   9661             final File afterCodeFile = new File(packagePath);
   9662 
   9663             // Reflect the rename in scanned details
   9664             pkg.codePath = afterCodeFile.getAbsolutePath();
   9665             pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
   9666                     pkg.baseCodePath);
   9667             pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
   9668                     pkg.splitCodePaths);
   9669 
   9670             // Reflect the rename in app info
   9671             pkg.applicationInfo.setCodePath(pkg.codePath);
   9672             pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
   9673             pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
   9674             pkg.applicationInfo.setResourcePath(pkg.codePath);
   9675             pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
   9676             pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
   9677 
   9678             return true;
   9679         }
   9680 
   9681         private void setMountPath(String mountPath) {
   9682             final File mountFile = new File(mountPath);
   9683 
   9684             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
   9685             if (monolithicFile.exists()) {
   9686                 packagePath = monolithicFile.getAbsolutePath();
   9687                 if (isFwdLocked()) {
   9688                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
   9689                 } else {
   9690                     resourcePath = packagePath;
   9691                 }
   9692             } else {
   9693                 packagePath = mountFile.getAbsolutePath();
   9694                 resourcePath = packagePath;
   9695             }
   9696 
   9697             legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
   9698         }
   9699 
   9700         int doPostInstall(int status, int uid) {
   9701             if (status != PackageManager.INSTALL_SUCCEEDED) {
   9702                 cleanUp();
   9703             } else {
   9704                 final int groupOwner;
   9705                 final String protectedFile;
   9706                 if (isFwdLocked()) {
   9707                     groupOwner = UserHandle.getSharedAppGid(uid);
   9708                     protectedFile = RES_FILE_NAME;
   9709                 } else {
   9710                     groupOwner = -1;
   9711                     protectedFile = null;
   9712                 }
   9713 
   9714                 if (uid < Process.FIRST_APPLICATION_UID
   9715                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
   9716                     Slog.e(TAG, "Failed to finalize " + cid);
   9717                     PackageHelper.destroySdDir(cid);
   9718                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
   9719                 }
   9720 
   9721                 boolean mounted = PackageHelper.isContainerMounted(cid);
   9722                 if (!mounted) {
   9723                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
   9724                 }
   9725             }
   9726             return status;
   9727         }
   9728 
   9729         private void cleanUp() {
   9730             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
   9731 
   9732             // Destroy secure container
   9733             PackageHelper.destroySdDir(cid);
   9734         }
   9735 
   9736         private List<String> getAllCodePaths() {
   9737             final File codeFile = new File(getCodePath());
   9738             if (codeFile != null && codeFile.exists()) {
   9739                 try {
   9740                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
   9741                     return pkg.getAllCodePaths();
   9742                 } catch (PackageParserException e) {
   9743                     // Ignored; we tried our best
   9744                 }
   9745             }
   9746             return Collections.EMPTY_LIST;
   9747         }
   9748 
   9749         void cleanUpResourcesLI() {
   9750             // Enumerate all code paths before deleting
   9751             cleanUpResourcesLI(getAllCodePaths());
   9752         }
   9753 
   9754         private void cleanUpResourcesLI(List<String> allCodePaths) {
   9755             cleanUp();
   9756 
   9757             if (!allCodePaths.isEmpty()) {
   9758                 if (instructionSets == null) {
   9759                     throw new IllegalStateException("instructionSet == null");
   9760                 }
   9761                 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
   9762                 for (String codePath : allCodePaths) {
   9763                     for (String dexCodeInstructionSet : dexCodeInstructionSets) {
   9764                         int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
   9765                         if (retCode < 0) {
   9766                             Slog.w(TAG, "Couldn't remove dex file for package: "
   9767                                     + " at location " + codePath + ", retcode=" + retCode);
   9768                             // we don't consider this to be a failure of the core package deletion
   9769                         }
   9770                     }
   9771                 }
   9772             }
   9773         }
   9774 
   9775         boolean matchContainer(String app) {
   9776             if (cid.startsWith(app)) {
   9777                 return true;
   9778             }
   9779             return false;
   9780         }
   9781 
   9782         String getPackageName() {
   9783             return getAsecPackageName(cid);
   9784         }
   9785 
   9786         boolean doPostDeleteLI(boolean delete) {
   9787             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
   9788             final List<String> allCodePaths = getAllCodePaths();
   9789             boolean mounted = PackageHelper.isContainerMounted(cid);
   9790             if (mounted) {
   9791                 // Unmount first
   9792                 if (PackageHelper.unMountSdDir(cid)) {
   9793                     mounted = false;
   9794                 }
   9795             }
   9796             if (!mounted && delete) {
   9797                 cleanUpResourcesLI(allCodePaths);
   9798             }
   9799             return !mounted;
   9800         }
   9801 
   9802         @Override
   9803         int doPreCopy() {
   9804             if (isFwdLocked()) {
   9805                 if (!PackageHelper.fixSdPermissions(cid,
   9806                         getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
   9807                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
   9808                 }
   9809             }
   9810 
   9811             return PackageManager.INSTALL_SUCCEEDED;
   9812         }
   9813 
   9814         @Override
   9815         int doPostCopy(int uid) {
   9816             if (isFwdLocked()) {
   9817                 if (uid < Process.FIRST_APPLICATION_UID
   9818                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
   9819                                 RES_FILE_NAME)) {
   9820                     Slog.e(TAG, "Failed to finalize " + cid);
   9821                     PackageHelper.destroySdDir(cid);
   9822                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
   9823                 }
   9824             }
   9825 
   9826             return PackageManager.INSTALL_SUCCEEDED;
   9827         }
   9828     }
   9829 
   9830     static String getAsecPackageName(String packageCid) {
   9831         int idx = packageCid.lastIndexOf("-");
   9832         if (idx == -1) {
   9833             return packageCid;
   9834         }
   9835         return packageCid.substring(0, idx);
   9836     }
   9837 
   9838     // Utility method used to create code paths based on package name and available index.
   9839     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
   9840         String idxStr = "";
   9841         int idx = 1;
   9842         // Fall back to default value of idx=1 if prefix is not
   9843         // part of oldCodePath
   9844         if (oldCodePath != null) {
   9845             String subStr = oldCodePath;
   9846             // Drop the suffix right away
   9847             if (suffix != null && subStr.endsWith(suffix)) {
   9848                 subStr = subStr.substring(0, subStr.length() - suffix.length());
   9849             }
   9850             // If oldCodePath already contains prefix find out the
   9851             // ending index to either increment or decrement.
   9852             int sidx = subStr.lastIndexOf(prefix);
   9853             if (sidx != -1) {
   9854                 subStr = subStr.substring(sidx + prefix.length());
   9855                 if (subStr != null) {
   9856                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
   9857                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
   9858                     }
   9859                     try {
   9860                         idx = Integer.parseInt(subStr);
   9861                         if (idx <= 1) {
   9862                             idx++;
   9863                         } else {
   9864                             idx--;
   9865                         }
   9866                     } catch(NumberFormatException e) {
   9867                     }
   9868                 }
   9869             }
   9870         }
   9871         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
   9872         return prefix + idxStr;
   9873     }
   9874 
   9875     private File getNextCodePath(String packageName) {
   9876         int suffix = 1;
   9877         File result;
   9878         do {
   9879             result = new File(mAppInstallDir, packageName + "-" + suffix);
   9880             suffix++;
   9881         } while (result.exists());
   9882         return result;
   9883     }
   9884 
   9885     // Utility method used to ignore ADD/REMOVE events
   9886     // by directory observer.
   9887     private static boolean ignoreCodePath(String fullPathStr) {
   9888         String apkName = deriveCodePathName(fullPathStr);
   9889         int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
   9890         if (idx != -1 && ((idx+1) < apkName.length())) {
   9891             // Make sure the package ends with a numeral
   9892             String version = apkName.substring(idx+1);
   9893             try {
   9894                 Integer.parseInt(version);
   9895                 return true;
   9896             } catch (NumberFormatException e) {}
   9897         }
   9898         return false;
   9899     }
   9900 
   9901     // Utility method that returns the relative package path with respect
   9902     // to the installation directory. Like say for /data/data/com.test-1.apk
   9903     // string com.test-1 is returned.
   9904     static String deriveCodePathName(String codePath) {
   9905         if (codePath == null) {
   9906             return null;
   9907         }
   9908         final File codeFile = new File(codePath);
   9909         final String name = codeFile.getName();
   9910         if (codeFile.isDirectory()) {
   9911             return name;
   9912         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
   9913             final int lastDot = name.lastIndexOf('.');
   9914             return name.substring(0, lastDot);
   9915         } else {
   9916             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
   9917             return null;
   9918         }
   9919     }
   9920 
   9921     class PackageInstalledInfo {
   9922         String name;
   9923         int uid;
   9924         // The set of users that originally had this package installed.
   9925         int[] origUsers;
   9926         // The set of users that now have this package installed.
   9927         int[] newUsers;
   9928         PackageParser.Package pkg;
   9929         int returnCode;
   9930         String returnMsg;
   9931         PackageRemovedInfo removedInfo;
   9932 
   9933         public void setError(int code, String msg) {
   9934             returnCode = code;
   9935             returnMsg = msg;
   9936             Slog.w(TAG, msg);
   9937         }
   9938 
   9939         public void setError(String msg, PackageParserException e) {
   9940             returnCode = e.error;
   9941             returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
   9942             Slog.w(TAG, msg, e);
   9943         }
   9944 
   9945         public void setError(String msg, PackageManagerException e) {
   9946             returnCode = e.error;
   9947             returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
   9948             Slog.w(TAG, msg, e);
   9949         }
   9950 
   9951         // In some error cases we want to convey more info back to the observer
   9952         String origPackage;
   9953         String origPermission;
   9954     }
   9955 
   9956     /*
   9957      * Install a non-existing package.
   9958      */
   9959     private void installNewPackageLI(PackageParser.Package pkg,
   9960             int parseFlags, int scanFlags, UserHandle user,
   9961             String installerPackageName, PackageInstalledInfo res) {
   9962         // Remember this for later, in case we need to rollback this install
   9963         String pkgName = pkg.packageName;
   9964 
   9965         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
   9966         boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
   9967         synchronized(mPackages) {
   9968             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
   9969                 // A package with the same name is already installed, though
   9970                 // it has been renamed to an older name.  The package we
   9971                 // are trying to install should be installed as an update to
   9972                 // the existing one, but that has not been requested, so bail.
   9973                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
   9974                         + " without first uninstalling package running as "
   9975                         + mSettings.mRenamedPackages.get(pkgName));
   9976                 return;
   9977             }
   9978             if (mPackages.containsKey(pkgName)) {
   9979                 // Don't allow installation over an existing package with the same name.
   9980                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
   9981                         + " without first uninstalling.");
   9982                 return;
   9983             }
   9984         }
   9985 
   9986         try {
   9987             PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
   9988                     System.currentTimeMillis(), user);
   9989 
   9990             updateSettingsLI(newPackage, installerPackageName, null, null, res);
   9991             // delete the partially installed application. the data directory will have to be
   9992             // restored if it was already existing
   9993             if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
   9994                 // remove package from internal structures.  Note that we want deletePackageX to
   9995                 // delete the package data and cache directories that it created in
   9996                 // scanPackageLocked, unless those directories existed before we even tried to
   9997                 // install.
   9998                 deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
   9999                         dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
   10000                                 res.removedInfo, true);
   10001             }
   10002 
   10003         } catch (PackageManagerException e) {
   10004             res.setError("Package couldn't be installed in " + pkg.codePath, e);
   10005         }
   10006     }
   10007 
   10008     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
   10009         // Upgrade keysets are being used.  Determine if new package has a superset of the
   10010         // required keys.
   10011         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
   10012         KeySetManagerService ksms = mSettings.mKeySetManagerService;
   10013         for (int i = 0; i < upgradeKeySets.length; i++) {
   10014             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
   10015             if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
   10016                 return true;
   10017             }
   10018         }
   10019         return false;
   10020     }
   10021 
   10022     private void replacePackageLI(PackageParser.Package pkg,
   10023             int parseFlags, int scanFlags, UserHandle user,
   10024             String installerPackageName, PackageInstalledInfo res) {
   10025         PackageParser.Package oldPackage;
   10026         String pkgName = pkg.packageName;
   10027         int[] allUsers;
   10028         boolean[] perUserInstalled;
   10029 
   10030         // First find the old package info and check signatures
   10031         synchronized(mPackages) {
   10032             oldPackage = mPackages.get(pkgName);
   10033             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
   10034             PackageSetting ps = mSettings.mPackages.get(pkgName);
   10035             if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
   10036                 // default to original signature matching
   10037                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
   10038                     != PackageManager.SIGNATURE_MATCH) {
   10039                     res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
   10040                             "New package has a different signature: " + pkgName);
   10041                     return;
   10042                 }
   10043             } else {
   10044                 if(!checkUpgradeKeySetLP(ps, pkg)) {
   10045                     res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
   10046                             "New package not signed by keys specified by upgrade-keysets: "
   10047                             + pkgName);
   10048                     return;
   10049                 }
   10050             }
   10051 
   10052             // In case of rollback, remember per-user/profile install state
   10053             allUsers = sUserManager.getUserIds();
   10054             perUserInstalled = new boolean[allUsers.length];
   10055             for (int i = 0; i < allUsers.length; i++) {
   10056                 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
   10057             }
   10058         }
   10059 
   10060         boolean sysPkg = (isSystemApp(oldPackage));
   10061         if (sysPkg) {
   10062             replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
   10063                     user, allUsers, perUserInstalled, installerPackageName, res);
   10064         } else {
   10065             replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
   10066                     user, allUsers, perUserInstalled, installerPackageName, res);
   10067         }
   10068     }
   10069 
   10070     private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
   10071             PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
   10072             int[] allUsers, boolean[] perUserInstalled,
   10073             String installerPackageName, PackageInstalledInfo res) {
   10074         String pkgName = deletedPackage.packageName;
   10075         boolean deletedPkg = true;
   10076         boolean updatedSettings = false;
   10077 
   10078         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
   10079                 + deletedPackage);
   10080         long origUpdateTime;
   10081         if (pkg.mExtras != null) {
   10082             origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
   10083         } else {
   10084             origUpdateTime = 0;
   10085         }
   10086 
   10087         // First delete the existing package while retaining the data directory
   10088         if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
   10089                 res.removedInfo, true)) {
   10090             // If the existing package wasn't successfully deleted
   10091             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
   10092             deletedPkg = false;
   10093         } else {
   10094             // Successfully deleted the old package; proceed with replace.
   10095 
   10096             // If deleted package lived in a container, give users a chance to
   10097             // relinquish resources before killing.
   10098             if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
   10099                 if (DEBUG_INSTALL) {
   10100                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
   10101                 }
   10102                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
   10103                 final ArrayList<String> pkgList = new ArrayList<String>(1);
   10104                 pkgList.add(deletedPackage.applicationInfo.packageName);
   10105                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
   10106             }
   10107 
   10108             deleteCodeCacheDirsLI(pkgName);
   10109             try {
   10110                 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
   10111                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
   10112                 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
   10113                 updatedSettings = true;
   10114             } catch (PackageManagerException e) {
   10115                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
   10116             }
   10117         }
   10118 
   10119         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
   10120             // remove package from internal structures.  Note that we want deletePackageX to
   10121             // delete the package data and cache directories that it created in
   10122             // scanPackageLocked, unless those directories existed before we even tried to
   10123             // install.
   10124             if(updatedSettings) {
   10125                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
   10126                 deletePackageLI(
   10127                         pkgName, null, true, allUsers, perUserInstalled,
   10128                         PackageManager.DELETE_KEEP_DATA,
   10129                                 res.removedInfo, true);
   10130             }
   10131             // Since we failed to install the new package we need to restore the old
   10132             // package that we deleted.
   10133             if (deletedPkg) {
   10134                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
   10135                 File restoreFile = new File(deletedPackage.codePath);
   10136                 // Parse old package
   10137                 boolean oldOnSd = isExternal(deletedPackage);
   10138                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
   10139                         (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
   10140                         (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
   10141                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
   10142                 try {
   10143                     scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
   10144                 } catch (PackageManagerException e) {
   10145                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
   10146                             + e.getMessage());
   10147                     return;
   10148                 }
   10149                 // Restore of old package succeeded. Update permissions.
   10150                 // writer
   10151                 synchronized (mPackages) {
   10152                     updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
   10153                             UPDATE_PERMISSIONS_ALL);
   10154                     // can downgrade to reader
   10155                     mSettings.writeLPr();
   10156                 }
   10157                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
   10158             }
   10159         }
   10160     }
   10161 
   10162     private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
   10163             PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
   10164             int[] allUsers, boolean[] perUserInstalled,
   10165             String installerPackageName, PackageInstalledInfo res) {
   10166         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
   10167                 + ", old=" + deletedPackage);
   10168         boolean disabledSystem = false;
   10169         boolean updatedSettings = false;
   10170         parseFlags |= PackageParser.PARSE_IS_SYSTEM;
   10171         if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
   10172             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
   10173         }
   10174         String packageName = deletedPackage.packageName;
   10175         if (packageName == null) {
   10176             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
   10177                     "Attempt to delete null packageName.");
   10178             return;
   10179         }
   10180         PackageParser.Package oldPkg;
   10181         PackageSetting oldPkgSetting;
   10182         // reader
   10183         synchronized (mPackages) {
   10184             oldPkg = mPackages.get(packageName);
   10185             oldPkgSetting = mSettings.mPackages.get(packageName);
   10186             if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
   10187                     (oldPkgSetting == null)) {
   10188                 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
   10189                         "Couldn't find package:" + packageName + " information");
   10190                 return;
   10191             }
   10192         }
   10193 
   10194         killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
   10195 
   10196         res.removedInfo.uid = oldPkg.applicationInfo.uid;
   10197         res.removedInfo.removedPackage = packageName;
   10198         // Remove existing system package
   10199         removePackageLI(oldPkgSetting, true);
   10200         // writer
   10201         synchronized (mPackages) {
   10202             disabledSystem = mSettings.disableSystemPackageLPw(packageName);
   10203             if (!disabledSystem && deletedPackage != null) {
   10204                 // We didn't need to disable the .apk as a current system package,
   10205                 // which means we are replacing another update that is already
   10206                 // installed.  We need to make sure to delete the older one's .apk.
   10207                 res.removedInfo.args = createInstallArgsForExisting(0,
   10208                         deletedPackage.applicationInfo.getCodePath(),
   10209                         deletedPackage.applicationInfo.getResourcePath(),
   10210                         deletedPackage.applicationInfo.nativeLibraryRootDir,
   10211                         getAppDexInstructionSets(deletedPackage.applicationInfo));
   10212             } else {
   10213                 res.removedInfo.args = null;
   10214             }
   10215         }
   10216 
   10217         // Successfully disabled the old package. Now proceed with re-installation
   10218         deleteCodeCacheDirsLI(packageName);
   10219 
   10220         res.returnCode = PackageManager.INSTALL_SUCCEEDED;
   10221         pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
   10222 
   10223         PackageParser.Package newPackage = null;
   10224         try {
   10225             newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
   10226             if (newPackage.mExtras != null) {
   10227                 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
   10228                 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
   10229                 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
   10230 
   10231                 // is the update attempting to change shared user? that isn't going to work...
   10232                 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
   10233                     res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
   10234                             "Forbidding shared user change from " + oldPkgSetting.sharedUser
   10235                             + " to " + newPkgSetting.sharedUser);
   10236                     updatedSettings = true;
   10237                 }
   10238             }
   10239 
   10240             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
   10241                 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
   10242                 updatedSettings = true;
   10243             }
   10244 
   10245         } catch (PackageManagerException e) {
   10246             res.setError("Package couldn't be installed in " + pkg.codePath, e);
   10247         }
   10248 
   10249         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
   10250             // Re installation failed. Restore old information
   10251             // Remove new pkg information
   10252             if (newPackage != null) {
   10253                 removeInstalledPackageLI(newPackage, true);
   10254             }
   10255             // Add back the old system package
   10256             try {
   10257                 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
   10258             } catch (PackageManagerException e) {
   10259                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
   10260             }
   10261             // Restore the old system information in Settings
   10262             synchronized (mPackages) {
   10263                 if (disabledSystem) {
   10264                     mSettings.enableSystemPackageLPw(packageName);
   10265                 }
   10266                 if (updatedSettings) {
   10267                     mSettings.setInstallerPackageName(packageName,
   10268                             oldPkgSetting.installerPackageName);
   10269                 }
   10270                 mSettings.writeLPr();
   10271             }
   10272         }
   10273     }
   10274 
   10275     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
   10276             int[] allUsers, boolean[] perUserInstalled,
   10277             PackageInstalledInfo res) {
   10278         String pkgName = newPackage.packageName;
   10279         synchronized (mPackages) {
   10280             //write settings. the installStatus will be incomplete at this stage.
   10281             //note that the new package setting would have already been
   10282             //added to mPackages. It hasn't been persisted yet.
   10283             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
   10284             mSettings.writeLPr();
   10285         }
   10286 
   10287         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
   10288 
   10289         synchronized (mPackages) {
   10290             updatePermissionsLPw(newPackage.packageName, newPackage,
   10291                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
   10292                             ? UPDATE_PERMISSIONS_ALL : 0));
   10293             // For system-bundled packages, we assume that installing an upgraded version
   10294             // of the package implies that the user actually wants to run that new code,
   10295             // so we enable the package.
   10296             if (isSystemApp(newPackage)) {
   10297                 // NB: implicit assumption that system package upgrades apply to all users
   10298                 if (DEBUG_INSTALL) {
   10299                     Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
   10300                 }
   10301                 PackageSetting ps = mSettings.mPackages.get(pkgName);
   10302                 if (ps != null) {
   10303                     if (res.origUsers != null) {
   10304                         for (int userHandle : res.origUsers) {
   10305                             ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
   10306                                     userHandle, installerPackageName);
   10307                         }
   10308                     }
   10309                     // Also convey the prior install/uninstall state
   10310                     if (allUsers != null && perUserInstalled != null) {
   10311                         for (int i = 0; i < allUsers.length; i++) {
   10312                             if (DEBUG_INSTALL) {
   10313                                 Slog.d(TAG, "    user " + allUsers[i]
   10314                                         + " => " + perUserInstalled[i]);
   10315                             }
   10316                             ps.setInstalled(perUserInstalled[i], allUsers[i]);
   10317                         }
   10318                         // these install state changes will be persisted in the
   10319                         // upcoming call to mSettings.writeLPr().
   10320                     }
   10321                 }
   10322             }
   10323             res.name = pkgName;
   10324             res.uid = newPackage.applicationInfo.uid;
   10325             res.pkg = newPackage;
   10326             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
   10327             mSettings.setInstallerPackageName(pkgName, installerPackageName);
   10328             res.returnCode = PackageManager.INSTALL_SUCCEEDED;
   10329             //to update install status
   10330             mSettings.writeLPr();
   10331         }
   10332     }
   10333 
   10334     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
   10335         final int installFlags = args.installFlags;
   10336         String installerPackageName = args.installerPackageName;
   10337         File tmpPackageFile = new File(args.getCodePath());
   10338         boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
   10339         boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
   10340         boolean replace = false;
   10341         final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
   10342         // Result object to be returned
   10343         res.returnCode = PackageManager.INSTALL_SUCCEEDED;
   10344 
   10345         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
   10346         // Retrieve PackageSettings and parse package
   10347         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
   10348                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
   10349                 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
   10350         PackageParser pp = new PackageParser();
   10351         pp.setSeparateProcesses(mSeparateProcesses);
   10352         pp.setDisplayMetrics(mMetrics);
   10353 
   10354         final PackageParser.Package pkg;
   10355         try {
   10356             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
   10357         } catch (PackageParserException e) {
   10358             res.setError("Failed parse during installPackageLI", e);
   10359             return;
   10360         }
   10361 
   10362         // Mark that we have an install time CPU ABI override.
   10363         pkg.cpuAbiOverride = args.abiOverride;
   10364 
   10365         String pkgName = res.name = pkg.packageName;
   10366         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
   10367             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
   10368                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
   10369                 return;
   10370             }
   10371         }
   10372 
   10373         try {
   10374             pp.collectCertificates(pkg, parseFlags);
   10375             pp.collectManifestDigest(pkg);
   10376         } catch (PackageParserException e) {
   10377             res.setError("Failed collect during installPackageLI", e);
   10378             return;
   10379         }
   10380 
   10381         /* If the installer passed in a manifest digest, compare it now. */
   10382         if (args.manifestDigest != null) {
   10383             if (DEBUG_INSTALL) {
   10384                 final String parsedManifest = pkg.manifestDigest == null ? "null"
   10385                         : pkg.manifestDigest.toString();
   10386                 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
   10387                         + parsedManifest);
   10388             }
   10389 
   10390             if (!args.manifestDigest.equals(pkg.manifestDigest)) {
   10391                 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
   10392                 return;
   10393             }
   10394         } else if (DEBUG_INSTALL) {
   10395             final String parsedManifest = pkg.manifestDigest == null
   10396                     ? "null" : pkg.manifestDigest.toString();
   10397             Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
   10398         }
   10399 
   10400         // Get rid of all references to package scan path via parser.
   10401         pp = null;
   10402         String oldCodePath = null;
   10403         boolean systemApp = false;
   10404         synchronized (mPackages) {
   10405             // Check whether the newly-scanned package wants to define an already-defined perm
   10406             int N = pkg.permissions.size();
   10407             for (int i = N-1; i >= 0; i--) {
   10408                 PackageParser.Permission perm = pkg.permissions.get(i);
   10409                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
   10410                 if (bp != null) {
   10411                     // If the defining package is signed with our cert, it's okay.  This
   10412                     // also includes the "updating the same package" case, of course.
   10413                     // "updating same package" could also involve key-rotation.
   10414                     final boolean sigsOk;
   10415                     if (!bp.sourcePackage.equals(pkg.packageName)
   10416                             || !(bp.packageSetting instanceof PackageSetting)
   10417                             || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
   10418                             || ((PackageSetting) bp.packageSetting).sharedUser != null) {
   10419                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
   10420                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
   10421                     } else {
   10422                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
   10423                     }
   10424                     if (!sigsOk) {
   10425                         // If the owning package is the system itself, we log but allow
   10426                         // install to proceed; we fail the install on all other permission
   10427                         // redefinitions.
   10428                         if (!bp.sourcePackage.equals("android")) {
   10429                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
   10430                                     + pkg.packageName + " attempting to redeclare permission "
   10431                                     + perm.info.name + " already owned by " + bp.sourcePackage);
   10432                             res.origPermission = perm.info.name;
   10433                             res.origPackage = bp.sourcePackage;
   10434                             return;
   10435                         } else {
   10436                             Slog.w(TAG, "Package " + pkg.packageName
   10437                                     + " attempting to redeclare system permission "
   10438                                     + perm.info.name + "; ignoring new declaration");
   10439                             pkg.permissions.remove(i);
   10440                         }
   10441                     }
   10442                 }
   10443             }
   10444 
   10445             // Check if installing already existing package
   10446             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
   10447                 String oldName = mSettings.mRenamedPackages.get(pkgName);
   10448                 if (pkg.mOriginalPackages != null
   10449                         && pkg.mOriginalPackages.contains(oldName)
   10450                         && mPackages.containsKey(oldName)) {
   10451                     // This package is derived from an original package,
   10452                     // and this device has been updating from that original
   10453                     // name.  We must continue using the original name, so
   10454                     // rename the new package here.
   10455                     pkg.setPackageName(oldName);
   10456                     pkgName = pkg.packageName;
   10457                     replace = true;
   10458                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
   10459                             + oldName + " pkgName=" + pkgName);
   10460                 } else if (mPackages.containsKey(pkgName)) {
   10461                     // This package, under its official name, already exists
   10462                     // on the device; we should replace it.
   10463                     replace = true;
   10464                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
   10465                 }
   10466             }
   10467             PackageSetting ps = mSettings.mPackages.get(pkgName);
   10468             if (ps != null) {
   10469                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
   10470                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
   10471                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
   10472                     systemApp = (ps.pkg.applicationInfo.flags &
   10473                             ApplicationInfo.FLAG_SYSTEM) != 0;
   10474                 }
   10475                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
   10476             }
   10477         }
   10478 
   10479         if (systemApp && onSd) {
   10480             // Disable updates to system apps on sdcard
   10481             res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
   10482                     "Cannot install updates to system apps on sdcard");
   10483             return;
   10484         }
   10485 
   10486         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
   10487             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
   10488             return;
   10489         }
   10490 
   10491         if (replace) {
   10492             replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
   10493                     installerPackageName, res);
   10494         } else {
   10495             installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
   10496                     args.user, installerPackageName, res);
   10497         }
   10498         synchronized (mPackages) {
   10499             final PackageSetting ps = mSettings.mPackages.get(pkgName);
   10500             if (ps != null) {
   10501                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
   10502             }
   10503         }
   10504     }
   10505 
   10506     private static boolean isForwardLocked(PackageParser.Package pkg) {
   10507         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
   10508     }
   10509 
   10510     private static boolean isForwardLocked(ApplicationInfo info) {
   10511         return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
   10512     }
   10513 
   10514     private boolean isForwardLocked(PackageSetting ps) {
   10515         return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
   10516     }
   10517 
   10518     private static boolean isMultiArch(PackageSetting ps) {
   10519         return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
   10520     }
   10521 
   10522     private static boolean isMultiArch(ApplicationInfo info) {
   10523         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
   10524     }
   10525 
   10526     private static boolean isExternal(PackageParser.Package pkg) {
   10527         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
   10528     }
   10529 
   10530     private static boolean isExternal(PackageSetting ps) {
   10531         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
   10532     }
   10533 
   10534     private static boolean isExternal(ApplicationInfo info) {
   10535         return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
   10536     }
   10537 
   10538     private static boolean isSystemApp(PackageParser.Package pkg) {
   10539         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   10540     }
   10541 
   10542     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
   10543         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
   10544     }
   10545 
   10546     private static boolean isSystemApp(ApplicationInfo info) {
   10547         return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
   10548     }
   10549 
   10550     private static boolean isSystemApp(PackageSetting ps) {
   10551         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
   10552     }
   10553 
   10554     private static boolean isUpdatedSystemApp(PackageSetting ps) {
   10555         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
   10556     }
   10557 
   10558     private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
   10559         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
   10560     }
   10561 
   10562     private static boolean isUpdatedSystemApp(ApplicationInfo info) {
   10563         return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
   10564     }
   10565 
   10566     private int packageFlagsToInstallFlags(PackageSetting ps) {
   10567         int installFlags = 0;
   10568         if (isExternal(ps)) {
   10569             installFlags |= PackageManager.INSTALL_EXTERNAL;
   10570         }
   10571         if (isForwardLocked(ps)) {
   10572             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
   10573         }
   10574         return installFlags;
   10575     }
   10576 
   10577     private void deleteTempPackageFiles() {
   10578         final FilenameFilter filter = new FilenameFilter() {
   10579             public boolean accept(File dir, String name) {
   10580                 return name.startsWith("vmdl") && name.endsWith(".tmp");
   10581             }
   10582         };
   10583         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
   10584             file.delete();
   10585         }
   10586     }
   10587 
   10588     @Override
   10589     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
   10590             int flags) {
   10591         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
   10592                 flags);
   10593     }
   10594 
   10595     @Override
   10596     public void deletePackage(final String packageName,
   10597             final IPackageDeleteObserver2 observer, final int userId, final int flags) {
   10598         mContext.enforceCallingOrSelfPermission(
   10599                 android.Manifest.permission.DELETE_PACKAGES, null);
   10600         final int uid = Binder.getCallingUid();
   10601         if (UserHandle.getUserId(uid) != userId) {
   10602             mContext.enforceCallingPermission(
   10603                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
   10604                     "deletePackage for user " + userId);
   10605         }
   10606         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
   10607             try {
   10608                 observer.onPackageDeleted(packageName,
   10609                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
   10610             } catch (RemoteException re) {
   10611             }
   10612             return;
   10613         }
   10614 
   10615         boolean uninstallBlocked = false;
   10616         if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
   10617             int[] users = sUserManager.getUserIds();
   10618             for (int i = 0; i < users.length; ++i) {
   10619                 if (getBlockUninstallForUser(packageName, users[i])) {
   10620                     uninstallBlocked = true;
   10621                     break;
   10622                 }
   10623             }
   10624         } else {
   10625             uninstallBlocked = getBlockUninstallForUser(packageName, userId);
   10626         }
   10627         if (uninstallBlocked) {
   10628             try {
   10629                 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
   10630                         null);
   10631             } catch (RemoteException re) {
   10632             }
   10633             return;
   10634         }
   10635 
   10636         if (DEBUG_REMOVE) {
   10637             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
   10638         }
   10639         // Queue up an async operation since the package deletion may take a little while.
   10640         mHandler.post(new Runnable() {
   10641             public void run() {
   10642                 mHandler.removeCallbacks(this);
   10643                 final int returnCode = deletePackageX(packageName, userId, flags);
   10644                 if (observer != null) {
   10645                     try {
   10646                         observer.onPackageDeleted(packageName, returnCode, null);
   10647                     } catch (RemoteException e) {
   10648                         Log.i(TAG, "Observer no longer exists.");
   10649                     } //end catch
   10650                 } //end if
   10651             } //end run
   10652         });
   10653     }
   10654 
   10655     private boolean isPackageDeviceAdmin(String packageName, int userId) {
   10656         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
   10657                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
   10658         try {
   10659             if (dpm != null) {
   10660                 if (dpm.isDeviceOwner(packageName)) {
   10661                     return true;
   10662                 }
   10663                 int[] users;
   10664                 if (userId == UserHandle.USER_ALL) {
   10665                     users = sUserManager.getUserIds();
   10666                 } else {
   10667                     users = new int[]{userId};
   10668                 }
   10669                 for (int i = 0; i < users.length; ++i) {
   10670                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
   10671                         return true;
   10672                     }
   10673                 }
   10674             }
   10675         } catch (RemoteException e) {
   10676         }
   10677         return false;
   10678     }
   10679 
   10680     /**
   10681      *  This method is an internal method that could be get invoked either
   10682      *  to delete an installed package or to clean up a failed installation.
   10683      *  After deleting an installed package, a broadcast is sent to notify any
   10684      *  listeners that the package has been installed. For cleaning up a failed
   10685      *  installation, the broadcast is not necessary since the package's
   10686      *  installation wouldn't have sent the initial broadcast either
   10687      *  The key steps in deleting a package are
   10688      *  deleting the package information in internal structures like mPackages,
   10689      *  deleting the packages base directories through installd
   10690      *  updating mSettings to reflect current status
   10691      *  persisting settings for later use
   10692      *  sending a broadcast if necessary
   10693      */
   10694     private int deletePackageX(String packageName, int userId, int flags) {
   10695         final PackageRemovedInfo info = new PackageRemovedInfo();
   10696         final boolean res;
   10697 
   10698         final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
   10699                 ? UserHandle.ALL : new UserHandle(userId);
   10700 
   10701         if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
   10702             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
   10703             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
   10704         }
   10705 
   10706         boolean removedForAllUsers = false;
   10707         boolean systemUpdate = false;
   10708 
   10709         // for the uninstall-updates case and restricted profiles, remember the per-
   10710         // userhandle installed state
   10711         int[] allUsers;
   10712         boolean[] perUserInstalled;
   10713         synchronized (mPackages) {
   10714             PackageSetting ps = mSettings.mPackages.get(packageName);
   10715             allUsers = sUserManager.getUserIds();
   10716             perUserInstalled = new boolean[allUsers.length];
   10717             for (int i = 0; i < allUsers.length; i++) {
   10718                 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
   10719             }
   10720         }
   10721 
   10722         synchronized (mInstallLock) {
   10723             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
   10724             res = deletePackageLI(packageName, removeForUser,
   10725                     true, allUsers, perUserInstalled,
   10726                     flags | REMOVE_CHATTY, info, true);
   10727             systemUpdate = info.isRemovedPackageSystemUpdate;
   10728             if (res && !systemUpdate && mPackages.get(packageName) == null) {
   10729                 removedForAllUsers = true;
   10730             }
   10731             if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
   10732                     + " removedForAllUsers=" + removedForAllUsers);
   10733         }
   10734 
   10735         if (res) {
   10736             info.sendBroadcast(true, systemUpdate, removedForAllUsers);
   10737 
   10738             // If the removed package was a system update, the old system package
   10739             // was re-enabled; we need to broadcast this information
   10740             if (systemUpdate) {
   10741                 Bundle extras = new Bundle(1);
   10742                 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
   10743                         ? info.removedAppId : info.uid);
   10744                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
   10745 
   10746                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
   10747                         extras, null, null, null);
   10748                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
   10749                         extras, null, null, null);
   10750                 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
   10751                         null, packageName, null, null);
   10752             }
   10753         }
   10754         // Force a gc here.
   10755         Runtime.getRuntime().gc();
   10756         // Delete the resources here after sending the broadcast to let
   10757         // other processes clean up before deleting resources.
   10758         if (info.args != null) {
   10759             synchronized (mInstallLock) {
   10760                 info.args.doPostDeleteLI(true);
   10761             }
   10762         }
   10763 
   10764         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
   10765     }
   10766 
   10767     static class PackageRemovedInfo {
   10768         String removedPackage;
   10769         int uid = -1;
   10770         int removedAppId = -1;
   10771         int[] removedUsers = null;
   10772         boolean isRemovedPackageSystemUpdate = false;
   10773         // Clean up resources deleted packages.
   10774         InstallArgs args = null;
   10775 
   10776         void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
   10777             Bundle extras = new Bundle(1);
   10778             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
   10779             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
   10780             if (replacing) {
   10781                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
   10782             }
   10783             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
   10784             if (removedPackage != null) {
   10785                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
   10786                         extras, null, null, removedUsers);
   10787                 if (fullRemove && !replacing) {
   10788                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
   10789                             extras, null, null, removedUsers);
   10790                 }
   10791             }
   10792             if (removedAppId >= 0) {
   10793                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
   10794                         removedUsers);
   10795             }
   10796         }
   10797     }
   10798 
   10799     /*
   10800      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
   10801      * flag is not set, the data directory is removed as well.
   10802      * make sure this flag is set for partially installed apps. If not its meaningless to
   10803      * delete a partially installed application.
   10804      */
   10805     private void removePackageDataLI(PackageSetting ps,
   10806             int[] allUserHandles, boolean[] perUserInstalled,
   10807             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
   10808         String packageName = ps.name;
   10809         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
   10810         removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
   10811         // Retrieve object to delete permissions for shared user later on
   10812         final PackageSetting deletedPs;
   10813         // reader
   10814         synchronized (mPackages) {
   10815             deletedPs = mSettings.mPackages.get(packageName);
   10816             if (outInfo != null) {
   10817                 outInfo.removedPackage = packageName;
   10818                 outInfo.removedUsers = deletedPs != null
   10819                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
   10820                         : null;
   10821             }
   10822         }
   10823         if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
   10824             removeDataDirsLI(packageName);
   10825             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
   10826         }
   10827         // writer
   10828         synchronized (mPackages) {
   10829             if (deletedPs != null) {
   10830                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
   10831                     if (outInfo != null) {
   10832                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
   10833                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
   10834                     }
   10835                     if (deletedPs != null) {
   10836                         updatePermissionsLPw(deletedPs.name, null, 0);
   10837                         if (deletedPs.sharedUser != null) {
   10838                             // remove permissions associated with package
   10839                             mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
   10840                         }
   10841                     }
   10842                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
   10843                 }
   10844                 // make sure to preserve per-user disabled state if this removal was just
   10845                 // a downgrade of a system app to the factory package
   10846                 if (allUserHandles != null && perUserInstalled != null) {
   10847                     if (DEBUG_REMOVE) {
   10848                         Slog.d(TAG, "Propagating install state across downgrade");
   10849                     }
   10850                     for (int i = 0; i < allUserHandles.length; i++) {
   10851                         if (DEBUG_REMOVE) {
   10852                             Slog.d(TAG, "    user " + allUserHandles[i]
   10853                                     + " => " + perUserInstalled[i]);
   10854                         }
   10855                         ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
   10856                     }
   10857                 }
   10858             }
   10859             // can downgrade to reader
   10860             if (writeSettings) {
   10861                 // Save settings now
   10862                 mSettings.writeLPr();
   10863             }
   10864         }
   10865         if (outInfo != null) {
   10866             // A user ID was deleted here. Go through all users and remove it
   10867             // from KeyStore.
   10868             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
   10869         }
   10870     }
   10871 
   10872     static boolean locationIsPrivileged(File path) {
   10873         try {
   10874             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
   10875                     .getCanonicalPath();
   10876             return path.getCanonicalPath().startsWith(privilegedAppDir);
   10877         } catch (IOException e) {
   10878             Slog.e(TAG, "Unable to access code path " + path);
   10879         }
   10880         return false;
   10881     }
   10882 
   10883     /*
   10884      * Tries to delete system package.
   10885      */
   10886     private boolean deleteSystemPackageLI(PackageSetting newPs,
   10887             int[] allUserHandles, boolean[] perUserInstalled,
   10888             int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
   10889         final boolean applyUserRestrictions
   10890                 = (allUserHandles != null) && (perUserInstalled != null);
   10891         PackageSetting disabledPs = null;
   10892         // Confirm if the system package has been updated
   10893         // An updated system app can be deleted. This will also have to restore
   10894         // the system pkg from system partition
   10895         // reader
   10896         synchronized (mPackages) {
   10897             disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
   10898         }
   10899         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
   10900                 + " disabledPs=" + disabledPs);
   10901         if (disabledPs == null) {
   10902             Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
   10903             return false;
   10904         } else if (DEBUG_REMOVE) {
   10905             Slog.d(TAG, "Deleting system pkg from data partition");
   10906         }
   10907         if (DEBUG_REMOVE) {
   10908             if (applyUserRestrictions) {
   10909                 Slog.d(TAG, "Remembering install states:");
   10910                 for (int i = 0; i < allUserHandles.length; i++) {
   10911                     Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
   10912                 }
   10913             }
   10914         }
   10915         // Delete the updated package
   10916         outInfo.isRemovedPackageSystemUpdate = true;
   10917         if (disabledPs.versionCode < newPs.versionCode) {
   10918             // Delete data for downgrades
   10919             flags &= ~PackageManager.DELETE_KEEP_DATA;
   10920         } else {
   10921             // Preserve data by setting flag
   10922             flags |= PackageManager.DELETE_KEEP_DATA;
   10923         }
   10924         boolean ret = deleteInstalledPackageLI(newPs, true, flags,
   10925                 allUserHandles, perUserInstalled, outInfo, writeSettings);
   10926         if (!ret) {
   10927             return false;
   10928         }
   10929         // writer
   10930         synchronized (mPackages) {
   10931             // Reinstate the old system package
   10932             mSettings.enableSystemPackageLPw(newPs.name);
   10933             // Remove any native libraries from the upgraded package.
   10934             NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
   10935         }
   10936         // Install the system package
   10937         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
   10938         int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
   10939         if (locationIsPrivileged(disabledPs.codePath)) {
   10940             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
   10941         }
   10942 
   10943         final PackageParser.Package newPkg;
   10944         try {
   10945             newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
   10946         } catch (PackageManagerException e) {
   10947             Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
   10948             return false;
   10949         }
   10950 
   10951         // writer
   10952         synchronized (mPackages) {
   10953             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
   10954             updatePermissionsLPw(newPkg.packageName, newPkg,
   10955                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
   10956             if (applyUserRestrictions) {
   10957                 if (DEBUG_REMOVE) {
   10958                     Slog.d(TAG, "Propagating install state across reinstall");
   10959                 }
   10960                 for (int i = 0; i < allUserHandles.length; i++) {
   10961                     if (DEBUG_REMOVE) {
   10962                         Slog.d(TAG, "    user " + allUserHandles[i]
   10963                                 + " => " + perUserInstalled[i]);
   10964                     }
   10965                     ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
   10966                 }
   10967                 // Regardless of writeSettings we need to ensure that this restriction
   10968                 // state propagation is persisted
   10969                 mSettings.writeAllUsersPackageRestrictionsLPr();
   10970             }
   10971             // can downgrade to reader here
   10972             if (writeSettings) {
   10973                 mSettings.writeLPr();
   10974             }
   10975         }
   10976         return true;
   10977     }
   10978 
   10979     private boolean deleteInstalledPackageLI(PackageSetting ps,
   10980             boolean deleteCodeAndResources, int flags,
   10981             int[] allUserHandles, boolean[] perUserInstalled,
   10982             PackageRemovedInfo outInfo, boolean writeSettings) {
   10983         if (outInfo != null) {
   10984             outInfo.uid = ps.appId;
   10985         }
   10986 
   10987         // Delete package data from internal structures and also remove data if flag is set
   10988         removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
   10989 
   10990         // Delete application code and resources
   10991         if (deleteCodeAndResources && (outInfo != null)) {
   10992             outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
   10993                     ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
   10994                     getAppDexInstructionSets(ps));
   10995             if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
   10996         }
   10997         return true;
   10998     }
   10999 
   11000     @Override
   11001     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
   11002             int userId) {
   11003         mContext.enforceCallingOrSelfPermission(
   11004                 android.Manifest.permission.DELETE_PACKAGES, null);
   11005         synchronized (mPackages) {
   11006             PackageSetting ps = mSettings.mPackages.get(packageName);
   11007             if (ps == null) {
   11008                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
   11009                 return false;
   11010             }
   11011             if (!ps.getInstalled(userId)) {
   11012                 // Can't block uninstall for an app that is not installed or enabled.
   11013                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
   11014                 return false;
   11015             }
   11016             ps.setBlockUninstall(blockUninstall, userId);
   11017             mSettings.writePackageRestrictionsLPr(userId);
   11018         }
   11019         return true;
   11020     }
   11021 
   11022     @Override
   11023     public boolean getBlockUninstallForUser(String packageName, int userId) {
   11024         synchronized (mPackages) {
   11025             PackageSetting ps = mSettings.mPackages.get(packageName);
   11026             if (ps == null) {
   11027                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
   11028                 return false;
   11029             }
   11030             return ps.getBlockUninstall(userId);
   11031         }
   11032     }
   11033 
   11034     /*
   11035      * This method handles package deletion in general
   11036      */
   11037     private boolean deletePackageLI(String packageName, UserHandle user,
   11038             boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
   11039             int flags, PackageRemovedInfo outInfo,
   11040             boolean writeSettings) {
   11041         if (packageName == null) {
   11042             Slog.w(TAG, "Attempt to delete null packageName.");
   11043             return false;
   11044         }
   11045         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
   11046         PackageSetting ps;
   11047         boolean dataOnly = false;
   11048         int removeUser = -1;
   11049         int appId = -1;
   11050         synchronized (mPackages) {
   11051             ps = mSettings.mPackages.get(packageName);
   11052             if (ps == null) {
   11053                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
   11054                 return false;
   11055             }
   11056             if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
   11057                     && user.getIdentifier() != UserHandle.USER_ALL) {
   11058                 // The caller is asking that the package only be deleted for a single
   11059                 // user.  To do this, we just mark its uninstalled state and delete
   11060                 // its data.  If this is a system app, we only allow this to happen if
   11061                 // they have set the special DELETE_SYSTEM_APP which requests different
   11062                 // semantics than normal for uninstalling system apps.
   11063                 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
   11064                 ps.setUserState(user.getIdentifier(),
   11065                         COMPONENT_ENABLED_STATE_DEFAULT,
   11066                         false, //installed
   11067                         true,  //stopped
   11068                         true,  //notLaunched
   11069                         false, //hidden
   11070                         null, null, null,
   11071                         false // blockUninstall
   11072                         );
   11073                 if (!isSystemApp(ps)) {
   11074                     if (ps.isAnyInstalled(sUserManager.getUserIds())) {
   11075                         // Other user still have this package installed, so all
   11076                         // we need to do is clear this user's data and save that
   11077                         // it is uninstalled.
   11078                         if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
   11079                         removeUser = user.getIdentifier();
   11080                         appId = ps.appId;
   11081                         mSettings.writePackageRestrictionsLPr(removeUser);
   11082                     } else {
   11083                         // We need to set it back to 'installed' so the uninstall
   11084                         // broadcasts will be sent correctly.
   11085                         if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
   11086                         ps.setInstalled(true, user.getIdentifier());
   11087                     }
   11088                 } else {
   11089                     // This is a system app, so we assume that the
   11090                     // other users still have this package installed, so all
   11091                     // we need to do is clear this user's data and save that
   11092                     // it is uninstalled.
   11093                     if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
   11094                     removeUser = user.getIdentifier();
   11095                     appId = ps.appId;
   11096                     mSettings.writePackageRestrictionsLPr(removeUser);
   11097                 }
   11098             }
   11099         }
   11100 
   11101         if (removeUser >= 0) {
   11102             // From above, we determined that we are deleting this only
   11103             // for a single user.  Continue the work here.
   11104             if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
   11105             if (outInfo != null) {
   11106                 outInfo.removedPackage = packageName;
   11107                 outInfo.removedAppId = appId;
   11108                 outInfo.removedUsers = new int[] {removeUser};
   11109             }
   11110             mInstaller.clearUserData(packageName, removeUser);
   11111             removeKeystoreDataIfNeeded(removeUser, appId);
   11112             schedulePackageCleaning(packageName, removeUser, false);
   11113             return true;
   11114         }
   11115 
   11116         if (dataOnly) {
   11117             // Delete application data first
   11118             if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
   11119             removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
   11120             return true;
   11121         }
   11122 
   11123         boolean ret = false;
   11124         if (isSystemApp(ps)) {
   11125             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
   11126             // When an updated system application is deleted we delete the existing resources as well and
   11127             // fall back to existing code in system partition
   11128             ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
   11129                     flags, outInfo, writeSettings);
   11130         } else {
   11131             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
   11132             // Kill application pre-emptively especially for apps on sd.
   11133             killApplication(packageName, ps.appId, "uninstall pkg");
   11134             ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
   11135                     allUserHandles, perUserInstalled,
   11136                     outInfo, writeSettings);
   11137         }
   11138 
   11139         return ret;
   11140     }
   11141 
   11142     private final class ClearStorageConnection implements ServiceConnection {
   11143         IMediaContainerService mContainerService;
   11144 
   11145         @Override
   11146         public void onServiceConnected(ComponentName name, IBinder service) {
   11147             synchronized (this) {
   11148                 mContainerService = IMediaContainerService.Stub.asInterface(service);
   11149                 notifyAll();
   11150             }
   11151         }
   11152 
   11153         @Override
   11154         public void onServiceDisconnected(ComponentName name) {
   11155         }
   11156     }
   11157 
   11158     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
   11159         final boolean mounted;
   11160         if (Environment.isExternalStorageEmulated()) {
   11161             mounted = true;
   11162         } else {
   11163             final String status = Environment.getExternalStorageState();
   11164 
   11165             mounted = status.equals(Environment.MEDIA_MOUNTED)
   11166                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
   11167         }
   11168 
   11169         if (!mounted) {
   11170             return;
   11171         }
   11172 
   11173         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
   11174         int[] users;
   11175         if (userId == UserHandle.USER_ALL) {
   11176             users = sUserManager.getUserIds();
   11177         } else {
   11178             users = new int[] { userId };
   11179         }
   11180         final ClearStorageConnection conn = new ClearStorageConnection();
   11181         if (mContext.bindServiceAsUser(
   11182                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
   11183             try {
   11184                 for (int curUser : users) {
   11185                     long timeout = SystemClock.uptimeMillis() + 5000;
   11186                     synchronized (conn) {
   11187                         long now = SystemClock.uptimeMillis();
   11188                         while (conn.mContainerService == null && now < timeout) {
   11189                             try {
   11190                                 conn.wait(timeout - now);
   11191                             } catch (InterruptedException e) {
   11192                             }
   11193                         }
   11194                     }
   11195                     if (conn.mContainerService == null) {
   11196                         return;
   11197                     }
   11198 
   11199                     final UserEnvironment userEnv = new UserEnvironment(curUser);
   11200                     clearDirectory(conn.mContainerService,
   11201                             userEnv.buildExternalStorageAppCacheDirs(packageName));
   11202                     if (allData) {
   11203                         clearDirectory(conn.mContainerService,
   11204                                 userEnv.buildExternalStorageAppDataDirs(packageName));
   11205                         clearDirectory(conn.mContainerService,
   11206                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
   11207                     }
   11208                 }
   11209             } finally {
   11210                 mContext.unbindService(conn);
   11211             }
   11212         }
   11213     }
   11214 
   11215     @Override
   11216     public void clearApplicationUserData(final String packageName,
   11217             final IPackageDataObserver observer, final int userId) {
   11218         mContext.enforceCallingOrSelfPermission(
   11219                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
   11220         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
   11221         // Queue up an async operation since the package deletion may take a little while.
   11222         mHandler.post(new Runnable() {
   11223             public void run() {
   11224                 mHandler.removeCallbacks(this);
   11225                 final boolean succeeded;
   11226                 synchronized (mInstallLock) {
   11227                     succeeded = clearApplicationUserDataLI(packageName, userId);
   11228                 }
   11229                 clearExternalStorageDataSync(packageName, userId, true);
   11230                 if (succeeded) {
   11231                     // invoke DeviceStorageMonitor's update method to clear any notifications
   11232                     DeviceStorageMonitorInternal
   11233                             dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
   11234                     if (dsm != null) {
   11235                         dsm.checkMemory();
   11236                     }
   11237                 }
   11238                 if(observer != null) {
   11239                     try {
   11240                         observer.onRemoveCompleted(packageName, succeeded);
   11241                     } catch (RemoteException e) {
   11242                         Log.i(TAG, "Observer no longer exists.");
   11243                     }
   11244                 } //end if observer
   11245             } //end run
   11246         });
   11247     }
   11248 
   11249     private boolean clearApplicationUserDataLI(String packageName, int userId) {
   11250         if (packageName == null) {
   11251             Slog.w(TAG, "Attempt to delete null packageName.");
   11252             return false;
   11253         }
   11254 
   11255         // Try finding details about the requested package
   11256         PackageParser.Package pkg;
   11257         synchronized (mPackages) {
   11258             pkg = mPackages.get(packageName);
   11259             if (pkg == null) {
   11260                 final PackageSetting ps = mSettings.mPackages.get(packageName);
   11261                 if (ps != null) {
   11262                     pkg = ps.pkg;
   11263                 }
   11264             }
   11265         }
   11266 
   11267         if (pkg == null) {
   11268             Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
   11269         }
   11270 
   11271         // Always delete data directories for package, even if we found no other
   11272         // record of app. This helps users recover from UID mismatches without
   11273         // resorting to a full data wipe.
   11274         int retCode = mInstaller.clearUserData(packageName, userId);
   11275         if (retCode < 0) {
   11276             Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
   11277             return false;
   11278         }
   11279 
   11280         if (pkg == null) {
   11281             return false;
   11282         }
   11283 
   11284         if (pkg != null && pkg.applicationInfo != null) {
   11285             final int appId = pkg.applicationInfo.uid;
   11286             removeKeystoreDataIfNeeded(userId, appId);
   11287         }
   11288 
   11289         // Create a native library symlink only if we have native libraries
   11290         // and if the native libraries are 32 bit libraries. We do not provide
   11291         // this symlink for 64 bit libraries.
   11292         if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
   11293                 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
   11294             final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
   11295             if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
   11296                 Slog.w(TAG, "Failed linking native library dir");
   11297                 return false;
   11298             }
   11299         }
   11300 
   11301         return true;
   11302     }
   11303 
   11304     /**
   11305      * Remove entries from the keystore daemon. Will only remove it if the
   11306      * {@code appId} is valid.
   11307      */
   11308     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
   11309         if (appId < 0) {
   11310             return;
   11311         }
   11312 
   11313         final KeyStore keyStore = KeyStore.getInstance();
   11314         if (keyStore != null) {
   11315             if (userId == UserHandle.USER_ALL) {
   11316                 for (final int individual : sUserManager.getUserIds()) {
   11317                     keyStore.clearUid(UserHandle.getUid(individual, appId));
   11318                 }
   11319             } else {
   11320                 keyStore.clearUid(UserHandle.getUid(userId, appId));
   11321             }
   11322         } else {
   11323             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
   11324         }
   11325     }
   11326 
   11327     @Override
   11328     public void deleteApplicationCacheFiles(final String packageName,
   11329             final IPackageDataObserver observer) {
   11330         mContext.enforceCallingOrSelfPermission(
   11331                 android.Manifest.permission.DELETE_CACHE_FILES, null);
   11332         // Queue up an async operation since the package deletion may take a little while.
   11333         final int userId = UserHandle.getCallingUserId();
   11334         mHandler.post(new Runnable() {
   11335             public void run() {
   11336                 mHandler.removeCallbacks(this);
   11337                 final boolean succeded;
   11338                 synchronized (mInstallLock) {
   11339                     succeded = deleteApplicationCacheFilesLI(packageName, userId);
   11340                 }
   11341                 clearExternalStorageDataSync(packageName, userId, false);
   11342                 if(observer != null) {
   11343                     try {
   11344                         observer.onRemoveCompleted(packageName, succeded);
   11345                     } catch (RemoteException e) {
   11346                         Log.i(TAG, "Observer no longer exists.");
   11347                     }
   11348                 } //end if observer
   11349             } //end run
   11350         });
   11351     }
   11352 
   11353     private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
   11354         if (packageName == null) {
   11355             Slog.w(TAG, "Attempt to delete null packageName.");
   11356             return false;
   11357         }
   11358         PackageParser.Package p;
   11359         synchronized (mPackages) {
   11360             p = mPackages.get(packageName);
   11361         }
   11362         if (p == null) {
   11363             Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
   11364             return false;
   11365         }
   11366         final ApplicationInfo applicationInfo = p.applicationInfo;
   11367         if (applicationInfo == null) {
   11368             Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
   11369             return false;
   11370         }
   11371         int retCode = mInstaller.deleteCacheFiles(packageName, userId);
   11372         if (retCode < 0) {
   11373             Slog.w(TAG, "Couldn't remove cache files for package: "
   11374                        + packageName + " u" + userId);
   11375             return false;
   11376         }
   11377         return true;
   11378     }
   11379 
   11380     @Override
   11381     public void getPackageSizeInfo(final String packageName, int userHandle,
   11382             final IPackageStatsObserver observer) {
   11383         mContext.enforceCallingOrSelfPermission(
   11384                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
   11385         if (packageName == null) {
   11386             throw new IllegalArgumentException("Attempt to get size of null packageName");
   11387         }
   11388 
   11389         PackageStats stats = new PackageStats(packageName, userHandle);
   11390 
   11391         /*
   11392          * Queue up an async operation since the package measurement may take a
   11393          * little while.
   11394          */
   11395         Message msg = mHandler.obtainMessage(INIT_COPY);
   11396         msg.obj = new MeasureParams(stats, observer);
   11397         mHandler.sendMessage(msg);
   11398     }
   11399 
   11400     private boolean getPackageSizeInfoLI(String packageName, int userHandle,
   11401             PackageStats pStats) {
   11402         if (packageName == null) {
   11403             Slog.w(TAG, "Attempt to get size of null packageName.");
   11404             return false;
   11405         }
   11406         PackageParser.Package p;
   11407         boolean dataOnly = false;
   11408         String libDirRoot = null;
   11409         String asecPath = null;
   11410         PackageSetting ps = null;
   11411         synchronized (mPackages) {
   11412             p = mPackages.get(packageName);
   11413             ps = mSettings.mPackages.get(packageName);
   11414             if(p == null) {
   11415                 dataOnly = true;
   11416                 if((ps == null) || (ps.pkg == null)) {
   11417                     Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
   11418                     return false;
   11419                 }
   11420                 p = ps.pkg;
   11421             }
   11422             if (ps != null) {
   11423                 libDirRoot = ps.legacyNativeLibraryPathString;
   11424             }
   11425             if (p != null && (isExternal(p) || isForwardLocked(p))) {
   11426                 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
   11427                 if (secureContainerId != null) {
   11428                     asecPath = PackageHelper.getSdFilesystem(secureContainerId);
   11429                 }
   11430             }
   11431         }
   11432         String publicSrcDir = null;
   11433         if(!dataOnly) {
   11434             final ApplicationInfo applicationInfo = p.applicationInfo;
   11435             if (applicationInfo == null) {
   11436                 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
   11437                 return false;
   11438             }
   11439             if (isForwardLocked(p)) {
   11440                 publicSrcDir = applicationInfo.getBaseResourcePath();
   11441             }
   11442         }
   11443         // TODO: extend to measure size of split APKs
   11444         // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
   11445         // not just the first level.
   11446         // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
   11447         // just the primary.
   11448         String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
   11449         int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
   11450                 publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
   11451         if (res < 0) {
   11452             return false;
   11453         }
   11454 
   11455         // Fix-up for forward-locked applications in ASEC containers.
   11456         if (!isExternal(p)) {
   11457             pStats.codeSize += pStats.externalCodeSize;
   11458             pStats.externalCodeSize = 0L;
   11459         }
   11460 
   11461         return true;
   11462     }
   11463 
   11464 
   11465     @Override
   11466     public void addPackageToPreferred(String packageName) {
   11467         Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
   11468     }
   11469 
   11470     @Override
   11471     public void removePackageFromPreferred(String packageName) {
   11472         Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
   11473     }
   11474 
   11475     @Override
   11476     public List<PackageInfo> getPreferredPackages(int flags) {
   11477         return new ArrayList<PackageInfo>();
   11478     }
   11479 
   11480     private int getUidTargetSdkVersionLockedLPr(int uid) {
   11481         Object obj = mSettings.getUserIdLPr(uid);
   11482         if (obj instanceof SharedUserSetting) {
   11483             final SharedUserSetting sus = (SharedUserSetting) obj;
   11484             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
   11485             final Iterator<PackageSetting> it = sus.packages.iterator();
   11486             while (it.hasNext()) {
   11487                 final PackageSetting ps = it.next();
   11488                 if (ps.pkg != null) {
   11489                     int v = ps.pkg.applicationInfo.targetSdkVersion;
   11490                     if (v < vers) vers = v;
   11491                 }
   11492             }
   11493             return vers;
   11494         } else if (obj instanceof PackageSetting) {
   11495             final PackageSetting ps = (PackageSetting) obj;
   11496             if (ps.pkg != null) {
   11497                 return ps.pkg.applicationInfo.targetSdkVersion;
   11498             }
   11499         }
   11500         return Build.VERSION_CODES.CUR_DEVELOPMENT;
   11501     }
   11502 
   11503     @Override
   11504     public void addPreferredActivity(IntentFilter filter, int match,
   11505             ComponentName[] set, ComponentName activity, int userId) {
   11506         addPreferredActivityInternal(filter, match, set, activity, true, userId,
   11507                 "Adding preferred");
   11508     }
   11509 
   11510     private void addPreferredActivityInternal(IntentFilter filter, int match,
   11511             ComponentName[] set, ComponentName activity, boolean always, int userId,
   11512             String opname) {
   11513         // writer
   11514         int callingUid = Binder.getCallingUid();
   11515         enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
   11516         if (filter.countActions() == 0) {
   11517             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
   11518             return;
   11519         }
   11520         synchronized (mPackages) {
   11521             if (mContext.checkCallingOrSelfPermission(
   11522                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
   11523                     != PackageManager.PERMISSION_GRANTED) {
   11524                 if (getUidTargetSdkVersionLockedLPr(callingUid)
   11525                         < Build.VERSION_CODES.FROYO) {
   11526                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
   11527                             + callingUid);
   11528                     return;
   11529                 }
   11530                 mContext.enforceCallingOrSelfPermission(
   11531                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   11532             }
   11533 
   11534             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
   11535             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
   11536                     + userId + ":");
   11537             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   11538             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
   11539             mSettings.writePackageRestrictionsLPr(userId);
   11540         }
   11541     }
   11542 
   11543     @Override
   11544     public void replacePreferredActivity(IntentFilter filter, int match,
   11545             ComponentName[] set, ComponentName activity, int userId) {
   11546         if (filter.countActions() != 1) {
   11547             throw new IllegalArgumentException(
   11548                     "replacePreferredActivity expects filter to have only 1 action.");
   11549         }
   11550         if (filter.countDataAuthorities() != 0
   11551                 || filter.countDataPaths() != 0
   11552                 || filter.countDataSchemes() > 1
   11553                 || filter.countDataTypes() != 0) {
   11554             throw new IllegalArgumentException(
   11555                     "replacePreferredActivity expects filter to have no data authorities, " +
   11556                     "paths, or types; and at most one scheme.");
   11557         }
   11558 
   11559         final int callingUid = Binder.getCallingUid();
   11560         enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
   11561         synchronized (mPackages) {
   11562             if (mContext.checkCallingOrSelfPermission(
   11563                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
   11564                     != PackageManager.PERMISSION_GRANTED) {
   11565                 if (getUidTargetSdkVersionLockedLPr(callingUid)
   11566                         < Build.VERSION_CODES.FROYO) {
   11567                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
   11568                             + Binder.getCallingUid());
   11569                     return;
   11570                 }
   11571                 mContext.enforceCallingOrSelfPermission(
   11572                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   11573             }
   11574 
   11575             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   11576             if (pir != null) {
   11577                 // Get all of the existing entries that exactly match this filter.
   11578                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
   11579                 if (existing != null && existing.size() == 1) {
   11580                     PreferredActivity cur = existing.get(0);
   11581                     if (DEBUG_PREFERRED) {
   11582                         Slog.i(TAG, "Checking replace of preferred:");
   11583                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   11584                         if (!cur.mPref.mAlways) {
   11585                             Slog.i(TAG, "  -- CUR; not mAlways!");
   11586                         } else {
   11587                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
   11588                             Slog.i(TAG, "  -- CUR: mSet="
   11589                                     + Arrays.toString(cur.mPref.mSetComponents));
   11590                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
   11591                             Slog.i(TAG, "  -- NEW: mMatch="
   11592                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
   11593                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
   11594                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
   11595                         }
   11596                     }
   11597                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
   11598                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
   11599                             && cur.mPref.sameSet(set)) {
   11600                         // Setting the preferred activity to what it happens to be already
   11601                         if (DEBUG_PREFERRED) {
   11602                             Slog.i(TAG, "Replacing with same preferred activity "
   11603                                     + cur.mPref.mShortComponent + " for user "
   11604                                     + userId + ":");
   11605                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   11606                         }
   11607                         return;
   11608                     }
   11609                 }
   11610 
   11611                 if (existing != null) {
   11612                     if (DEBUG_PREFERRED) {
   11613                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
   11614                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   11615                     }
   11616                     for (int i = 0; i < existing.size(); i++) {
   11617                         PreferredActivity pa = existing.get(i);
   11618                         if (DEBUG_PREFERRED) {
   11619                             Slog.i(TAG, "Removing existing preferred activity "
   11620                                     + pa.mPref.mComponent + ":");
   11621                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
   11622                         }
   11623                         pir.removeFilter(pa);
   11624                     }
   11625                 }
   11626             }
   11627             addPreferredActivityInternal(filter, match, set, activity, true, userId,
   11628                     "Replacing preferred");
   11629         }
   11630     }
   11631 
   11632     @Override
   11633     public void clearPackagePreferredActivities(String packageName) {
   11634         final int uid = Binder.getCallingUid();
   11635         // writer
   11636         synchronized (mPackages) {
   11637             PackageParser.Package pkg = mPackages.get(packageName);
   11638             if (pkg == null || pkg.applicationInfo.uid != uid) {
   11639                 if (mContext.checkCallingOrSelfPermission(
   11640                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
   11641                         != PackageManager.PERMISSION_GRANTED) {
   11642                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
   11643                             < Build.VERSION_CODES.FROYO) {
   11644                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
   11645                                 + Binder.getCallingUid());
   11646                         return;
   11647                     }
   11648                     mContext.enforceCallingOrSelfPermission(
   11649                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   11650                 }
   11651             }
   11652 
   11653             int user = UserHandle.getCallingUserId();
   11654             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
   11655                 mSettings.writePackageRestrictionsLPr(user);
   11656                 scheduleWriteSettingsLocked();
   11657             }
   11658         }
   11659     }
   11660 
   11661     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
   11662     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
   11663         ArrayList<PreferredActivity> removed = null;
   11664         boolean changed = false;
   11665         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
   11666             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
   11667             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
   11668             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
   11669                 continue;
   11670             }
   11671             Iterator<PreferredActivity> it = pir.filterIterator();
   11672             while (it.hasNext()) {
   11673                 PreferredActivity pa = it.next();
   11674                 // Mark entry for removal only if it matches the package name
   11675                 // and the entry is of type "always".
   11676                 if (packageName == null ||
   11677                         (pa.mPref.mComponent.getPackageName().equals(packageName)
   11678                                 && pa.mPref.mAlways)) {
   11679                     if (removed == null) {
   11680                         removed = new ArrayList<PreferredActivity>();
   11681                     }
   11682                     removed.add(pa);
   11683                 }
   11684             }
   11685             if (removed != null) {
   11686                 for (int j=0; j<removed.size(); j++) {
   11687                     PreferredActivity pa = removed.get(j);
   11688                     pir.removeFilter(pa);
   11689                 }
   11690                 changed = true;
   11691             }
   11692         }
   11693         return changed;
   11694     }
   11695 
   11696     @Override
   11697     public void resetPreferredActivities(int userId) {
   11698         /* TODO: Actually use userId. Why is it being passed in? */
   11699         mContext.enforceCallingOrSelfPermission(
   11700                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
   11701         // writer
   11702         synchronized (mPackages) {
   11703             int user = UserHandle.getCallingUserId();
   11704             clearPackagePreferredActivitiesLPw(null, user);
   11705             mSettings.readDefaultPreferredAppsLPw(this, user);
   11706             mSettings.writePackageRestrictionsLPr(user);
   11707             scheduleWriteSettingsLocked();
   11708         }
   11709     }
   11710 
   11711     @Override
   11712     public int getPreferredActivities(List<IntentFilter> outFilters,
   11713             List<ComponentName> outActivities, String packageName) {
   11714 
   11715         int num = 0;
   11716         final int userId = UserHandle.getCallingUserId();
   11717         // reader
   11718         synchronized (mPackages) {
   11719             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
   11720             if (pir != null) {
   11721                 final Iterator<PreferredActivity> it = pir.filterIterator();
   11722                 while (it.hasNext()) {
   11723                     final PreferredActivity pa = it.next();
   11724                     if (packageName == null
   11725                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
   11726                                     && pa.mPref.mAlways)) {
   11727                         if (outFilters != null) {
   11728                             outFilters.add(new IntentFilter(pa));
   11729                         }
   11730                         if (outActivities != null) {
   11731                             outActivities.add(pa.mPref.mComponent);
   11732                         }
   11733                     }
   11734                 }
   11735             }
   11736         }
   11737 
   11738         return num;
   11739     }
   11740 
   11741     @Override
   11742     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
   11743             int userId) {
   11744         int callingUid = Binder.getCallingUid();
   11745         if (callingUid != Process.SYSTEM_UID) {
   11746             throw new SecurityException(
   11747                     "addPersistentPreferredActivity can only be run by the system");
   11748         }
   11749         if (filter.countActions() == 0) {
   11750             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
   11751             return;
   11752         }
   11753         synchronized (mPackages) {
   11754             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
   11755                     " :");
   11756             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
   11757             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
   11758                     new PersistentPreferredActivity(filter, activity));
   11759             mSettings.writePackageRestrictionsLPr(userId);
   11760         }
   11761     }
   11762 
   11763     @Override
   11764     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
   11765         int callingUid = Binder.getCallingUid();
   11766         if (callingUid != Process.SYSTEM_UID) {
   11767             throw new SecurityException(
   11768                     "clearPackagePersistentPreferredActivities can only be run by the system");
   11769         }
   11770         ArrayList<PersistentPreferredActivity> removed = null;
   11771         boolean changed = false;
   11772         synchronized (mPackages) {
   11773             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
   11774                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
   11775                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
   11776                         .valueAt(i);
   11777                 if (userId != thisUserId) {
   11778                     continue;
   11779                 }
   11780                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
   11781                 while (it.hasNext()) {
   11782                     PersistentPreferredActivity ppa = it.next();
   11783                     // Mark entry for removal only if it matches the package name.
   11784                     if (ppa.mComponent.getPackageName().equals(packageName)) {
   11785                         if (removed == null) {
   11786                             removed = new ArrayList<PersistentPreferredActivity>();
   11787                         }
   11788                         removed.add(ppa);
   11789                     }
   11790                 }
   11791                 if (removed != null) {
   11792                     for (int j=0; j<removed.size(); j++) {
   11793                         PersistentPreferredActivity ppa = removed.get(j);
   11794                         ppir.removeFilter(ppa);
   11795                     }
   11796                     changed = true;
   11797                 }
   11798             }
   11799 
   11800             if (changed) {
   11801                 mSettings.writePackageRestrictionsLPr(userId);
   11802             }
   11803         }
   11804     }
   11805 
   11806     @Override
   11807     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
   11808             int ownerUserId, int sourceUserId, int targetUserId, int flags) {
   11809         mContext.enforceCallingOrSelfPermission(
   11810                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   11811         int callingUid = Binder.getCallingUid();
   11812         enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
   11813         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
   11814         if (intentFilter.countActions() == 0) {
   11815             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
   11816             return;
   11817         }
   11818         synchronized (mPackages) {
   11819             CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
   11820                     ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
   11821             mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
   11822             mSettings.writePackageRestrictionsLPr(sourceUserId);
   11823         }
   11824     }
   11825 
   11826     @Override
   11827     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
   11828             int ownerUserId) {
   11829         mContext.enforceCallingOrSelfPermission(
   11830                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
   11831         int callingUid = Binder.getCallingUid();
   11832         enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
   11833         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
   11834         int callingUserId = UserHandle.getUserId(callingUid);
   11835         synchronized (mPackages) {
   11836             CrossProfileIntentResolver resolver =
   11837                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
   11838             HashSet<CrossProfileIntentFilter> set =
   11839                     new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
   11840             for (CrossProfileIntentFilter filter : set) {
   11841                 if (filter.getOwnerPackage().equals(ownerPackage)
   11842                         && filter.getOwnerUserId() == callingUserId) {
   11843                     resolver.removeFilter(filter);
   11844                 }
   11845             }
   11846             mSettings.writePackageRestrictionsLPr(sourceUserId);
   11847         }
   11848     }
   11849 
   11850     // Enforcing that callingUid is owning pkg on userId
   11851     private void enforceOwnerRights(String pkg, int userId, int callingUid) {
   11852         // The system owns everything.
   11853         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
   11854             return;
   11855         }
   11856         int callingUserId = UserHandle.getUserId(callingUid);
   11857         if (callingUserId != userId) {
   11858             throw new SecurityException("calling uid " + callingUid
   11859                     + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
   11860                     + callingUserId);
   11861         }
   11862         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
   11863         if (pi == null) {
   11864             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
   11865                     + callingUserId);
   11866         }
   11867         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
   11868             throw new SecurityException("Calling uid " + callingUid
   11869                     + " does not own package " + pkg);
   11870         }
   11871     }
   11872 
   11873     @Override
   11874     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
   11875         Intent intent = new Intent(Intent.ACTION_MAIN);
   11876         intent.addCategory(Intent.CATEGORY_HOME);
   11877 
   11878         final int callingUserId = UserHandle.getCallingUserId();
   11879         List<ResolveInfo> list = queryIntentActivities(intent, null,
   11880                 PackageManager.GET_META_DATA, callingUserId);
   11881         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
   11882                 true, false, false, callingUserId);
   11883 
   11884         allHomeCandidates.clear();
   11885         if (list != null) {
   11886             for (ResolveInfo ri : list) {
   11887                 allHomeCandidates.add(ri);
   11888             }
   11889         }
   11890         return (preferred == null || preferred.activityInfo == null)
   11891                 ? null
   11892                 : new ComponentName(preferred.activityInfo.packageName,
   11893                         preferred.activityInfo.name);
   11894     }
   11895 
   11896     @Override
   11897     public void setApplicationEnabledSetting(String appPackageName,
   11898             int newState, int flags, int userId, String callingPackage) {
   11899         if (!sUserManager.exists(userId)) return;
   11900         if (callingPackage == null) {
   11901             callingPackage = Integer.toString(Binder.getCallingUid());
   11902         }
   11903         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
   11904     }
   11905 
   11906     @Override
   11907     public void setComponentEnabledSetting(ComponentName componentName,
   11908             int newState, int flags, int userId) {
   11909         if (!sUserManager.exists(userId)) return;
   11910         setEnabledSetting(componentName.getPackageName(),
   11911                 componentName.getClassName(), newState, flags, userId, null);
   11912     }
   11913 
   11914     private void setEnabledSetting(final String packageName, String className, int newState,
   11915             final int flags, int userId, String callingPackage) {
   11916         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
   11917               || newState == COMPONENT_ENABLED_STATE_ENABLED
   11918               || newState == COMPONENT_ENABLED_STATE_DISABLED
   11919               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
   11920               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
   11921             throw new IllegalArgumentException("Invalid new component state: "
   11922                     + newState);
   11923         }
   11924         PackageSetting pkgSetting;
   11925         final int uid = Binder.getCallingUid();
   11926         final int permission = mContext.checkCallingOrSelfPermission(
   11927                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
   11928         enforceCrossUserPermission(uid, userId, false, true, "set enabled");
   11929         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
   11930         boolean sendNow = false;
   11931         boolean isApp = (className == null);
   11932         String componentName = isApp ? packageName : className;
   11933         int packageUid = -1;
   11934         ArrayList<String> components;
   11935 
   11936         // writer
   11937         synchronized (mPackages) {
   11938             pkgSetting = mSettings.mPackages.get(packageName);
   11939             if (pkgSetting == null) {
   11940                 if (className == null) {
   11941                     throw new IllegalArgumentException(
   11942                             "Unknown package: " + packageName);
   11943                 }
   11944                 throw new IllegalArgumentException(
   11945                         "Unknown component: " + packageName
   11946                         + "/" + className);
   11947             }
   11948             // Allow root and verify that userId is not being specified by a different user
   11949             if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
   11950                 throw new SecurityException(
   11951                         "Permission Denial: attempt to change component state from pid="
   11952                         + Binder.getCallingPid()
   11953                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
   11954             }
   11955             if (className == null) {
   11956                 // We're dealing with an application/package level state change
   11957                 if (pkgSetting.getEnabled(userId) == newState) {
   11958                     // Nothing to do
   11959                     return;
   11960                 }
   11961                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
   11962                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
   11963                     // Don't care about who enables an app.
   11964                     callingPackage = null;
   11965                 }
   11966                 pkgSetting.setEnabled(newState, userId, callingPackage);
   11967                 // pkgSetting.pkg.mSetEnabled = newState;
   11968             } else {
   11969                 // We're dealing with a component level state change
   11970                 // First, verify that this is a valid class name.
   11971                 PackageParser.Package pkg = pkgSetting.pkg;
   11972                 if (pkg == null || !pkg.hasComponentClassName(className)) {
   11973                     if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
   11974                         throw new IllegalArgumentException("Component class " + className
   11975                                 + " does not exist in " + packageName);
   11976                     } else {
   11977                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
   11978                                 + className + " does not exist in " + packageName);
   11979                     }
   11980                 }
   11981                 switch (newState) {
   11982                 case COMPONENT_ENABLED_STATE_ENABLED:
   11983                     if (!pkgSetting.enableComponentLPw(className, userId)) {
   11984                         return;
   11985                     }
   11986                     break;
   11987                 case COMPONENT_ENABLED_STATE_DISABLED:
   11988                     if (!pkgSetting.disableComponentLPw(className, userId)) {
   11989                         return;
   11990                     }
   11991                     break;
   11992                 case COMPONENT_ENABLED_STATE_DEFAULT:
   11993                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
   11994                         return;
   11995                     }
   11996                     break;
   11997                 default:
   11998                     Slog.e(TAG, "Invalid new component state: " + newState);
   11999                     return;
   12000                 }
   12001             }
   12002             mSettings.writePackageRestrictionsLPr(userId);
   12003             components = mPendingBroadcasts.get(userId, packageName);
   12004             final boolean newPackage = components == null;
   12005             if (newPackage) {
   12006                 components = new ArrayList<String>();
   12007             }
   12008             if (!components.contains(componentName)) {
   12009                 components.add(componentName);
   12010             }
   12011             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
   12012                 sendNow = true;
   12013                 // Purge entry from pending broadcast list if another one exists already
   12014                 // since we are sending one right away.
   12015                 mPendingBroadcasts.remove(userId, packageName);
   12016             } else {
   12017                 if (newPackage) {
   12018                     mPendingBroadcasts.put(userId, packageName, components);
   12019                 }
   12020                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
   12021                     // Schedule a message
   12022                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
   12023                 }
   12024             }
   12025         }
   12026 
   12027         long callingId = Binder.clearCallingIdentity();
   12028         try {
   12029             if (sendNow) {
   12030                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
   12031                 sendPackageChangedBroadcast(packageName,
   12032                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
   12033             }
   12034         } finally {
   12035             Binder.restoreCallingIdentity(callingId);
   12036         }
   12037     }
   12038 
   12039     private void sendPackageChangedBroadcast(String packageName,
   12040             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
   12041         if (DEBUG_INSTALL)
   12042             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
   12043                     + componentNames);
   12044         Bundle extras = new Bundle(4);
   12045         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
   12046         String nameList[] = new String[componentNames.size()];
   12047         componentNames.toArray(nameList);
   12048         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
   12049         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
   12050         extras.putInt(Intent.EXTRA_UID, packageUid);
   12051         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
   12052                 new int[] {UserHandle.getUserId(packageUid)});
   12053     }
   12054 
   12055     @Override
   12056     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
   12057         if (!sUserManager.exists(userId)) return;
   12058         final int uid = Binder.getCallingUid();
   12059         final int permission = mContext.checkCallingOrSelfPermission(
   12060                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
   12061         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
   12062         enforceCrossUserPermission(uid, userId, true, true, "stop package");
   12063         // writer
   12064         synchronized (mPackages) {
   12065             if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
   12066                     uid, userId)) {
   12067                 scheduleWritePackageRestrictionsLocked(userId);
   12068             }
   12069         }
   12070     }
   12071 
   12072     @Override
   12073     public String getInstallerPackageName(String packageName) {
   12074         // reader
   12075         synchronized (mPackages) {
   12076             return mSettings.getInstallerPackageNameLPr(packageName);
   12077         }
   12078     }
   12079 
   12080     @Override
   12081     public int getApplicationEnabledSetting(String packageName, int userId) {
   12082         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
   12083         int uid = Binder.getCallingUid();
   12084         enforceCrossUserPermission(uid, userId, false, false, "get enabled");
   12085         // reader
   12086         synchronized (mPackages) {
   12087             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
   12088         }
   12089     }
   12090 
   12091     @Override
   12092     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
   12093         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
   12094         int uid = Binder.getCallingUid();
   12095         enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
   12096         // reader
   12097         synchronized (mPackages) {
   12098             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
   12099         }
   12100     }
   12101 
   12102     @Override
   12103     public void enterSafeMode() {
   12104         enforceSystemOrRoot("Only the system can request entering safe mode");
   12105 
   12106         if (!mSystemReady) {
   12107             mSafeMode = true;
   12108         }
   12109     }
   12110 
   12111     @Override
   12112     public void systemReady() {
   12113         mSystemReady = true;
   12114 
   12115         // Read the compatibilty setting when the system is ready.
   12116         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
   12117                 mContext.getContentResolver(),
   12118                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
   12119         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
   12120         if (DEBUG_SETTINGS) {
   12121             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
   12122         }
   12123 
   12124         synchronized (mPackages) {
   12125             // Verify that all of the preferred activity components actually
   12126             // exist.  It is possible for applications to be updated and at
   12127             // that point remove a previously declared activity component that
   12128             // had been set as a preferred activity.  We try to clean this up
   12129             // the next time we encounter that preferred activity, but it is
   12130             // possible for the user flow to never be able to return to that
   12131             // situation so here we do a sanity check to make sure we haven't
   12132             // left any junk around.
   12133             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
   12134             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
   12135                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
   12136                 removed.clear();
   12137                 for (PreferredActivity pa : pir.filterSet()) {
   12138                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
   12139                         removed.add(pa);
   12140                     }
   12141                 }
   12142                 if (removed.size() > 0) {
   12143                     for (int r=0; r<removed.size(); r++) {
   12144                         PreferredActivity pa = removed.get(r);
   12145                         Slog.w(TAG, "Removing dangling preferred activity: "
   12146                                 + pa.mPref.mComponent);
   12147                         pir.removeFilter(pa);
   12148                     }
   12149                     mSettings.writePackageRestrictionsLPr(
   12150                             mSettings.mPreferredActivities.keyAt(i));
   12151                 }
   12152             }
   12153         }
   12154         sUserManager.systemReady();
   12155 
   12156         // Kick off any messages waiting for system ready
   12157         if (mPostSystemReadyMessages != null) {
   12158             for (Message msg : mPostSystemReadyMessages) {
   12159                 msg.sendToTarget();
   12160             }
   12161             mPostSystemReadyMessages = null;
   12162         }
   12163     }
   12164 
   12165     @Override
   12166     public boolean isSafeMode() {
   12167         return mSafeMode;
   12168     }
   12169 
   12170     @Override
   12171     public boolean hasSystemUidErrors() {
   12172         return mHasSystemUidErrors;
   12173     }
   12174 
   12175     static String arrayToString(int[] array) {
   12176         StringBuffer buf = new StringBuffer(128);
   12177         buf.append('[');
   12178         if (array != null) {
   12179             for (int i=0; i<array.length; i++) {
   12180                 if (i > 0) buf.append(", ");
   12181                 buf.append(array[i]);
   12182             }
   12183         }
   12184         buf.append(']');
   12185         return buf.toString();
   12186     }
   12187 
   12188     static class DumpState {
   12189         public static final int DUMP_LIBS = 1 << 0;
   12190         public static final int DUMP_FEATURES = 1 << 1;
   12191         public static final int DUMP_RESOLVERS = 1 << 2;
   12192         public static final int DUMP_PERMISSIONS = 1 << 3;
   12193         public static final int DUMP_PACKAGES = 1 << 4;
   12194         public static final int DUMP_SHARED_USERS = 1 << 5;
   12195         public static final int DUMP_MESSAGES = 1 << 6;
   12196         public static final int DUMP_PROVIDERS = 1 << 7;
   12197         public static final int DUMP_VERIFIERS = 1 << 8;
   12198         public static final int DUMP_PREFERRED = 1 << 9;
   12199         public static final int DUMP_PREFERRED_XML = 1 << 10;
   12200         public static final int DUMP_KEYSETS = 1 << 11;
   12201         public static final int DUMP_VERSION = 1 << 12;
   12202         public static final int DUMP_INSTALLS = 1 << 13;
   12203 
   12204         public static final int OPTION_SHOW_FILTERS = 1 << 0;
   12205 
   12206         private int mTypes;
   12207 
   12208         private int mOptions;
   12209 
   12210         private boolean mTitlePrinted;
   12211 
   12212         private SharedUserSetting mSharedUser;
   12213 
   12214         public boolean isDumping(int type) {
   12215             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
   12216                 return true;
   12217             }
   12218 
   12219             return (mTypes & type) != 0;
   12220         }
   12221 
   12222         public void setDump(int type) {
   12223             mTypes |= type;
   12224         }
   12225 
   12226         public boolean isOptionEnabled(int option) {
   12227             return (mOptions & option) != 0;
   12228         }
   12229 
   12230         public void setOptionEnabled(int option) {
   12231             mOptions |= option;
   12232         }
   12233 
   12234         public boolean onTitlePrinted() {
   12235             final boolean printed = mTitlePrinted;
   12236             mTitlePrinted = true;
   12237             return printed;
   12238         }
   12239 
   12240         public boolean getTitlePrinted() {
   12241             return mTitlePrinted;
   12242         }
   12243 
   12244         public void setTitlePrinted(boolean enabled) {
   12245             mTitlePrinted = enabled;
   12246         }
   12247 
   12248         public SharedUserSetting getSharedUser() {
   12249             return mSharedUser;
   12250         }
   12251 
   12252         public void setSharedUser(SharedUserSetting user) {
   12253             mSharedUser = user;
   12254         }
   12255     }
   12256 
   12257     @Override
   12258     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   12259         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
   12260                 != PackageManager.PERMISSION_GRANTED) {
   12261             pw.println("Permission Denial: can't dump ActivityManager from from pid="
   12262                     + Binder.getCallingPid()
   12263                     + ", uid=" + Binder.getCallingUid()
   12264                     + " without permission "
   12265                     + android.Manifest.permission.DUMP);
   12266             return;
   12267         }
   12268 
   12269         DumpState dumpState = new DumpState();
   12270         boolean fullPreferred = false;
   12271         boolean checkin = false;
   12272 
   12273         String packageName = null;
   12274 
   12275         int opti = 0;
   12276         while (opti < args.length) {
   12277             String opt = args[opti];
   12278             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
   12279                 break;
   12280             }
   12281             opti++;
   12282 
   12283             if ("-a".equals(opt)) {
   12284                 // Right now we only know how to print all.
   12285             } else if ("-h".equals(opt)) {
   12286                 pw.println("Package manager dump options:");
   12287                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
   12288                 pw.println("    --checkin: dump for a checkin");
   12289                 pw.println("    -f: print details of intent filters");
   12290                 pw.println("    -h: print this help");
   12291                 pw.println("  cmd may be one of:");
   12292                 pw.println("    l[ibraries]: list known shared libraries");
   12293                 pw.println("    f[ibraries]: list device features");
   12294                 pw.println("    k[eysets]: print known keysets");
   12295                 pw.println("    r[esolvers]: dump intent resolvers");
   12296                 pw.println("    perm[issions]: dump permissions");
   12297                 pw.println("    pref[erred]: print preferred package settings");
   12298                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
   12299                 pw.println("    prov[iders]: dump content providers");
   12300                 pw.println("    p[ackages]: dump installed packages");
   12301                 pw.println("    s[hared-users]: dump shared user IDs");
   12302                 pw.println("    m[essages]: print collected runtime messages");
   12303                 pw.println("    v[erifiers]: print package verifier info");
   12304                 pw.println("    version: print database version info");
   12305                 pw.println("    write: write current settings now");
   12306                 pw.println("    <package.name>: info about given package");
   12307                 pw.println("    installs: details about install sessions");
   12308                 return;
   12309             } else if ("--checkin".equals(opt)) {
   12310                 checkin = true;
   12311             } else if ("-f".equals(opt)) {
   12312                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
   12313             } else {
   12314                 pw.println("Unknown argument: " + opt + "; use -h for help");
   12315             }
   12316         }
   12317 
   12318         // Is the caller requesting to dump a particular piece of data?
   12319         if (opti < args.length) {
   12320             String cmd = args[opti];
   12321             opti++;
   12322             // Is this a package name?
   12323             if ("android".equals(cmd) || cmd.contains(".")) {
   12324                 packageName = cmd;
   12325                 // When dumping a single package, we always dump all of its
   12326                 // filter information since the amount of data will be reasonable.
   12327                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
   12328             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
   12329                 dumpState.setDump(DumpState.DUMP_LIBS);
   12330             } else if ("f".equals(cmd) || "features".equals(cmd)) {
   12331                 dumpState.setDump(DumpState.DUMP_FEATURES);
   12332             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
   12333                 dumpState.setDump(DumpState.DUMP_RESOLVERS);
   12334             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
   12335                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
   12336             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
   12337                 dumpState.setDump(DumpState.DUMP_PREFERRED);
   12338             } else if ("preferred-xml".equals(cmd)) {
   12339                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
   12340                 if (opti < args.length && "--full".equals(args[opti])) {
   12341                     fullPreferred = true;
   12342                     opti++;
   12343                 }
   12344             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
   12345                 dumpState.setDump(DumpState.DUMP_PACKAGES);
   12346             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
   12347                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
   12348             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
   12349                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
   12350             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
   12351                 dumpState.setDump(DumpState.DUMP_MESSAGES);
   12352             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
   12353                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
   12354             } else if ("version".equals(cmd)) {
   12355                 dumpState.setDump(DumpState.DUMP_VERSION);
   12356             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
   12357                 dumpState.setDump(DumpState.DUMP_KEYSETS);
   12358             } else if ("installs".equals(cmd)) {
   12359                 dumpState.setDump(DumpState.DUMP_INSTALLS);
   12360             } else if ("write".equals(cmd)) {
   12361                 synchronized (mPackages) {
   12362                     mSettings.writeLPr();
   12363                     pw.println("Settings written.");
   12364                     return;
   12365                 }
   12366             }
   12367         }
   12368 
   12369         if (checkin) {
   12370             pw.println("vers,1");
   12371         }
   12372 
   12373         // reader
   12374         synchronized (mPackages) {
   12375             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
   12376                 if (!checkin) {
   12377                     if (dumpState.onTitlePrinted())
   12378                         pw.println();
   12379                     pw.println("Database versions:");
   12380                     pw.print("  SDK Version:");
   12381                     pw.print(" internal=");
   12382                     pw.print(mSettings.mInternalSdkPlatform);
   12383                     pw.print(" external=");
   12384                     pw.println(mSettings.mExternalSdkPlatform);
   12385                     pw.print("  DB Version:");
   12386                     pw.print(" internal=");
   12387                     pw.print(mSettings.mInternalDatabaseVersion);
   12388                     pw.print(" external=");
   12389                     pw.println(mSettings.mExternalDatabaseVersion);
   12390                 }
   12391             }
   12392 
   12393             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
   12394                 if (!checkin) {
   12395                     if (dumpState.onTitlePrinted())
   12396                         pw.println();
   12397                     pw.println("Verifiers:");
   12398                     pw.print("  Required: ");
   12399                     pw.print(mRequiredVerifierPackage);
   12400                     pw.print(" (uid=");
   12401                     pw.print(getPackageUid(mRequiredVerifierPackage, 0));
   12402                     pw.println(")");
   12403                 } else if (mRequiredVerifierPackage != null) {
   12404                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
   12405                     pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
   12406                 }
   12407             }
   12408 
   12409             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
   12410                 boolean printedHeader = false;
   12411                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
   12412                 while (it.hasNext()) {
   12413                     String name = it.next();
   12414                     SharedLibraryEntry ent = mSharedLibraries.get(name);
   12415                     if (!checkin) {
   12416                         if (!printedHeader) {
   12417                             if (dumpState.onTitlePrinted())
   12418                                 pw.println();
   12419                             pw.println("Libraries:");
   12420                             printedHeader = true;
   12421                         }
   12422                         pw.print("  ");
   12423                     } else {
   12424                         pw.print("lib,");
   12425                     }
   12426                     pw.print(name);
   12427                     if (!checkin) {
   12428                         pw.print(" -> ");
   12429                     }
   12430                     if (ent.path != null) {
   12431                         if (!checkin) {
   12432                             pw.print("(jar) ");
   12433                             pw.print(ent.path);
   12434                         } else {
   12435                             pw.print(",jar,");
   12436                             pw.print(ent.path);
   12437                         }
   12438                     } else {
   12439                         if (!checkin) {
   12440                             pw.print("(apk) ");
   12441                             pw.print(ent.apk);
   12442                         } else {
   12443                             pw.print(",apk,");
   12444                             pw.print(ent.apk);
   12445                         }
   12446                     }
   12447                     pw.println();
   12448                 }
   12449             }
   12450 
   12451             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
   12452                 if (dumpState.onTitlePrinted())
   12453                     pw.println();
   12454                 if (!checkin) {
   12455                     pw.println("Features:");
   12456                 }
   12457                 Iterator<String> it = mAvailableFeatures.keySet().iterator();
   12458                 while (it.hasNext()) {
   12459                     String name = it.next();
   12460                     if (!checkin) {
   12461                         pw.print("  ");
   12462                     } else {
   12463                         pw.print("feat,");
   12464                     }
   12465                     pw.println(name);
   12466                 }
   12467             }
   12468 
   12469             if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
   12470                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
   12471                         : "Activity Resolver Table:", "  ", packageName,
   12472                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
   12473                     dumpState.setTitlePrinted(true);
   12474                 }
   12475                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
   12476                         : "Receiver Resolver Table:", "  ", packageName,
   12477                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
   12478                     dumpState.setTitlePrinted(true);
   12479                 }
   12480                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
   12481                         : "Service Resolver Table:", "  ", packageName,
   12482                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
   12483                     dumpState.setTitlePrinted(true);
   12484                 }
   12485                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
   12486                         : "Provider Resolver Table:", "  ", packageName,
   12487                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
   12488                     dumpState.setTitlePrinted(true);
   12489                 }
   12490             }
   12491 
   12492             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
   12493                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
   12494                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
   12495                     int user = mSettings.mPreferredActivities.keyAt(i);
   12496                     if (pir.dump(pw,
   12497                             dumpState.getTitlePrinted()
   12498                                 ? "\nPreferred Activities User " + user + ":"
   12499                                 : "Preferred Activities User " + user + ":", "  ",
   12500                             packageName, true)) {
   12501                         dumpState.setTitlePrinted(true);
   12502                     }
   12503                 }
   12504             }
   12505 
   12506             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
   12507                 pw.flush();
   12508                 FileOutputStream fout = new FileOutputStream(fd);
   12509                 BufferedOutputStream str = new BufferedOutputStream(fout);
   12510                 XmlSerializer serializer = new FastXmlSerializer();
   12511                 try {
   12512                     serializer.setOutput(str, "utf-8");
   12513                     serializer.startDocument(null, true);
   12514                     serializer.setFeature(
   12515                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
   12516                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
   12517                     serializer.endDocument();
   12518                     serializer.flush();
   12519                 } catch (IllegalArgumentException e) {
   12520                     pw.println("Failed writing: " + e);
   12521                 } catch (IllegalStateException e) {
   12522                     pw.println("Failed writing: " + e);
   12523                 } catch (IOException e) {
   12524                     pw.println("Failed writing: " + e);
   12525                 }
   12526             }
   12527 
   12528             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
   12529                 mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
   12530                 if (packageName == null) {
   12531                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
   12532                         if (iperm == 0) {
   12533                             if (dumpState.onTitlePrinted())
   12534                                 pw.println();
   12535                             pw.println("AppOp Permissions:");
   12536                         }
   12537                         pw.print("  AppOp Permission ");
   12538                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
   12539                         pw.println(":");
   12540                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
   12541                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
   12542                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
   12543                         }
   12544                     }
   12545                 }
   12546             }
   12547 
   12548             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
   12549                 boolean printedSomething = false;
   12550                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
   12551                     if (packageName != null && !packageName.equals(p.info.packageName)) {
   12552                         continue;
   12553                     }
   12554                     if (!printedSomething) {
   12555                         if (dumpState.onTitlePrinted())
   12556                             pw.println();
   12557                         pw.println("Registered ContentProviders:");
   12558                         printedSomething = true;
   12559                     }
   12560                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
   12561                     pw.print("    "); pw.println(p.toString());
   12562                 }
   12563                 printedSomething = false;
   12564                 for (Map.Entry<String, PackageParser.Provider> entry :
   12565                         mProvidersByAuthority.entrySet()) {
   12566                     PackageParser.Provider p = entry.getValue();
   12567                     if (packageName != null && !packageName.equals(p.info.packageName)) {
   12568                         continue;
   12569                     }
   12570                     if (!printedSomething) {
   12571                         if (dumpState.onTitlePrinted())
   12572                             pw.println();
   12573                         pw.println("ContentProvider Authorities:");
   12574                         printedSomething = true;
   12575                     }
   12576                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
   12577                     pw.print("    "); pw.println(p.toString());
   12578                     if (p.info != null && p.info.applicationInfo != null) {
   12579                         final String appInfo = p.info.applicationInfo.toString();
   12580                         pw.print("      applicationInfo="); pw.println(appInfo);
   12581                     }
   12582                 }
   12583             }
   12584 
   12585             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
   12586                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
   12587             }
   12588 
   12589             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
   12590                 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
   12591             }
   12592 
   12593             if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
   12594                 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
   12595             }
   12596 
   12597             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
   12598                 // XXX should handle packageName != null by dumping only install data that
   12599                 // the given package is involved with.
   12600                 if (dumpState.onTitlePrinted()) pw.println();
   12601                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
   12602             }
   12603 
   12604             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
   12605                 if (dumpState.onTitlePrinted()) pw.println();
   12606                 mSettings.dumpReadMessagesLPr(pw, dumpState);
   12607 
   12608                 pw.println();
   12609                 pw.println("Package warning messages:");
   12610                 final File fname = getSettingsProblemFile();
   12611                 FileInputStream in = null;
   12612                 try {
   12613                     in = new FileInputStream(fname);
   12614                     final int avail = in.available();
   12615                     final byte[] data = new byte[avail];
   12616                     in.read(data);
   12617                     pw.print(new String(data));
   12618                 } catch (FileNotFoundException e) {
   12619                 } catch (IOException e) {
   12620                 } finally {
   12621                     if (in != null) {
   12622                         try {
   12623                             in.close();
   12624                         } catch (IOException e) {
   12625                         }
   12626                     }
   12627                 }
   12628             }
   12629 
   12630             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
   12631                 BufferedReader in = null;
   12632                 String line = null;
   12633                 try {
   12634                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
   12635                     while ((line = in.readLine()) != null) {
   12636                         pw.print("msg,");
   12637                         pw.println(line);
   12638                     }
   12639                 } catch (IOException ignored) {
   12640                 } finally {
   12641                     IoUtils.closeQuietly(in);
   12642                 }
   12643             }
   12644         }
   12645     }
   12646 
   12647     // ------- apps on sdcard specific code -------
   12648     static final boolean DEBUG_SD_INSTALL = false;
   12649 
   12650     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
   12651 
   12652     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
   12653 
   12654     private boolean mMediaMounted = false;
   12655 
   12656     static String getEncryptKey() {
   12657         try {
   12658             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
   12659                     SD_ENCRYPTION_KEYSTORE_NAME);
   12660             if (sdEncKey == null) {
   12661                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
   12662                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
   12663                 if (sdEncKey == null) {
   12664                     Slog.e(TAG, "Failed to create encryption keys");
   12665                     return null;
   12666                 }
   12667             }
   12668             return sdEncKey;
   12669         } catch (NoSuchAlgorithmException nsae) {
   12670             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
   12671             return null;
   12672         } catch (IOException ioe) {
   12673             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
   12674             return null;
   12675         }
   12676     }
   12677 
   12678     /*
   12679      * Update media status on PackageManager.
   12680      */
   12681     @Override
   12682     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
   12683         int callingUid = Binder.getCallingUid();
   12684         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
   12685             throw new SecurityException("Media status can only be updated by the system");
   12686         }
   12687         // reader; this apparently protects mMediaMounted, but should probably
   12688         // be a different lock in that case.
   12689         synchronized (mPackages) {
   12690             Log.i(TAG, "Updating external media status from "
   12691                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
   12692                     + (mediaStatus ? "mounted" : "unmounted"));
   12693             if (DEBUG_SD_INSTALL)
   12694                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
   12695                         + ", mMediaMounted=" + mMediaMounted);
   12696             if (mediaStatus == mMediaMounted) {
   12697                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
   12698                         : 0, -1);
   12699                 mHandler.sendMessage(msg);
   12700                 return;
   12701             }
   12702             mMediaMounted = mediaStatus;
   12703         }
   12704         // Queue up an async operation since the package installation may take a
   12705         // little while.
   12706         mHandler.post(new Runnable() {
   12707             public void run() {
   12708                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
   12709             }
   12710         });
   12711     }
   12712 
   12713     /**
   12714      * Called by MountService when the initial ASECs to scan are available.
   12715      * Should block until all the ASEC containers are finished being scanned.
   12716      */
   12717     public void scanAvailableAsecs() {
   12718         updateExternalMediaStatusInner(true, false, false);
   12719         if (mShouldRestoreconData) {
   12720             SELinuxMMAC.setRestoreconDone();
   12721             mShouldRestoreconData = false;
   12722         }
   12723     }
   12724 
   12725     /*
   12726      * Collect information of applications on external media, map them against
   12727      * existing containers and update information based on current mount status.
   12728      * Please note that we always have to report status if reportStatus has been
   12729      * set to true especially when unloading packages.
   12730      */
   12731     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
   12732             boolean externalStorage) {
   12733         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
   12734         int[] uidArr = EmptyArray.INT;
   12735 
   12736         final String[] list = PackageHelper.getSecureContainerList();
   12737         if (ArrayUtils.isEmpty(list)) {
   12738             Log.i(TAG, "No secure containers found");
   12739         } else {
   12740             // Process list of secure containers and categorize them
   12741             // as active or stale based on their package internal state.
   12742 
   12743             // reader
   12744             synchronized (mPackages) {
   12745                 for (String cid : list) {
   12746                     // Leave stages untouched for now; installer service owns them
   12747                     if (PackageInstallerService.isStageName(cid)) continue;
   12748 
   12749                     if (DEBUG_SD_INSTALL)
   12750                         Log.i(TAG, "Processing container " + cid);
   12751                     String pkgName = getAsecPackageName(cid);
   12752                     if (pkgName == null) {
   12753                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
   12754                         continue;
   12755                     }
   12756                     if (DEBUG_SD_INSTALL)
   12757                         Log.i(TAG, "Looking for pkg : " + pkgName);
   12758 
   12759                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
   12760                     if (ps == null) {
   12761                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
   12762                         continue;
   12763                     }
   12764 
   12765                     /*
   12766                      * Skip packages that are not external if we're unmounting
   12767                      * external storage.
   12768                      */
   12769                     if (externalStorage && !isMounted && !isExternal(ps)) {
   12770                         continue;
   12771                     }
   12772 
   12773                     final AsecInstallArgs args = new AsecInstallArgs(cid,
   12774                             getAppDexInstructionSets(ps), isForwardLocked(ps));
   12775                     // The package status is changed only if the code path
   12776                     // matches between settings and the container id.
   12777                     if (ps.codePathString != null
   12778                             && ps.codePathString.startsWith(args.getCodePath())) {
   12779                         if (DEBUG_SD_INSTALL) {
   12780                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
   12781                                     + " at code path: " + ps.codePathString);
   12782                         }
   12783 
   12784                         // We do have a valid package installed on sdcard
   12785                         processCids.put(args, ps.codePathString);
   12786                         final int uid = ps.appId;
   12787                         if (uid != -1) {
   12788                             uidArr = ArrayUtils.appendInt(uidArr, uid);
   12789                         }
   12790                     } else {
   12791                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
   12792                                 + ps.codePathString);
   12793                     }
   12794                 }
   12795             }
   12796 
   12797             Arrays.sort(uidArr);
   12798         }
   12799 
   12800         // Process packages with valid entries.
   12801         if (isMounted) {
   12802             if (DEBUG_SD_INSTALL)
   12803                 Log.i(TAG, "Loading packages");
   12804             loadMediaPackages(processCids, uidArr);
   12805             startCleaningPackages();
   12806             mInstallerService.onSecureContainersAvailable();
   12807         } else {
   12808             if (DEBUG_SD_INSTALL)
   12809                 Log.i(TAG, "Unloading packages");
   12810             unloadMediaPackages(processCids, uidArr, reportStatus);
   12811         }
   12812     }
   12813 
   12814     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
   12815             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
   12816         int size = pkgList.size();
   12817         if (size > 0) {
   12818             // Send broadcasts here
   12819             Bundle extras = new Bundle();
   12820             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
   12821                     .toArray(new String[size]));
   12822             if (uidArr != null) {
   12823                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
   12824             }
   12825             if (replacing) {
   12826                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
   12827             }
   12828             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
   12829                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
   12830             sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
   12831         }
   12832     }
   12833 
   12834    /*
   12835      * Look at potentially valid container ids from processCids If package
   12836      * information doesn't match the one on record or package scanning fails,
   12837      * the cid is added to list of removeCids. We currently don't delete stale
   12838      * containers.
   12839      */
   12840     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
   12841         ArrayList<String> pkgList = new ArrayList<String>();
   12842         Set<AsecInstallArgs> keys = processCids.keySet();
   12843 
   12844         for (AsecInstallArgs args : keys) {
   12845             String codePath = processCids.get(args);
   12846             if (DEBUG_SD_INSTALL)
   12847                 Log.i(TAG, "Loading container : " + args.cid);
   12848             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
   12849             try {
   12850                 // Make sure there are no container errors first.
   12851                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
   12852                     Slog.e(TAG, "Failed to mount cid : " + args.cid
   12853                             + " when installing from sdcard");
   12854                     continue;
   12855                 }
   12856                 // Check code path here.
   12857                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
   12858                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
   12859                             + " does not match one in settings " + codePath);
   12860                     continue;
   12861                 }
   12862                 // Parse package
   12863                 int parseFlags = mDefParseFlags;
   12864                 if (args.isExternal()) {
   12865                     parseFlags |= PackageParser.PARSE_ON_SDCARD;
   12866                 }
   12867                 if (args.isFwdLocked()) {
   12868                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
   12869                 }
   12870 
   12871                 synchronized (mInstallLock) {
   12872                     PackageParser.Package pkg = null;
   12873                     try {
   12874                         pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
   12875                     } catch (PackageManagerException e) {
   12876                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
   12877                     }
   12878                     // Scan the package
   12879                     if (pkg != null) {
   12880                         /*
   12881                          * TODO why is the lock being held? doPostInstall is
   12882                          * called in other places without the lock. This needs
   12883                          * to be straightened out.
   12884                          */
   12885                         // writer
   12886                         synchronized (mPackages) {
   12887                             retCode = PackageManager.INSTALL_SUCCEEDED;
   12888                             pkgList.add(pkg.packageName);
   12889                             // Post process args
   12890                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
   12891                                     pkg.applicationInfo.uid);
   12892                         }
   12893                     } else {
   12894                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
   12895                     }
   12896                 }
   12897 
   12898             } finally {
   12899                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
   12900                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
   12901                 }
   12902             }
   12903         }
   12904         // writer
   12905         synchronized (mPackages) {
   12906             // If the platform SDK has changed since the last time we booted,
   12907             // we need to re-grant app permission to catch any new ones that
   12908             // appear. This is really a hack, and means that apps can in some
   12909             // cases get permissions that the user didn't initially explicitly
   12910             // allow... it would be nice to have some better way to handle
   12911             // this situation.
   12912             final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
   12913             if (regrantPermissions)
   12914                 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
   12915                         + mSdkVersion + "; regranting permissions for external storage");
   12916             mSettings.mExternalSdkPlatform = mSdkVersion;
   12917 
   12918             // Make sure group IDs have been assigned, and any permission
   12919             // changes in other apps are accounted for
   12920             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
   12921                     | (regrantPermissions
   12922                             ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
   12923                             : 0));
   12924 
   12925             mSettings.updateExternalDatabaseVersion();
   12926 
   12927             // can downgrade to reader
   12928             // Persist settings
   12929             mSettings.writeLPr();
   12930         }
   12931         // Send a broadcast to let everyone know we are done processing
   12932         if (pkgList.size() > 0) {
   12933             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
   12934         }
   12935     }
   12936 
   12937    /*
   12938      * Utility method to unload a list of specified containers
   12939      */
   12940     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
   12941         // Just unmount all valid containers.
   12942         for (AsecInstallArgs arg : cidArgs) {
   12943             synchronized (mInstallLock) {
   12944                 arg.doPostDeleteLI(false);
   12945            }
   12946        }
   12947    }
   12948 
   12949     /*
   12950      * Unload packages mounted on external media. This involves deleting package
   12951      * data from internal structures, sending broadcasts about diabled packages,
   12952      * gc'ing to free up references, unmounting all secure containers
   12953      * corresponding to packages on external media, and posting a
   12954      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
   12955      * that we always have to post this message if status has been requested no
   12956      * matter what.
   12957      */
   12958     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
   12959             final boolean reportStatus) {
   12960         if (DEBUG_SD_INSTALL)
   12961             Log.i(TAG, "unloading media packages");
   12962         ArrayList<String> pkgList = new ArrayList<String>();
   12963         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
   12964         final Set<AsecInstallArgs> keys = processCids.keySet();
   12965         for (AsecInstallArgs args : keys) {
   12966             String pkgName = args.getPackageName();
   12967             if (DEBUG_SD_INSTALL)
   12968                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
   12969             // Delete package internally
   12970             PackageRemovedInfo outInfo = new PackageRemovedInfo();
   12971             synchronized (mInstallLock) {
   12972                 boolean res = deletePackageLI(pkgName, null, false, null, null,
   12973                         PackageManager.DELETE_KEEP_DATA, outInfo, false);
   12974                 if (res) {
   12975                     pkgList.add(pkgName);
   12976                 } else {
   12977                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
   12978                     failedList.add(args);
   12979                 }
   12980             }
   12981         }
   12982 
   12983         // reader
   12984         synchronized (mPackages) {
   12985             // We didn't update the settings after removing each package;
   12986             // write them now for all packages.
   12987             mSettings.writeLPr();
   12988         }
   12989 
   12990         // We have to absolutely send UPDATED_MEDIA_STATUS only
   12991         // after confirming that all the receivers processed the ordered
   12992         // broadcast when packages get disabled, force a gc to clean things up.
   12993         // and unload all the containers.
   12994         if (pkgList.size() > 0) {
   12995             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
   12996                     new IIntentReceiver.Stub() {
   12997                 public void performReceive(Intent intent, int resultCode, String data,
   12998                         Bundle extras, boolean ordered, boolean sticky,
   12999                         int sendingUser) throws RemoteException {
   13000                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
   13001                             reportStatus ? 1 : 0, 1, keys);
   13002                     mHandler.sendMessage(msg);
   13003                 }
   13004             });
   13005         } else {
   13006             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
   13007                     keys);
   13008             mHandler.sendMessage(msg);
   13009         }
   13010     }
   13011 
   13012     /** Binder call */
   13013     @Override
   13014     public void movePackage(final String packageName, final IPackageMoveObserver observer,
   13015             final int flags) {
   13016         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
   13017         UserHandle user = new UserHandle(UserHandle.getCallingUserId());
   13018         int returnCode = PackageManager.MOVE_SUCCEEDED;
   13019         int currInstallFlags = 0;
   13020         int newInstallFlags = 0;
   13021 
   13022         File codeFile = null;
   13023         String installerPackageName = null;
   13024         String packageAbiOverride = null;
   13025 
   13026         // reader
   13027         synchronized (mPackages) {
   13028             final PackageParser.Package pkg = mPackages.get(packageName);
   13029             final PackageSetting ps = mSettings.mPackages.get(packageName);
   13030             if (pkg == null || ps == null) {
   13031                 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
   13032             } else {
   13033                 // Disable moving fwd locked apps and system packages
   13034                 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
   13035                     Slog.w(TAG, "Cannot move system application");
   13036                     returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
   13037                 } else if (pkg.mOperationPending) {
   13038                     Slog.w(TAG, "Attempt to move package which has pending operations");
   13039                     returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
   13040                 } else {
   13041                     // Find install location first
   13042                     if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
   13043                             && (flags & PackageManager.MOVE_INTERNAL) != 0) {
   13044                         Slog.w(TAG, "Ambigous flags specified for move location.");
   13045                         returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
   13046                     } else {
   13047                         newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
   13048                                 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
   13049                         currInstallFlags = isExternal(pkg)
   13050                                 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
   13051 
   13052                         if (newInstallFlags == currInstallFlags) {
   13053                             Slog.w(TAG, "No move required. Trying to move to same location");
   13054                             returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
   13055                         } else {
   13056                             if (isForwardLocked(pkg)) {
   13057                                 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
   13058                                 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
   13059                             }
   13060                         }
   13061                     }
   13062                     if (returnCode == PackageManager.MOVE_SUCCEEDED) {
   13063                         pkg.mOperationPending = true;
   13064                     }
   13065                 }
   13066 
   13067                 codeFile = new File(pkg.codePath);
   13068                 installerPackageName = ps.installerPackageName;
   13069                 packageAbiOverride = ps.cpuAbiOverrideString;
   13070             }
   13071         }
   13072 
   13073         if (returnCode != PackageManager.MOVE_SUCCEEDED) {
   13074             try {
   13075                 observer.packageMoved(packageName, returnCode);
   13076             } catch (RemoteException ignored) {
   13077             }
   13078             return;
   13079         }
   13080 
   13081         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
   13082             @Override
   13083             public void onUserActionRequired(Intent intent) throws RemoteException {
   13084                 throw new IllegalStateException();
   13085             }
   13086 
   13087             @Override
   13088             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
   13089                     Bundle extras) throws RemoteException {
   13090                 Slog.d(TAG, "Install result for move: "
   13091                         + PackageManager.installStatusToString(returnCode, msg));
   13092 
   13093                 // We usually have a new package now after the install, but if
   13094                 // we failed we need to clear the pending flag on the original
   13095                 // package object.
   13096                 synchronized (mPackages) {
   13097                     final PackageParser.Package pkg = mPackages.get(packageName);
   13098                     if (pkg != null) {
   13099                         pkg.mOperationPending = false;
   13100                     }
   13101                 }
   13102 
   13103                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
   13104                 switch (status) {
   13105                     case PackageInstaller.STATUS_SUCCESS:
   13106                         observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
   13107                         break;
   13108                     case PackageInstaller.STATUS_FAILURE_STORAGE:
   13109                         observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
   13110                         break;
   13111                     default:
   13112                         observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
   13113                         break;
   13114                 }
   13115             }
   13116         };
   13117 
   13118         // Treat a move like reinstalling an existing app, which ensures that we
   13119         // process everythign uniformly, like unpacking native libraries.
   13120         newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
   13121 
   13122         final Message msg = mHandler.obtainMessage(INIT_COPY);
   13123         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
   13124         msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
   13125                 installerPackageName, null, user, packageAbiOverride);
   13126         mHandler.sendMessage(msg);
   13127     }
   13128 
   13129     @Override
   13130     public boolean setInstallLocation(int loc) {
   13131         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
   13132                 null);
   13133         if (getInstallLocation() == loc) {
   13134             return true;
   13135         }
   13136         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
   13137                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
   13138             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
   13139                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
   13140             return true;
   13141         }
   13142         return false;
   13143    }
   13144 
   13145     @Override
   13146     public int getInstallLocation() {
   13147         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
   13148                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
   13149                 PackageHelper.APP_INSTALL_AUTO);
   13150     }
   13151 
   13152     /** Called by UserManagerService */
   13153     void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
   13154         mDirtyUsers.remove(userHandle);
   13155         mSettings.removeUserLPw(userHandle);
   13156         mPendingBroadcasts.remove(userHandle);
   13157         if (mInstaller != null) {
   13158             // Technically, we shouldn't be doing this with the package lock
   13159             // held.  However, this is very rare, and there is already so much
   13160             // other disk I/O going on, that we'll let it slide for now.
   13161             mInstaller.removeUserDataDirs(userHandle);
   13162         }
   13163         mUserNeedsBadging.delete(userHandle);
   13164         removeUnusedPackagesLILPw(userManager, userHandle);
   13165     }
   13166 
   13167     /**
   13168      * We're removing userHandle and would like to remove any downloaded packages
   13169      * that are no longer in use by any other user.
   13170      * @param userHandle the user being removed
   13171      */
   13172     private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
   13173         final boolean DEBUG_CLEAN_APKS = false;
   13174         int [] users = userManager.getUserIdsLPr();
   13175         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
   13176         while (psit.hasNext()) {
   13177             PackageSetting ps = psit.next();
   13178             if (ps.pkg == null) {
   13179                 continue;
   13180             }
   13181             final String packageName = ps.pkg.packageName;
   13182             // Skip over if system app
   13183             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
   13184                 continue;
   13185             }
   13186             if (DEBUG_CLEAN_APKS) {
   13187                 Slog.i(TAG, "Checking package " + packageName);
   13188             }
   13189             boolean keep = false;
   13190             for (int i = 0; i < users.length; i++) {
   13191                 if (users[i] != userHandle && ps.getInstalled(users[i])) {
   13192                     keep = true;
   13193                     if (DEBUG_CLEAN_APKS) {
   13194                         Slog.i(TAG, "  Keeping package " + packageName + " for user "
   13195                                 + users[i]);
   13196                     }
   13197                     break;
   13198                 }
   13199             }
   13200             if (!keep) {
   13201                 if (DEBUG_CLEAN_APKS) {
   13202                     Slog.i(TAG, "  Removing package " + packageName);
   13203                 }
   13204                 mHandler.post(new Runnable() {
   13205                     public void run() {
   13206                         deletePackageX(packageName, userHandle, 0);
   13207                     } //end run
   13208                 });
   13209             }
   13210         }
   13211     }
   13212 
   13213     /** Called by UserManagerService */
   13214     void createNewUserLILPw(int userHandle, File path) {
   13215         if (mInstaller != null) {
   13216             mInstaller.createUserConfig(userHandle);
   13217             mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
   13218         }
   13219     }
   13220 
   13221     @Override
   13222     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
   13223         mContext.enforceCallingOrSelfPermission(
   13224                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
   13225                 "Only package verification agents can read the verifier device identity");
   13226 
   13227         synchronized (mPackages) {
   13228             return mSettings.getVerifierDeviceIdentityLPw();
   13229         }
   13230     }
   13231 
   13232     @Override
   13233     public void setPermissionEnforced(String permission, boolean enforced) {
   13234         mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
   13235         if (READ_EXTERNAL_STORAGE.equals(permission)) {
   13236             synchronized (mPackages) {
   13237                 if (mSettings.mReadExternalStorageEnforced == null
   13238                         || mSettings.mReadExternalStorageEnforced != enforced) {
   13239                     mSettings.mReadExternalStorageEnforced = enforced;
   13240                     mSettings.writeLPr();
   13241                 }
   13242             }
   13243             // kill any non-foreground processes so we restart them and
   13244             // grant/revoke the GID.
   13245             final IActivityManager am = ActivityManagerNative.getDefault();
   13246             if (am != null) {
   13247                 final long token = Binder.clearCallingIdentity();
   13248                 try {
   13249                     am.killProcessesBelowForeground("setPermissionEnforcement");
   13250                 } catch (RemoteException e) {
   13251                 } finally {
   13252                     Binder.restoreCallingIdentity(token);
   13253                 }
   13254             }
   13255         } else {
   13256             throw new IllegalArgumentException("No selective enforcement for " + permission);
   13257         }
   13258     }
   13259 
   13260     @Override
   13261     @Deprecated
   13262     public boolean isPermissionEnforced(String permission) {
   13263         return true;
   13264     }
   13265 
   13266     @Override
   13267     public boolean isStorageLow() {
   13268         final long token = Binder.clearCallingIdentity();
   13269         try {
   13270             final DeviceStorageMonitorInternal
   13271                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
   13272             if (dsm != null) {
   13273                 return dsm.isMemoryLow();
   13274             } else {
   13275                 return false;
   13276             }
   13277         } finally {
   13278             Binder.restoreCallingIdentity(token);
   13279         }
   13280     }
   13281 
   13282     @Override
   13283     public IPackageInstaller getPackageInstaller() {
   13284         return mInstallerService;
   13285     }
   13286 
   13287     private boolean userNeedsBadging(int userId) {
   13288         int index = mUserNeedsBadging.indexOfKey(userId);
   13289         if (index < 0) {
   13290             final UserInfo userInfo;
   13291             final long token = Binder.clearCallingIdentity();
   13292             try {
   13293                 userInfo = sUserManager.getUserInfo(userId);
   13294             } finally {
   13295                 Binder.restoreCallingIdentity(token);
   13296             }
   13297             final boolean b;
   13298             if (userInfo != null && userInfo.isManagedProfile()) {
   13299                 b = true;
   13300             } else {
   13301                 b = false;
   13302             }
   13303             mUserNeedsBadging.put(userId, b);
   13304             return b;
   13305         }
   13306         return mUserNeedsBadging.valueAt(index);
   13307     }
   13308 
   13309     @Override
   13310     public KeySet getKeySetByAlias(String packageName, String alias) {
   13311         if (packageName == null || alias == null) {
   13312             return null;
   13313         }
   13314         synchronized(mPackages) {
   13315             final PackageParser.Package pkg = mPackages.get(packageName);
   13316             if (pkg == null) {
   13317                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
   13318                 throw new IllegalArgumentException("Unknown package: " + packageName);
   13319             }
   13320             KeySetManagerService ksms = mSettings.mKeySetManagerService;
   13321             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
   13322         }
   13323     }
   13324 
   13325     @Override
   13326     public KeySet getSigningKeySet(String packageName) {
   13327         if (packageName == null) {
   13328             return null;
   13329         }
   13330         synchronized(mPackages) {
   13331             final PackageParser.Package pkg = mPackages.get(packageName);
   13332             if (pkg == null) {
   13333                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
   13334                 throw new IllegalArgumentException("Unknown package: " + packageName);
   13335             }
   13336             if (pkg.applicationInfo.uid != Binder.getCallingUid()
   13337                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
   13338                 throw new SecurityException("May not access signing KeySet of other apps.");
   13339             }
   13340             KeySetManagerService ksms = mSettings.mKeySetManagerService;
   13341             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
   13342         }
   13343     }
   13344 
   13345     @Override
   13346     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
   13347         if (packageName == null || ks == null) {
   13348             return false;
   13349         }
   13350         synchronized(mPackages) {
   13351             final PackageParser.Package pkg = mPackages.get(packageName);
   13352             if (pkg == null) {
   13353                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
   13354                 throw new IllegalArgumentException("Unknown package: " + packageName);
   13355             }
   13356             IBinder ksh = ks.getToken();
   13357             if (ksh instanceof KeySetHandle) {
   13358                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
   13359                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
   13360             }
   13361             return false;
   13362         }
   13363     }
   13364 
   13365     @Override
   13366     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
   13367         if (packageName == null || ks == null) {
   13368             return false;
   13369         }
   13370         synchronized(mPackages) {
   13371             final PackageParser.Package pkg = mPackages.get(packageName);
   13372             if (pkg == null) {
   13373                 Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
   13374                 throw new IllegalArgumentException("Unknown package: " + packageName);
   13375             }
   13376             IBinder ksh = ks.getToken();
   13377             if (ksh instanceof KeySetHandle) {
   13378                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
   13379                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
   13380             }
   13381             return false;
   13382         }
   13383     }
   13384 }
   13385