Home | History | Annotate | Download | only in pm
      1 /*
      2  * Copyright (C) 2011 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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
     20 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
     21 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
     22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
     23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
     24 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
     25 
     26 import android.content.IntentFilter;
     27 import android.content.pm.ActivityInfo;
     28 import android.content.pm.ResolveInfo;
     29 import android.net.Uri;
     30 import android.os.PatternMatcher;
     31 import android.util.LogPrinter;
     32 import com.android.internal.util.FastXmlSerializer;
     33 import com.android.internal.util.JournaledFile;
     34 import com.android.internal.util.XmlUtils;
     35 import com.android.server.pm.PackageManagerService.DumpState;
     36 
     37 import org.xmlpull.v1.XmlPullParser;
     38 import org.xmlpull.v1.XmlPullParserException;
     39 import org.xmlpull.v1.XmlSerializer;
     40 
     41 import android.content.ComponentName;
     42 import android.content.Context;
     43 import android.content.Intent;
     44 import android.content.pm.ApplicationInfo;
     45 import android.content.pm.ComponentInfo;
     46 import android.content.pm.PackageCleanItem;
     47 import android.content.pm.PackageManager;
     48 import android.content.pm.PackageParser;
     49 import android.content.pm.PermissionInfo;
     50 import android.content.pm.Signature;
     51 import android.content.pm.UserInfo;
     52 import android.content.pm.PackageUserState;
     53 import android.content.pm.VerifierDeviceIdentity;
     54 import android.os.Binder;
     55 import android.os.Environment;
     56 import android.os.FileUtils;
     57 import android.os.Process;
     58 import android.os.UserHandle;
     59 import android.util.Log;
     60 import android.util.Slog;
     61 import android.util.SparseArray;
     62 import android.util.Xml;
     63 
     64 import java.io.BufferedOutputStream;
     65 import java.io.File;
     66 import java.io.FileInputStream;
     67 import java.io.FileOutputStream;
     68 import java.io.IOException;
     69 import java.io.PrintWriter;
     70 import java.text.SimpleDateFormat;
     71 import java.util.ArrayList;
     72 import java.util.Arrays;
     73 import java.util.Date;
     74 import java.util.HashMap;
     75 import java.util.HashSet;
     76 import java.util.Iterator;
     77 import java.util.List;
     78 import java.util.Map;
     79 import java.util.Set;
     80 import java.util.Map.Entry;
     81 
     82 import libcore.io.IoUtils;
     83 
     84 /**
     85  * Holds information about dynamic settings.
     86  */
     87 final class Settings {
     88     private static final String TAG = "PackageSettings";
     89 
     90     private static final boolean DEBUG_STOPPED = false;
     91     private static final boolean DEBUG_MU = false;
     92 
     93     private static final String TAG_READ_EXTERNAL_STORAGE = "read-external-storage";
     94     private static final String ATTR_ENFORCEMENT = "enforcement";
     95 
     96     private static final String TAG_ITEM = "item";
     97     private static final String TAG_DISABLED_COMPONENTS = "disabled-components";
     98     private static final String TAG_ENABLED_COMPONENTS = "enabled-components";
     99     private static final String TAG_PACKAGE_RESTRICTIONS = "package-restrictions";
    100     private static final String TAG_PACKAGE = "pkg";
    101 
    102     private static final String ATTR_NAME = "name";
    103     private static final String ATTR_USER = "user";
    104     private static final String ATTR_CODE = "code";
    105     private static final String ATTR_NOT_LAUNCHED = "nl";
    106     private static final String ATTR_ENABLED = "enabled";
    107     private static final String ATTR_ENABLED_CALLER = "enabledCaller";
    108     private static final String ATTR_STOPPED = "stopped";
    109     private static final String ATTR_INSTALLED = "inst";
    110 
    111     private final File mSettingsFilename;
    112     private final File mBackupSettingsFilename;
    113     private final File mPackageListFilename;
    114     private final File mStoppedPackagesFilename;
    115     private final File mBackupStoppedPackagesFilename;
    116     final HashMap<String, PackageSetting> mPackages =
    117             new HashMap<String, PackageSetting>();
    118     // List of replaced system applications
    119     private final HashMap<String, PackageSetting> mDisabledSysPackages =
    120         new HashMap<String, PackageSetting>();
    121 
    122     // These are the last platform API version we were using for
    123     // the apps installed on internal and external storage.  It is
    124     // used to grant newer permissions one time during a system upgrade.
    125     int mInternalSdkPlatform;
    126     int mExternalSdkPlatform;
    127 
    128     Boolean mReadExternalStorageEnforced;
    129 
    130     /** Device identity for the purpose of package verification. */
    131     private VerifierDeviceIdentity mVerifierDeviceIdentity;
    132 
    133     // The user's preferred activities associated with particular intent
    134     // filters.
    135     final SparseArray<PreferredIntentResolver> mPreferredActivities =
    136             new SparseArray<PreferredIntentResolver>();
    137 
    138     final HashMap<String, SharedUserSetting> mSharedUsers =
    139             new HashMap<String, SharedUserSetting>();
    140     private final ArrayList<Object> mUserIds = new ArrayList<Object>();
    141     private final SparseArray<Object> mOtherUserIds =
    142             new SparseArray<Object>();
    143 
    144     // For reading/writing settings file.
    145     private final ArrayList<Signature> mPastSignatures =
    146             new ArrayList<Signature>();
    147 
    148     // Mapping from permission names to info about them.
    149     final HashMap<String, BasePermission> mPermissions =
    150             new HashMap<String, BasePermission>();
    151 
    152     // Mapping from permission tree names to info about them.
    153     final HashMap<String, BasePermission> mPermissionTrees =
    154             new HashMap<String, BasePermission>();
    155 
    156     // Packages that have been uninstalled and still need their external
    157     // storage data deleted.
    158     final ArrayList<PackageCleanItem> mPackagesToBeCleaned = new ArrayList<PackageCleanItem>();
    159 
    160     // Packages that have been renamed since they were first installed.
    161     // Keys are the new names of the packages, values are the original
    162     // names.  The packages appear everwhere else under their original
    163     // names.
    164     final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
    165 
    166     final StringBuilder mReadMessages = new StringBuilder();
    167 
    168     /**
    169      * Used to track packages that have a shared user ID that hasn't been read
    170      * in yet.
    171      * <p>
    172      * TODO: make this just a local variable that is passed in during package
    173      * scanning to make it less confusing.
    174      */
    175     private final ArrayList<PendingPackage> mPendingPackages = new ArrayList<PendingPackage>();
    176 
    177     private final Context mContext;
    178 
    179     private final File mSystemDir;
    180     Settings(Context context) {
    181         this(context, Environment.getDataDirectory());
    182     }
    183 
    184     Settings(Context context, File dataDir) {
    185         mContext = context;
    186         mSystemDir = new File(dataDir, "system");
    187         mSystemDir.mkdirs();
    188         FileUtils.setPermissions(mSystemDir.toString(),
    189                 FileUtils.S_IRWXU|FileUtils.S_IRWXG
    190                 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
    191                 -1, -1);
    192         mSettingsFilename = new File(mSystemDir, "packages.xml");
    193         mBackupSettingsFilename = new File(mSystemDir, "packages-backup.xml");
    194         mPackageListFilename = new File(mSystemDir, "packages.list");
    195         // Deprecated: Needed for migration
    196         mStoppedPackagesFilename = new File(mSystemDir, "packages-stopped.xml");
    197         mBackupStoppedPackagesFilename = new File(mSystemDir, "packages-stopped-backup.xml");
    198     }
    199 
    200     PackageSetting getPackageLPw(PackageParser.Package pkg, PackageSetting origPackage,
    201             String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
    202             String nativeLibraryPathString, int pkgFlags, UserHandle user, boolean add) {
    203         final String name = pkg.packageName;
    204         PackageSetting p = getPackageLPw(name, origPackage, realName, sharedUser, codePath,
    205                 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags,
    206                 user, add, true /* allowInstall */);
    207         return p;
    208     }
    209 
    210     PackageSetting peekPackageLPr(String name) {
    211         return mPackages.get(name);
    212     }
    213 
    214     void setInstallStatus(String pkgName, int status) {
    215         PackageSetting p = mPackages.get(pkgName);
    216         if(p != null) {
    217             if(p.getInstallStatus() != status) {
    218                 p.setInstallStatus(status);
    219             }
    220         }
    221     }
    222 
    223     void setInstallerPackageName(String pkgName,
    224             String installerPkgName) {
    225         PackageSetting p = mPackages.get(pkgName);
    226         if(p != null) {
    227             p.setInstallerPackageName(installerPkgName);
    228         }
    229     }
    230 
    231     SharedUserSetting getSharedUserLPw(String name,
    232             int pkgFlags, boolean create) {
    233         SharedUserSetting s = mSharedUsers.get(name);
    234         if (s == null) {
    235             if (!create) {
    236                 return null;
    237             }
    238             s = new SharedUserSetting(name, pkgFlags);
    239             s.userId = newUserIdLPw(s);
    240             Log.i(PackageManagerService.TAG, "New shared user " + name + ": id=" + s.userId);
    241             // < 0 means we couldn't assign a userid; fall out and return
    242             // s, which is currently null
    243             if (s.userId >= 0) {
    244                 mSharedUsers.put(name, s);
    245             }
    246         }
    247 
    248         return s;
    249     }
    250 
    251     boolean disableSystemPackageLPw(String name) {
    252         final PackageSetting p = mPackages.get(name);
    253         if(p == null) {
    254             Log.w(PackageManagerService.TAG, "Package:"+name+" is not an installed package");
    255             return false;
    256         }
    257         final PackageSetting dp = mDisabledSysPackages.get(name);
    258         // always make sure the system package code and resource paths dont change
    259         if (dp == null) {
    260             if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
    261                 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
    262             }
    263             mDisabledSysPackages.put(name, p);
    264 
    265             // a little trick...  when we install the new package, we don't
    266             // want to modify the existing PackageSetting for the built-in
    267             // version.  so at this point we need a new PackageSetting that
    268             // is okay to muck with.
    269             PackageSetting newp = new PackageSetting(p);
    270             replacePackageLPw(name, newp);
    271             return true;
    272         }
    273         return false;
    274     }
    275 
    276     PackageSetting enableSystemPackageLPw(String name) {
    277         PackageSetting p = mDisabledSysPackages.get(name);
    278         if(p == null) {
    279             Log.w(PackageManagerService.TAG, "Package:"+name+" is not disabled");
    280             return null;
    281         }
    282         // Reset flag in ApplicationInfo object
    283         if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
    284             p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
    285         }
    286         PackageSetting ret = addPackageLPw(name, p.realName, p.codePath, p.resourcePath,
    287                 p.nativeLibraryPathString, p.appId, p.versionCode, p.pkgFlags);
    288         mDisabledSysPackages.remove(name);
    289         return ret;
    290     }
    291 
    292     boolean isDisabledSystemPackageLPr(String name) {
    293         return mDisabledSysPackages.containsKey(name);
    294     }
    295 
    296     void removeDisabledSystemPackageLPw(String name) {
    297         mDisabledSysPackages.remove(name);
    298     }
    299 
    300     PackageSetting addPackageLPw(String name, String realName, File codePath, File resourcePath,
    301             String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
    302         PackageSetting p = mPackages.get(name);
    303         if (p != null) {
    304             if (p.appId == uid) {
    305                 return p;
    306             }
    307             PackageManagerService.reportSettingsProblem(Log.ERROR,
    308                     "Adding duplicate package, keeping first: " + name);
    309             return null;
    310         }
    311         p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
    312                 vc, pkgFlags);
    313         p.appId = uid;
    314         if (addUserIdLPw(uid, p, name)) {
    315             mPackages.put(name, p);
    316             return p;
    317         }
    318         return null;
    319     }
    320 
    321     SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags) {
    322         SharedUserSetting s = mSharedUsers.get(name);
    323         if (s != null) {
    324             if (s.userId == uid) {
    325                 return s;
    326             }
    327             PackageManagerService.reportSettingsProblem(Log.ERROR,
    328                     "Adding duplicate shared user, keeping first: " + name);
    329             return null;
    330         }
    331         s = new SharedUserSetting(name, pkgFlags);
    332         s.userId = uid;
    333         if (addUserIdLPw(uid, s, name)) {
    334             mSharedUsers.put(name, s);
    335             return s;
    336         }
    337         return null;
    338     }
    339 
    340     // Transfer ownership of permissions from one package to another.
    341     void transferPermissionsLPw(String origPkg, String newPkg) {
    342         // Transfer ownership of permissions to the new package.
    343         for (int i=0; i<2; i++) {
    344             HashMap<String, BasePermission> permissions =
    345                     i == 0 ? mPermissionTrees : mPermissions;
    346             for (BasePermission bp : permissions.values()) {
    347                 if (origPkg.equals(bp.sourcePackage)) {
    348                     if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG,
    349                             "Moving permission " + bp.name
    350                             + " from pkg " + bp.sourcePackage
    351                             + " to " + newPkg);
    352                     bp.sourcePackage = newPkg;
    353                     bp.packageSetting = null;
    354                     bp.perm = null;
    355                     if (bp.pendingInfo != null) {
    356                         bp.pendingInfo.packageName = newPkg;
    357                     }
    358                     bp.uid = 0;
    359                     bp.gids = null;
    360                 }
    361             }
    362         }
    363     }
    364 
    365     private PackageSetting getPackageLPw(String name, PackageSetting origPackage,
    366             String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
    367             String nativeLibraryPathString, int vc, int pkgFlags,
    368             UserHandle installUser, boolean add, boolean allowInstall) {
    369         PackageSetting p = mPackages.get(name);
    370         if (p != null) {
    371             if (!p.codePath.equals(codePath)) {
    372                 // Check to see if its a disabled system app
    373                 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
    374                     // This is an updated system app with versions in both system
    375                     // and data partition. Just let the most recent version
    376                     // take precedence.
    377                     Slog.w(PackageManagerService.TAG, "Trying to update system app code path from "
    378                             + p.codePathString + " to " + codePath.toString());
    379                 } else {
    380                     // Just a change in the code path is not an issue, but
    381                     // let's log a message about it.
    382                     Slog.i(PackageManagerService.TAG, "Package " + name + " codePath changed from "
    383                             + p.codePath + " to " + codePath + "; Retaining data and using new");
    384                     /*
    385                      * Since we've changed paths, we need to prefer the new
    386                      * native library path over the one stored in the
    387                      * package settings since we might have moved from
    388                      * internal to external storage or vice versa.
    389                      */
    390                     p.nativeLibraryPathString = nativeLibraryPathString;
    391                 }
    392             }
    393             if (p.sharedUser != sharedUser) {
    394                 PackageManagerService.reportSettingsProblem(Log.WARN,
    395                         "Package " + name + " shared user changed from "
    396                         + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
    397                         + " to "
    398                         + (sharedUser != null ? sharedUser.name : "<nothing>")
    399                         + "; replacing with new");
    400                 p = null;
    401             } else {
    402                 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
    403                     // If what we are scanning is a system package, then
    404                     // make it so, regardless of whether it was previously
    405                     // installed only in the data partition.
    406                     p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
    407                 }
    408             }
    409         }
    410         if (p == null) {
    411             if (origPackage != null) {
    412                 // We are consuming the data from an existing package.
    413                 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
    414                         nativeLibraryPathString, vc, pkgFlags);
    415                 if (PackageManagerService.DEBUG_UPGRADE) Log.v(PackageManagerService.TAG, "Package "
    416                         + name + " is adopting original package " + origPackage.name);
    417                 // Note that we will retain the new package's signature so
    418                 // that we can keep its data.
    419                 PackageSignatures s = p.signatures;
    420                 p.copyFrom(origPackage);
    421                 p.signatures = s;
    422                 p.sharedUser = origPackage.sharedUser;
    423                 p.appId = origPackage.appId;
    424                 p.origPackage = origPackage;
    425                 mRenamedPackages.put(name, origPackage.name);
    426                 name = origPackage.name;
    427                 // Update new package state.
    428                 p.setTimeStamp(codePath.lastModified());
    429             } else {
    430                 p = new PackageSetting(name, realName, codePath, resourcePath,
    431                         nativeLibraryPathString, vc, pkgFlags);
    432                 p.setTimeStamp(codePath.lastModified());
    433                 p.sharedUser = sharedUser;
    434                 // If this is not a system app, it starts out stopped.
    435                 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
    436                     if (DEBUG_STOPPED) {
    437                         RuntimeException e = new RuntimeException("here");
    438                         e.fillInStackTrace();
    439                         Slog.i(PackageManagerService.TAG, "Stopping package " + name, e);
    440                     }
    441                     List<UserInfo> users = getAllUsers();
    442                     if (users != null && allowInstall) {
    443                         for (UserInfo user : users) {
    444                             // By default we consider this app to be installed
    445                             // for the user if no user has been specified (which
    446                             // means to leave it at its original value, and the
    447                             // original default value is true), or we are being
    448                             // asked to install for all users, or this is the
    449                             // user we are installing for.
    450                             final boolean installed = installUser == null
    451                                     || installUser.getIdentifier() == UserHandle.USER_ALL
    452                                     || installUser.getIdentifier() == user.id;
    453                             p.setUserState(user.id, COMPONENT_ENABLED_STATE_DEFAULT,
    454                                     installed,
    455                                     true, // stopped,
    456                                     true, // notLaunched
    457                                     null, null, null);
    458                             writePackageRestrictionsLPr(user.id);
    459                         }
    460                     }
    461                 }
    462                 if (sharedUser != null) {
    463                     p.appId = sharedUser.userId;
    464                 } else {
    465                     // Clone the setting here for disabled system packages
    466                     PackageSetting dis = mDisabledSysPackages.get(name);
    467                     if (dis != null) {
    468                         // For disabled packages a new setting is created
    469                         // from the existing user id. This still has to be
    470                         // added to list of user id's
    471                         // Copy signatures from previous setting
    472                         if (dis.signatures.mSignatures != null) {
    473                             p.signatures.mSignatures = dis.signatures.mSignatures.clone();
    474                         }
    475                         p.appId = dis.appId;
    476                         // Clone permissions
    477                         p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
    478                         // Clone component info
    479                         List<UserInfo> users = getAllUsers();
    480                         if (users != null) {
    481                             for (UserInfo user : users) {
    482                                 int userId = user.id;
    483                                 p.setDisabledComponentsCopy(
    484                                         dis.getDisabledComponents(userId), userId);
    485                                 p.setEnabledComponentsCopy(
    486                                         dis.getEnabledComponents(userId), userId);
    487                             }
    488                         }
    489                         // Add new setting to list of user ids
    490                         addUserIdLPw(p.appId, p, name);
    491                     } else {
    492                         // Assign new user id
    493                         p.appId = newUserIdLPw(p);
    494                     }
    495                 }
    496             }
    497             if (p.appId < 0) {
    498                 PackageManagerService.reportSettingsProblem(Log.WARN,
    499                         "Package " + name + " could not be assigned a valid uid");
    500                 return null;
    501             }
    502             if (add) {
    503                 // Finish adding new package by adding it and updating shared
    504                 // user preferences
    505                 addPackageSettingLPw(p, name, sharedUser);
    506             }
    507         } else {
    508             if (installUser != null && allowInstall) {
    509                 // The caller has explicitly specified the user they want this
    510                 // package installed for, and the package already exists.
    511                 // Make sure it conforms to the new request.
    512                 List<UserInfo> users = getAllUsers();
    513                 if (users != null) {
    514                     for (UserInfo user : users) {
    515                         if (installUser.getIdentifier() == UserHandle.USER_ALL
    516                                 || installUser.getIdentifier() == user.id) {
    517                             boolean installed = p.getInstalled(user.id);
    518                             if (!installed) {
    519                                 p.setInstalled(true, user.id);
    520                                 writePackageRestrictionsLPr(user.id);
    521                             }
    522                         }
    523                     }
    524                 }
    525             }
    526         }
    527         return p;
    528     }
    529 
    530     void insertPackageSettingLPw(PackageSetting p, PackageParser.Package pkg) {
    531         p.pkg = pkg;
    532         // pkg.mSetEnabled = p.getEnabled(userId);
    533         // pkg.mSetStopped = p.getStopped(userId);
    534         final String codePath = pkg.applicationInfo.sourceDir;
    535         final String resourcePath = pkg.applicationInfo.publicSourceDir;
    536         // Update code path if needed
    537         if (!codePath.equalsIgnoreCase(p.codePathString)) {
    538             Slog.w(PackageManagerService.TAG, "Code path for pkg : " + p.pkg.packageName +
    539                     " changing from " + p.codePathString + " to " + codePath);
    540             p.codePath = new File(codePath);
    541             p.codePathString = codePath;
    542         }
    543         //Update resource path if needed
    544         if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
    545             Slog.w(PackageManagerService.TAG, "Resource path for pkg : " + p.pkg.packageName +
    546                     " changing from " + p.resourcePathString + " to " + resourcePath);
    547             p.resourcePath = new File(resourcePath);
    548             p.resourcePathString = resourcePath;
    549         }
    550         // Update the native library path if needed
    551         final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
    552         if (nativeLibraryPath != null
    553                 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
    554             p.nativeLibraryPathString = nativeLibraryPath;
    555         }
    556         // Update version code if needed
    557         if (pkg.mVersionCode != p.versionCode) {
    558             p.versionCode = pkg.mVersionCode;
    559         }
    560         // Update signatures if needed.
    561         if (p.signatures.mSignatures == null) {
    562             p.signatures.assignSignatures(pkg.mSignatures);
    563         }
    564         // Update flags if needed.
    565         if (pkg.applicationInfo.flags != p.pkgFlags) {
    566             p.pkgFlags = pkg.applicationInfo.flags;
    567         }
    568         // If this app defines a shared user id initialize
    569         // the shared user signatures as well.
    570         if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
    571             p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
    572         }
    573         addPackageSettingLPw(p, pkg.packageName, p.sharedUser);
    574     }
    575 
    576     // Utility method that adds a PackageSetting to mPackages and
    577     // completes updating the shared user attributes
    578     private void addPackageSettingLPw(PackageSetting p, String name,
    579             SharedUserSetting sharedUser) {
    580         mPackages.put(name, p);
    581         if (sharedUser != null) {
    582             if (p.sharedUser != null && p.sharedUser != sharedUser) {
    583                 PackageManagerService.reportSettingsProblem(Log.ERROR,
    584                         "Package " + p.name + " was user "
    585                         + p.sharedUser + " but is now " + sharedUser
    586                         + "; I am not changing its files so it will probably fail!");
    587                 p.sharedUser.packages.remove(p);
    588             } else if (p.appId != sharedUser.userId) {
    589                 PackageManagerService.reportSettingsProblem(Log.ERROR,
    590                     "Package " + p.name + " was user id " + p.appId
    591                     + " but is now user " + sharedUser
    592                     + " with id " + sharedUser.userId
    593                     + "; I am not changing its files so it will probably fail!");
    594             }
    595 
    596             sharedUser.packages.add(p);
    597             p.sharedUser = sharedUser;
    598             p.appId = sharedUser.userId;
    599         }
    600     }
    601 
    602     /*
    603      * Update the shared user setting when a package using
    604      * specifying the shared user id is removed. The gids
    605      * associated with each permission of the deleted package
    606      * are removed from the shared user's gid list only if its
    607      * not in use by other permissions of packages in the
    608      * shared user setting.
    609      */
    610     void updateSharedUserPermsLPw(PackageSetting deletedPs, int[] globalGids) {
    611         if ((deletedPs == null) || (deletedPs.pkg == null)) {
    612             Slog.i(PackageManagerService.TAG,
    613                     "Trying to update info for null package. Just ignoring");
    614             return;
    615         }
    616         // No sharedUserId
    617         if (deletedPs.sharedUser == null) {
    618             return;
    619         }
    620         SharedUserSetting sus = deletedPs.sharedUser;
    621         // Update permissions
    622         for (String eachPerm : deletedPs.pkg.requestedPermissions) {
    623             boolean used = false;
    624             if (!sus.grantedPermissions.contains(eachPerm)) {
    625                 continue;
    626             }
    627             for (PackageSetting pkg:sus.packages) {
    628                 if (pkg.pkg != null &&
    629                         !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
    630                         pkg.pkg.requestedPermissions.contains(eachPerm)) {
    631                     used = true;
    632                     break;
    633                 }
    634             }
    635             if (!used) {
    636                 // can safely delete this permission from list
    637                 sus.grantedPermissions.remove(eachPerm);
    638             }
    639         }
    640         // Update gids
    641         int newGids[] = globalGids;
    642         for (String eachPerm : sus.grantedPermissions) {
    643             BasePermission bp = mPermissions.get(eachPerm);
    644             if (bp != null) {
    645                 newGids = PackageManagerService.appendInts(newGids, bp.gids);
    646             }
    647         }
    648         sus.gids = newGids;
    649     }
    650 
    651     int removePackageLPw(String name) {
    652         final PackageSetting p = mPackages.get(name);
    653         if (p != null) {
    654             mPackages.remove(name);
    655             if (p.sharedUser != null) {
    656                 p.sharedUser.packages.remove(p);
    657                 if (p.sharedUser.packages.size() == 0) {
    658                     mSharedUsers.remove(p.sharedUser.name);
    659                     removeUserIdLPw(p.sharedUser.userId);
    660                     return p.sharedUser.userId;
    661                 }
    662             } else {
    663                 removeUserIdLPw(p.appId);
    664                 return p.appId;
    665             }
    666         }
    667         return -1;
    668     }
    669 
    670     private void replacePackageLPw(String name, PackageSetting newp) {
    671         final PackageSetting p = mPackages.get(name);
    672         if (p != null) {
    673             if (p.sharedUser != null) {
    674                 p.sharedUser.packages.remove(p);
    675                 p.sharedUser.packages.add(newp);
    676             } else {
    677                 replaceUserIdLPw(p.appId, newp);
    678             }
    679         }
    680         mPackages.put(name, newp);
    681     }
    682 
    683     private boolean addUserIdLPw(int uid, Object obj, Object name) {
    684         if (uid > Process.LAST_APPLICATION_UID) {
    685             return false;
    686         }
    687 
    688         if (uid >= Process.FIRST_APPLICATION_UID) {
    689             int N = mUserIds.size();
    690             final int index = uid - Process.FIRST_APPLICATION_UID;
    691             while (index >= N) {
    692                 mUserIds.add(null);
    693                 N++;
    694             }
    695             if (mUserIds.get(index) != null) {
    696                 PackageManagerService.reportSettingsProblem(Log.ERROR,
    697                         "Adding duplicate user id: " + uid
    698                         + " name=" + name);
    699                 return false;
    700             }
    701             mUserIds.set(index, obj);
    702         } else {
    703             if (mOtherUserIds.get(uid) != null) {
    704                 PackageManagerService.reportSettingsProblem(Log.ERROR,
    705                         "Adding duplicate shared id: " + uid
    706                         + " name=" + name);
    707                 return false;
    708             }
    709             mOtherUserIds.put(uid, obj);
    710         }
    711         return true;
    712     }
    713 
    714     public Object getUserIdLPr(int uid) {
    715         if (uid >= Process.FIRST_APPLICATION_UID) {
    716             final int N = mUserIds.size();
    717             final int index = uid - Process.FIRST_APPLICATION_UID;
    718             return index < N ? mUserIds.get(index) : null;
    719         } else {
    720             return mOtherUserIds.get(uid);
    721         }
    722     }
    723 
    724     private void removeUserIdLPw(int uid) {
    725         if (uid >= Process.FIRST_APPLICATION_UID) {
    726             final int N = mUserIds.size();
    727             final int index = uid - Process.FIRST_APPLICATION_UID;
    728             if (index < N) mUserIds.set(index, null);
    729         } else {
    730             mOtherUserIds.remove(uid);
    731         }
    732     }
    733 
    734     private void replaceUserIdLPw(int uid, Object obj) {
    735         if (uid >= Process.FIRST_APPLICATION_UID) {
    736             final int N = mUserIds.size();
    737             final int index = uid - Process.FIRST_APPLICATION_UID;
    738             if (index < N) mUserIds.set(index, obj);
    739         } else {
    740             mOtherUserIds.put(uid, obj);
    741         }
    742     }
    743 
    744     PreferredIntentResolver editPreferredActivitiesLPw(int userId) {
    745         PreferredIntentResolver pir = mPreferredActivities.get(userId);
    746         if (pir == null) {
    747             pir = new PreferredIntentResolver();
    748             mPreferredActivities.put(userId, pir);
    749         }
    750         return pir;
    751     }
    752 
    753     private File getUserPackagesStateFile(int userId) {
    754         return new File(Environment.getUserSystemDirectory(userId), "package-restrictions.xml");
    755     }
    756 
    757     private File getUserPackagesStateBackupFile(int userId) {
    758         return new File(Environment.getUserSystemDirectory(userId),
    759                 "package-restrictions-backup.xml");
    760     }
    761 
    762     void writeAllUsersPackageRestrictionsLPr() {
    763         List<UserInfo> users = getAllUsers();
    764         if (users == null) return;
    765 
    766         for (UserInfo user : users) {
    767             writePackageRestrictionsLPr(user.id);
    768         }
    769     }
    770 
    771     void readAllUsersPackageRestrictionsLPr() {
    772         List<UserInfo> users = getAllUsers();
    773         if (users == null) {
    774             readPackageRestrictionsLPr(0);
    775             return;
    776         }
    777 
    778         for (UserInfo user : users) {
    779             readPackageRestrictionsLPr(user.id);
    780         }
    781     }
    782 
    783     private void readPreferredActivitiesLPw(XmlPullParser parser, int userId)
    784             throws XmlPullParserException, IOException {
    785         int outerDepth = parser.getDepth();
    786         int type;
    787         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
    788                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
    789             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
    790                 continue;
    791             }
    792 
    793             String tagName = parser.getName();
    794             if (tagName.equals(TAG_ITEM)) {
    795                 PreferredActivity pa = new PreferredActivity(parser);
    796                 if (pa.mPref.getParseError() == null) {
    797                     editPreferredActivitiesLPw(userId).addFilter(pa);
    798                 } else {
    799                     PackageManagerService.reportSettingsProblem(Log.WARN,
    800                             "Error in package manager settings: <preferred-activity> "
    801                                     + pa.mPref.getParseError() + " at "
    802                                     + parser.getPositionDescription());
    803                 }
    804             } else {
    805                 PackageManagerService.reportSettingsProblem(Log.WARN,
    806                         "Unknown element under <preferred-activities>: " + parser.getName());
    807                 XmlUtils.skipCurrentTag(parser);
    808             }
    809         }
    810     }
    811 
    812     void readPackageRestrictionsLPr(int userId) {
    813         if (DEBUG_MU) {
    814             Log.i(TAG, "Reading package restrictions for user=" + userId);
    815         }
    816         FileInputStream str = null;
    817         File userPackagesStateFile = getUserPackagesStateFile(userId);
    818         File backupFile = getUserPackagesStateBackupFile(userId);
    819         if (backupFile.exists()) {
    820             try {
    821                 str = new FileInputStream(backupFile);
    822                 mReadMessages.append("Reading from backup stopped packages file\n");
    823                 PackageManagerService.reportSettingsProblem(Log.INFO,
    824                         "Need to read from backup stopped packages file");
    825                 if (userPackagesStateFile.exists()) {
    826                     // If both the backup and normal file exist, we
    827                     // ignore the normal one since it might have been
    828                     // corrupted.
    829                     Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
    830                             + userPackagesStateFile);
    831                     userPackagesStateFile.delete();
    832                 }
    833             } catch (java.io.IOException e) {
    834                 // We'll try for the normal settings file.
    835             }
    836         }
    837 
    838         try {
    839             if (str == null) {
    840                 if (!userPackagesStateFile.exists()) {
    841                     mReadMessages.append("No stopped packages file found\n");
    842                     PackageManagerService.reportSettingsProblem(Log.INFO,
    843                             "No stopped packages file; "
    844                             + "assuming all started");
    845                     // At first boot, make sure no packages are stopped.
    846                     // We usually want to have third party apps initialize
    847                     // in the stopped state, but not at first boot.  Also
    848                     // consider all applications to be installed.
    849                     for (PackageSetting pkg : mPackages.values()) {
    850                         pkg.setUserState(userId, COMPONENT_ENABLED_STATE_DEFAULT,
    851                                 true,   // installed
    852                                 false,  // stopped
    853                                 false,  // notLaunched
    854                                 null, null, null);
    855                     }
    856                     return;
    857                 }
    858                 str = new FileInputStream(userPackagesStateFile);
    859             }
    860             final XmlPullParser parser = Xml.newPullParser();
    861             parser.setInput(str, null);
    862 
    863             int type;
    864             while ((type=parser.next()) != XmlPullParser.START_TAG
    865                        && type != XmlPullParser.END_DOCUMENT) {
    866                 ;
    867             }
    868 
    869             if (type != XmlPullParser.START_TAG) {
    870                 mReadMessages.append("No start tag found in package restrictions file\n");
    871                 PackageManagerService.reportSettingsProblem(Log.WARN,
    872                         "No start tag found in package manager stopped packages");
    873                 return;
    874             }
    875 
    876             int outerDepth = parser.getDepth();
    877             PackageSetting ps = null;
    878             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
    879                    && (type != XmlPullParser.END_TAG
    880                            || parser.getDepth() > outerDepth)) {
    881                 if (type == XmlPullParser.END_TAG
    882                         || type == XmlPullParser.TEXT) {
    883                     continue;
    884                 }
    885 
    886                 String tagName = parser.getName();
    887                 if (tagName.equals(TAG_PACKAGE)) {
    888                     String name = parser.getAttributeValue(null, ATTR_NAME);
    889                     ps = mPackages.get(name);
    890                     if (ps == null) {
    891                         Slog.w(PackageManagerService.TAG, "No package known for stopped package: "
    892                                 + name);
    893                         XmlUtils.skipCurrentTag(parser);
    894                         continue;
    895                     }
    896                     final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
    897                     final int enabled = enabledStr == null
    898                             ? COMPONENT_ENABLED_STATE_DEFAULT : Integer.parseInt(enabledStr);
    899                     final String enabledCaller = parser.getAttributeValue(null,
    900                             ATTR_ENABLED_CALLER);
    901                     final String installedStr = parser.getAttributeValue(null, ATTR_INSTALLED);
    902                     final boolean installed = installedStr == null
    903                             ? true : Boolean.parseBoolean(installedStr);
    904                     final String stoppedStr = parser.getAttributeValue(null, ATTR_STOPPED);
    905                     final boolean stopped = stoppedStr == null
    906                             ? false : Boolean.parseBoolean(stoppedStr);
    907                     final String notLaunchedStr = parser.getAttributeValue(null, ATTR_NOT_LAUNCHED);
    908                     final boolean notLaunched = stoppedStr == null
    909                             ? false : Boolean.parseBoolean(notLaunchedStr);
    910 
    911                     HashSet<String> enabledComponents = null;
    912                     HashSet<String> disabledComponents = null;
    913 
    914                     int packageDepth = parser.getDepth();
    915                     while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
    916                             && (type != XmlPullParser.END_TAG
    917                             || parser.getDepth() > packageDepth)) {
    918                         if (type == XmlPullParser.END_TAG
    919                                 || type == XmlPullParser.TEXT) {
    920                             continue;
    921                         }
    922                         tagName = parser.getName();
    923                         if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
    924                             enabledComponents = readComponentsLPr(parser);
    925                         } else if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
    926                             disabledComponents = readComponentsLPr(parser);
    927                         }
    928                     }
    929 
    930                     ps.setUserState(userId, enabled, installed, stopped, notLaunched,
    931                             enabledCaller, enabledComponents, disabledComponents);
    932                 } else if (tagName.equals("preferred-activities")) {
    933                     readPreferredActivitiesLPw(parser, userId);
    934                 } else {
    935                     Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
    936                           + parser.getName());
    937                     XmlUtils.skipCurrentTag(parser);
    938                 }
    939             }
    940 
    941             str.close();
    942 
    943         } catch (XmlPullParserException e) {
    944             mReadMessages.append("Error reading: " + e.toString());
    945             PackageManagerService.reportSettingsProblem(Log.ERROR,
    946                     "Error reading stopped packages: " + e);
    947             Log.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages", e);
    948 
    949         } catch (java.io.IOException e) {
    950             mReadMessages.append("Error reading: " + e.toString());
    951             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
    952             Log.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages", e);
    953         }
    954     }
    955 
    956     private HashSet<String> readComponentsLPr(XmlPullParser parser)
    957             throws IOException, XmlPullParserException {
    958         HashSet<String> components = null;
    959         int type;
    960         int outerDepth = parser.getDepth();
    961         String tagName;
    962         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
    963                 && (type != XmlPullParser.END_TAG
    964                 || parser.getDepth() > outerDepth)) {
    965             if (type == XmlPullParser.END_TAG
    966                     || type == XmlPullParser.TEXT) {
    967                 continue;
    968             }
    969             tagName = parser.getName();
    970             if (tagName.equals(TAG_ITEM)) {
    971                 String componentName = parser.getAttributeValue(null, ATTR_NAME);
    972                 if (componentName != null) {
    973                     if (components == null) {
    974                         components = new HashSet<String>();
    975                     }
    976                     components.add(componentName);
    977                 }
    978             }
    979         }
    980         return components;
    981     }
    982 
    983     void writePreferredActivitiesLPr(XmlSerializer serializer, int userId, boolean full)
    984             throws IllegalArgumentException, IllegalStateException, IOException {
    985         serializer.startTag(null, "preferred-activities");
    986         PreferredIntentResolver pir = mPreferredActivities.get(userId);
    987         if (pir != null) {
    988             for (final PreferredActivity pa : pir.filterSet()) {
    989                 serializer.startTag(null, TAG_ITEM);
    990                 pa.writeToXml(serializer, full);
    991                 serializer.endTag(null, TAG_ITEM);
    992             }
    993         }
    994         serializer.endTag(null, "preferred-activities");
    995     }
    996 
    997     void writePackageRestrictionsLPr(int userId) {
    998         if (DEBUG_MU) {
    999             Log.i(TAG, "Writing package restrictions for user=" + userId);
   1000         }
   1001         // Keep the old stopped packages around until we know the new ones have
   1002         // been successfully written.
   1003         File userPackagesStateFile = getUserPackagesStateFile(userId);
   1004         File backupFile = getUserPackagesStateBackupFile(userId);
   1005         new File(userPackagesStateFile.getParent()).mkdirs();
   1006         if (userPackagesStateFile.exists()) {
   1007             // Presence of backup settings file indicates that we failed
   1008             // to persist packages earlier. So preserve the older
   1009             // backup for future reference since the current packages
   1010             // might have been corrupted.
   1011             if (!backupFile.exists()) {
   1012                 if (!userPackagesStateFile.renameTo(backupFile)) {
   1013                     Log.wtf(PackageManagerService.TAG, "Unable to backup user packages state file, "
   1014                             + "current changes will be lost at reboot");
   1015                     return;
   1016                 }
   1017             } else {
   1018                 userPackagesStateFile.delete();
   1019                 Slog.w(PackageManagerService.TAG, "Preserving older stopped packages backup");
   1020             }
   1021         }
   1022 
   1023         try {
   1024             final FileOutputStream fstr = new FileOutputStream(userPackagesStateFile);
   1025             final BufferedOutputStream str = new BufferedOutputStream(fstr);
   1026 
   1027             final XmlSerializer serializer = new FastXmlSerializer();
   1028             serializer.setOutput(str, "utf-8");
   1029             serializer.startDocument(null, true);
   1030             serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
   1031 
   1032             serializer.startTag(null, TAG_PACKAGE_RESTRICTIONS);
   1033 
   1034             for (final PackageSetting pkg : mPackages.values()) {
   1035                 PackageUserState ustate = pkg.readUserState(userId);
   1036                 if (ustate.stopped || ustate.notLaunched || !ustate.installed
   1037                         || ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT
   1038                         || (ustate.enabledComponents != null
   1039                                 && ustate.enabledComponents.size() > 0)
   1040                         || (ustate.disabledComponents != null
   1041                                 && ustate.disabledComponents.size() > 0)) {
   1042                     serializer.startTag(null, TAG_PACKAGE);
   1043                     serializer.attribute(null, ATTR_NAME, pkg.name);
   1044                     if (DEBUG_MU) Log.i(TAG, "  pkg=" + pkg.name + ", state=" + ustate.enabled);
   1045 
   1046                     if (!ustate.installed) {
   1047                         serializer.attribute(null, ATTR_INSTALLED, "false");
   1048                     }
   1049                     if (ustate.stopped) {
   1050                         serializer.attribute(null, ATTR_STOPPED, "true");
   1051                     }
   1052                     if (ustate.notLaunched) {
   1053                         serializer.attribute(null, ATTR_NOT_LAUNCHED, "true");
   1054                     }
   1055                     if (ustate.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
   1056                         serializer.attribute(null, ATTR_ENABLED,
   1057                                 Integer.toString(ustate.enabled));
   1058                         if (ustate.lastDisableAppCaller != null) {
   1059                             serializer.attribute(null, ATTR_ENABLED_CALLER,
   1060                                     ustate.lastDisableAppCaller);
   1061                         }
   1062                     }
   1063                     if (ustate.enabledComponents != null
   1064                             && ustate.enabledComponents.size() > 0) {
   1065                         serializer.startTag(null, TAG_ENABLED_COMPONENTS);
   1066                         for (final String name : ustate.enabledComponents) {
   1067                             serializer.startTag(null, TAG_ITEM);
   1068                             serializer.attribute(null, ATTR_NAME, name);
   1069                             serializer.endTag(null, TAG_ITEM);
   1070                         }
   1071                         serializer.endTag(null, TAG_ENABLED_COMPONENTS);
   1072                     }
   1073                     if (ustate.disabledComponents != null
   1074                             && ustate.disabledComponents.size() > 0) {
   1075                         serializer.startTag(null, TAG_DISABLED_COMPONENTS);
   1076                         for (final String name : ustate.disabledComponents) {
   1077                             serializer.startTag(null, TAG_ITEM);
   1078                             serializer.attribute(null, ATTR_NAME, name);
   1079                             serializer.endTag(null, TAG_ITEM);
   1080                         }
   1081                         serializer.endTag(null, TAG_DISABLED_COMPONENTS);
   1082                     }
   1083                     serializer.endTag(null, TAG_PACKAGE);
   1084                 }
   1085             }
   1086 
   1087             writePreferredActivitiesLPr(serializer, userId, true);
   1088 
   1089             serializer.endTag(null, TAG_PACKAGE_RESTRICTIONS);
   1090 
   1091             serializer.endDocument();
   1092 
   1093             str.flush();
   1094             FileUtils.sync(fstr);
   1095             str.close();
   1096 
   1097             // New settings successfully written, old ones are no longer
   1098             // needed.
   1099             backupFile.delete();
   1100             FileUtils.setPermissions(userPackagesStateFile.toString(),
   1101                     FileUtils.S_IRUSR|FileUtils.S_IWUSR
   1102                     |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
   1103                     -1, -1);
   1104 
   1105             // Done, all is good!
   1106             return;
   1107         } catch(java.io.IOException e) {
   1108             Log.wtf(PackageManagerService.TAG,
   1109                     "Unable to write package manager user packages state, "
   1110                     + " current changes will be lost at reboot", e);
   1111         }
   1112 
   1113         // Clean up partially written files
   1114         if (userPackagesStateFile.exists()) {
   1115             if (!userPackagesStateFile.delete()) {
   1116                 Log.i(PackageManagerService.TAG, "Failed to clean up mangled file: "
   1117                         + mStoppedPackagesFilename);
   1118             }
   1119         }
   1120     }
   1121 
   1122     // Note: assumed "stopped" field is already cleared in all packages.
   1123     // Legacy reader, used to read in the old file format after an upgrade. Not used after that.
   1124     void readStoppedLPw() {
   1125         FileInputStream str = null;
   1126         if (mBackupStoppedPackagesFilename.exists()) {
   1127             try {
   1128                 str = new FileInputStream(mBackupStoppedPackagesFilename);
   1129                 mReadMessages.append("Reading from backup stopped packages file\n");
   1130                 PackageManagerService.reportSettingsProblem(Log.INFO,
   1131                         "Need to read from backup stopped packages file");
   1132                 if (mSettingsFilename.exists()) {
   1133                     // If both the backup and normal file exist, we
   1134                     // ignore the normal one since it might have been
   1135                     // corrupted.
   1136                     Slog.w(PackageManagerService.TAG, "Cleaning up stopped packages file "
   1137                             + mStoppedPackagesFilename);
   1138                     mStoppedPackagesFilename.delete();
   1139                 }
   1140             } catch (java.io.IOException e) {
   1141                 // We'll try for the normal settings file.
   1142             }
   1143         }
   1144 
   1145         try {
   1146             if (str == null) {
   1147                 if (!mStoppedPackagesFilename.exists()) {
   1148                     mReadMessages.append("No stopped packages file found\n");
   1149                     PackageManagerService.reportSettingsProblem(Log.INFO,
   1150                             "No stopped packages file file; assuming all started");
   1151                     // At first boot, make sure no packages are stopped.
   1152                     // We usually want to have third party apps initialize
   1153                     // in the stopped state, but not at first boot.
   1154                     for (PackageSetting pkg : mPackages.values()) {
   1155                         pkg.setStopped(false, 0);
   1156                         pkg.setNotLaunched(false, 0);
   1157                     }
   1158                     return;
   1159                 }
   1160                 str = new FileInputStream(mStoppedPackagesFilename);
   1161             }
   1162             final XmlPullParser parser = Xml.newPullParser();
   1163             parser.setInput(str, null);
   1164 
   1165             int type;
   1166             while ((type=parser.next()) != XmlPullParser.START_TAG
   1167                        && type != XmlPullParser.END_DOCUMENT) {
   1168                 ;
   1169             }
   1170 
   1171             if (type != XmlPullParser.START_TAG) {
   1172                 mReadMessages.append("No start tag found in stopped packages file\n");
   1173                 PackageManagerService.reportSettingsProblem(Log.WARN,
   1174                         "No start tag found in package manager stopped packages");
   1175                 return;
   1176             }
   1177 
   1178             int outerDepth = parser.getDepth();
   1179             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   1180                    && (type != XmlPullParser.END_TAG
   1181                            || parser.getDepth() > outerDepth)) {
   1182                 if (type == XmlPullParser.END_TAG
   1183                         || type == XmlPullParser.TEXT) {
   1184                     continue;
   1185                 }
   1186 
   1187                 String tagName = parser.getName();
   1188                 if (tagName.equals(TAG_PACKAGE)) {
   1189                     String name = parser.getAttributeValue(null, ATTR_NAME);
   1190                     PackageSetting ps = mPackages.get(name);
   1191                     if (ps != null) {
   1192                         ps.setStopped(true, 0);
   1193                         if ("1".equals(parser.getAttributeValue(null, ATTR_NOT_LAUNCHED))) {
   1194                             ps.setNotLaunched(true, 0);
   1195                         }
   1196                     } else {
   1197                         Slog.w(PackageManagerService.TAG,
   1198                                 "No package known for stopped package: " + name);
   1199                     }
   1200                     XmlUtils.skipCurrentTag(parser);
   1201                 } else {
   1202                     Slog.w(PackageManagerService.TAG, "Unknown element under <stopped-packages>: "
   1203                           + parser.getName());
   1204                     XmlUtils.skipCurrentTag(parser);
   1205                 }
   1206             }
   1207 
   1208             str.close();
   1209 
   1210         } catch (XmlPullParserException e) {
   1211             mReadMessages.append("Error reading: " + e.toString());
   1212             PackageManagerService.reportSettingsProblem(Log.ERROR,
   1213                     "Error reading stopped packages: " + e);
   1214             Log.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages", e);
   1215 
   1216         } catch (java.io.IOException e) {
   1217             mReadMessages.append("Error reading: " + e.toString());
   1218             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
   1219             Log.wtf(PackageManagerService.TAG, "Error reading package manager stopped packages", e);
   1220 
   1221         }
   1222     }
   1223 
   1224     void writeLPr() {
   1225         //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
   1226 
   1227         // Keep the old settings around until we know the new ones have
   1228         // been successfully written.
   1229         if (mSettingsFilename.exists()) {
   1230             // Presence of backup settings file indicates that we failed
   1231             // to persist settings earlier. So preserve the older
   1232             // backup for future reference since the current settings
   1233             // might have been corrupted.
   1234             if (!mBackupSettingsFilename.exists()) {
   1235                 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
   1236                     Log.wtf(PackageManagerService.TAG, "Unable to backup package manager settings, "
   1237                             + " current changes will be lost at reboot");
   1238                     return;
   1239                 }
   1240             } else {
   1241                 mSettingsFilename.delete();
   1242                 Slog.w(PackageManagerService.TAG, "Preserving older settings backup");
   1243             }
   1244         }
   1245 
   1246         mPastSignatures.clear();
   1247 
   1248         try {
   1249             FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
   1250             BufferedOutputStream str = new BufferedOutputStream(fstr);
   1251 
   1252             //XmlSerializer serializer = XmlUtils.serializerInstance();
   1253             XmlSerializer serializer = new FastXmlSerializer();
   1254             serializer.setOutput(str, "utf-8");
   1255             serializer.startDocument(null, true);
   1256             serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
   1257 
   1258             serializer.startTag(null, "packages");
   1259 
   1260             serializer.startTag(null, "last-platform-version");
   1261             serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
   1262             serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
   1263             serializer.endTag(null, "last-platform-version");
   1264 
   1265             if (mVerifierDeviceIdentity != null) {
   1266                 serializer.startTag(null, "verifier");
   1267                 serializer.attribute(null, "device", mVerifierDeviceIdentity.toString());
   1268                 serializer.endTag(null, "verifier");
   1269             }
   1270 
   1271             if (mReadExternalStorageEnforced != null) {
   1272                 serializer.startTag(null, TAG_READ_EXTERNAL_STORAGE);
   1273                 serializer.attribute(
   1274                         null, ATTR_ENFORCEMENT, mReadExternalStorageEnforced ? "1" : "0");
   1275                 serializer.endTag(null, TAG_READ_EXTERNAL_STORAGE);
   1276             }
   1277 
   1278             serializer.startTag(null, "permission-trees");
   1279             for (BasePermission bp : mPermissionTrees.values()) {
   1280                 writePermissionLPr(serializer, bp);
   1281             }
   1282             serializer.endTag(null, "permission-trees");
   1283 
   1284             serializer.startTag(null, "permissions");
   1285             for (BasePermission bp : mPermissions.values()) {
   1286                 writePermissionLPr(serializer, bp);
   1287             }
   1288             serializer.endTag(null, "permissions");
   1289 
   1290             for (final PackageSetting pkg : mPackages.values()) {
   1291                 writePackageLPr(serializer, pkg);
   1292             }
   1293 
   1294             for (final PackageSetting pkg : mDisabledSysPackages.values()) {
   1295                 writeDisabledSysPackageLPr(serializer, pkg);
   1296             }
   1297 
   1298             for (final SharedUserSetting usr : mSharedUsers.values()) {
   1299                 serializer.startTag(null, "shared-user");
   1300                 serializer.attribute(null, ATTR_NAME, usr.name);
   1301                 serializer.attribute(null, "userId",
   1302                         Integer.toString(usr.userId));
   1303                 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
   1304                 serializer.startTag(null, "perms");
   1305                 for (String name : usr.grantedPermissions) {
   1306                     serializer.startTag(null, TAG_ITEM);
   1307                     serializer.attribute(null, ATTR_NAME, name);
   1308                     serializer.endTag(null, TAG_ITEM);
   1309                 }
   1310                 serializer.endTag(null, "perms");
   1311                 serializer.endTag(null, "shared-user");
   1312             }
   1313 
   1314             if (mPackagesToBeCleaned.size() > 0) {
   1315                 for (PackageCleanItem item : mPackagesToBeCleaned) {
   1316                     final String userStr = Integer.toString(item.userId);
   1317                     serializer.startTag(null, "cleaning-package");
   1318                     serializer.attribute(null, ATTR_NAME, item.packageName);
   1319                     serializer.attribute(null, ATTR_CODE, item.andCode ? "true" : "false");
   1320                     serializer.attribute(null, ATTR_USER, userStr);
   1321                     serializer.endTag(null, "cleaning-package");
   1322                 }
   1323             }
   1324 
   1325             if (mRenamedPackages.size() > 0) {
   1326                 for (Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
   1327                     serializer.startTag(null, "renamed-package");
   1328                     serializer.attribute(null, "new", e.getKey());
   1329                     serializer.attribute(null, "old", e.getValue());
   1330                     serializer.endTag(null, "renamed-package");
   1331                 }
   1332             }
   1333 
   1334             serializer.endTag(null, "packages");
   1335 
   1336             serializer.endDocument();
   1337 
   1338             str.flush();
   1339             FileUtils.sync(fstr);
   1340             str.close();
   1341 
   1342             // New settings successfully written, old ones are no longer
   1343             // needed.
   1344             mBackupSettingsFilename.delete();
   1345             FileUtils.setPermissions(mSettingsFilename.toString(),
   1346                     FileUtils.S_IRUSR|FileUtils.S_IWUSR
   1347                     |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
   1348                     -1, -1);
   1349 
   1350             // Write package list file now, use a JournaledFile.
   1351             //
   1352             File tempFile = new File(mPackageListFilename.toString() + ".tmp");
   1353             JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
   1354 
   1355             fstr = new FileOutputStream(journal.chooseForWrite());
   1356             str = new BufferedOutputStream(fstr);
   1357             try {
   1358                 StringBuilder sb = new StringBuilder();
   1359                 for (final PackageSetting pkg : mPackages.values()) {
   1360                     ApplicationInfo ai = pkg.pkg.applicationInfo;
   1361                     String dataPath = ai.dataDir;
   1362                     boolean isDebug  = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
   1363 
   1364                     // Avoid any application that has a space in its path
   1365                     // or that is handled by the system.
   1366                     if (dataPath.indexOf(" ") >= 0 || ai.uid < Process.FIRST_APPLICATION_UID)
   1367                         continue;
   1368 
   1369                     // we store on each line the following information for now:
   1370                     //
   1371                     // pkgName    - package name
   1372                     // userId     - application-specific user id
   1373                     // debugFlag  - 0 or 1 if the package is debuggable.
   1374                     // dataPath   - path to package's data path
   1375                     // seinfo     - seinfo label for the app (assigned at install time)
   1376                     //
   1377                     // NOTE: We prefer not to expose all ApplicationInfo flags for now.
   1378                     //
   1379                     // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
   1380                     // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
   1381                     //   system/core/run-as/run-as.c
   1382                     //
   1383                     sb.setLength(0);
   1384                     sb.append(ai.packageName);
   1385                     sb.append(" ");
   1386                     sb.append((int)ai.uid);
   1387                     sb.append(isDebug ? " 1 " : " 0 ");
   1388                     sb.append(dataPath);
   1389                     sb.append(" ");
   1390                     sb.append(ai.seinfo);
   1391                     sb.append("\n");
   1392                     str.write(sb.toString().getBytes());
   1393                 }
   1394                 str.flush();
   1395                 FileUtils.sync(fstr);
   1396                 str.close();
   1397                 journal.commit();
   1398             } catch (Exception e) {
   1399                 IoUtils.closeQuietly(str);
   1400                 journal.rollback();
   1401             }
   1402 
   1403             FileUtils.setPermissions(mPackageListFilename.toString(),
   1404                     FileUtils.S_IRUSR|FileUtils.S_IWUSR
   1405                     |FileUtils.S_IRGRP|FileUtils.S_IWGRP,
   1406                     -1, -1);
   1407 
   1408             writeAllUsersPackageRestrictionsLPr();
   1409             return;
   1410 
   1411         } catch(XmlPullParserException e) {
   1412             Log.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
   1413                     + "current changes will be lost at reboot", e);
   1414         } catch(java.io.IOException e) {
   1415             Log.wtf(PackageManagerService.TAG, "Unable to write package manager settings, "
   1416                     + "current changes will be lost at reboot", e);
   1417         }
   1418         // Clean up partially written files
   1419         if (mSettingsFilename.exists()) {
   1420             if (!mSettingsFilename.delete()) {
   1421                 Log.wtf(PackageManagerService.TAG, "Failed to clean up mangled file: "
   1422                         + mSettingsFilename);
   1423             }
   1424         }
   1425         //Debug.stopMethodTracing();
   1426     }
   1427 
   1428     void writeDisabledSysPackageLPr(XmlSerializer serializer, final PackageSetting pkg)
   1429             throws java.io.IOException {
   1430         serializer.startTag(null, "updated-package");
   1431         serializer.attribute(null, ATTR_NAME, pkg.name);
   1432         if (pkg.realName != null) {
   1433             serializer.attribute(null, "realName", pkg.realName);
   1434         }
   1435         serializer.attribute(null, "codePath", pkg.codePathString);
   1436         serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
   1437         serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
   1438         serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
   1439         serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
   1440         if (!pkg.resourcePathString.equals(pkg.codePathString)) {
   1441             serializer.attribute(null, "resourcePath", pkg.resourcePathString);
   1442         }
   1443         if (pkg.nativeLibraryPathString != null) {
   1444             serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
   1445         }
   1446         if (pkg.sharedUser == null) {
   1447             serializer.attribute(null, "userId", Integer.toString(pkg.appId));
   1448         } else {
   1449             serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
   1450         }
   1451         serializer.startTag(null, "perms");
   1452         if (pkg.sharedUser == null) {
   1453             // If this is a shared user, the permissions will
   1454             // be written there. We still need to write an
   1455             // empty permissions list so permissionsFixed will
   1456             // be set.
   1457             for (final String name : pkg.grantedPermissions) {
   1458                 BasePermission bp = mPermissions.get(name);
   1459                 if (bp != null) {
   1460                     // We only need to write signature or system permissions but
   1461                     // this wont
   1462                     // match the semantics of grantedPermissions. So write all
   1463                     // permissions.
   1464                     serializer.startTag(null, TAG_ITEM);
   1465                     serializer.attribute(null, ATTR_NAME, name);
   1466                     serializer.endTag(null, TAG_ITEM);
   1467                 }
   1468             }
   1469         }
   1470         serializer.endTag(null, "perms");
   1471         serializer.endTag(null, "updated-package");
   1472     }
   1473 
   1474     void writePackageLPr(XmlSerializer serializer, final PackageSetting pkg)
   1475             throws java.io.IOException {
   1476         serializer.startTag(null, "package");
   1477         serializer.attribute(null, ATTR_NAME, pkg.name);
   1478         if (pkg.realName != null) {
   1479             serializer.attribute(null, "realName", pkg.realName);
   1480         }
   1481         serializer.attribute(null, "codePath", pkg.codePathString);
   1482         if (!pkg.resourcePathString.equals(pkg.codePathString)) {
   1483             serializer.attribute(null, "resourcePath", pkg.resourcePathString);
   1484         }
   1485         if (pkg.nativeLibraryPathString != null) {
   1486             serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
   1487         }
   1488         serializer.attribute(null, "flags", Integer.toString(pkg.pkgFlags));
   1489         serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
   1490         serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
   1491         serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
   1492         serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
   1493         if (pkg.sharedUser == null) {
   1494             serializer.attribute(null, "userId", Integer.toString(pkg.appId));
   1495         } else {
   1496             serializer.attribute(null, "sharedUserId", Integer.toString(pkg.appId));
   1497         }
   1498         if (pkg.uidError) {
   1499             serializer.attribute(null, "uidError", "true");
   1500         }
   1501         if (pkg.installStatus == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
   1502             serializer.attribute(null, "installStatus", "false");
   1503         }
   1504         if (pkg.installerPackageName != null) {
   1505             serializer.attribute(null, "installer", pkg.installerPackageName);
   1506         }
   1507         pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
   1508         if ((pkg.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
   1509             serializer.startTag(null, "perms");
   1510             if (pkg.sharedUser == null) {
   1511                 // If this is a shared user, the permissions will
   1512                 // be written there. We still need to write an
   1513                 // empty permissions list so permissionsFixed will
   1514                 // be set.
   1515                 for (final String name : pkg.grantedPermissions) {
   1516                     serializer.startTag(null, TAG_ITEM);
   1517                     serializer.attribute(null, ATTR_NAME, name);
   1518                     serializer.endTag(null, TAG_ITEM);
   1519                 }
   1520             }
   1521             serializer.endTag(null, "perms");
   1522         }
   1523 
   1524         serializer.endTag(null, "package");
   1525     }
   1526 
   1527     void writePermissionLPr(XmlSerializer serializer, BasePermission bp)
   1528             throws XmlPullParserException, java.io.IOException {
   1529         if (bp.type != BasePermission.TYPE_BUILTIN && bp.sourcePackage != null) {
   1530             serializer.startTag(null, TAG_ITEM);
   1531             serializer.attribute(null, ATTR_NAME, bp.name);
   1532             serializer.attribute(null, "package", bp.sourcePackage);
   1533             if (bp.protectionLevel != PermissionInfo.PROTECTION_NORMAL) {
   1534                 serializer.attribute(null, "protection", Integer.toString(bp.protectionLevel));
   1535             }
   1536             if (PackageManagerService.DEBUG_SETTINGS)
   1537                 Log.v(PackageManagerService.TAG, "Writing perm: name=" + bp.name + " type="
   1538                         + bp.type);
   1539             if (bp.type == BasePermission.TYPE_DYNAMIC) {
   1540                 final PermissionInfo pi = bp.perm != null ? bp.perm.info : bp.pendingInfo;
   1541                 if (pi != null) {
   1542                     serializer.attribute(null, "type", "dynamic");
   1543                     if (pi.icon != 0) {
   1544                         serializer.attribute(null, "icon", Integer.toString(pi.icon));
   1545                     }
   1546                     if (pi.nonLocalizedLabel != null) {
   1547                         serializer.attribute(null, "label", pi.nonLocalizedLabel.toString());
   1548                     }
   1549                 }
   1550             }
   1551             serializer.endTag(null, TAG_ITEM);
   1552         }
   1553     }
   1554 
   1555     ArrayList<PackageSetting> getListOfIncompleteInstallPackagesLPr() {
   1556         final HashSet<String> kList = new HashSet<String>(mPackages.keySet());
   1557         final Iterator<String> its = kList.iterator();
   1558         final ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
   1559         while (its.hasNext()) {
   1560             final String key = its.next();
   1561             final PackageSetting ps = mPackages.get(key);
   1562             if (ps.getInstallStatus() == PackageSettingBase.PKG_INSTALL_INCOMPLETE) {
   1563                 ret.add(ps);
   1564             }
   1565         }
   1566         return ret;
   1567     }
   1568 
   1569     void addPackageToCleanLPw(PackageCleanItem pkg) {
   1570         if (!mPackagesToBeCleaned.contains(pkg)) {
   1571             mPackagesToBeCleaned.add(pkg);
   1572         }
   1573     }
   1574 
   1575     boolean readLPw(PackageManagerService service, List<UserInfo> users, int sdkVersion,
   1576             boolean onlyCore) {
   1577         FileInputStream str = null;
   1578         if (mBackupSettingsFilename.exists()) {
   1579             try {
   1580                 str = new FileInputStream(mBackupSettingsFilename);
   1581                 mReadMessages.append("Reading from backup settings file\n");
   1582                 PackageManagerService.reportSettingsProblem(Log.INFO,
   1583                         "Need to read from backup settings file");
   1584                 if (mSettingsFilename.exists()) {
   1585                     // If both the backup and settings file exist, we
   1586                     // ignore the settings since it might have been
   1587                     // corrupted.
   1588                     Slog.w(PackageManagerService.TAG, "Cleaning up settings file "
   1589                             + mSettingsFilename);
   1590                     mSettingsFilename.delete();
   1591                 }
   1592             } catch (java.io.IOException e) {
   1593                 // We'll try for the normal settings file.
   1594             }
   1595         }
   1596 
   1597         mPendingPackages.clear();
   1598         mPastSignatures.clear();
   1599 
   1600         try {
   1601             if (str == null) {
   1602                 if (!mSettingsFilename.exists()) {
   1603                     mReadMessages.append("No settings file found\n");
   1604                     PackageManagerService.reportSettingsProblem(Log.INFO,
   1605                             "No settings file; creating initial state");
   1606                     mInternalSdkPlatform = mExternalSdkPlatform = sdkVersion;
   1607                     return false;
   1608                 }
   1609                 str = new FileInputStream(mSettingsFilename);
   1610             }
   1611             XmlPullParser parser = Xml.newPullParser();
   1612             parser.setInput(str, null);
   1613 
   1614             int type;
   1615             while ((type = parser.next()) != XmlPullParser.START_TAG
   1616                     && type != XmlPullParser.END_DOCUMENT) {
   1617                 ;
   1618             }
   1619 
   1620             if (type != XmlPullParser.START_TAG) {
   1621                 mReadMessages.append("No start tag found in settings file\n");
   1622                 PackageManagerService.reportSettingsProblem(Log.WARN,
   1623                         "No start tag found in package manager settings");
   1624                 Log.wtf(PackageManagerService.TAG,
   1625                         "No start tag found in package manager settings");
   1626                 return false;
   1627             }
   1628 
   1629             int outerDepth = parser.getDepth();
   1630             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   1631                     && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1632                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   1633                     continue;
   1634                 }
   1635 
   1636                 String tagName = parser.getName();
   1637                 if (tagName.equals("package")) {
   1638                     readPackageLPw(parser);
   1639                 } else if (tagName.equals("permissions")) {
   1640                     readPermissionsLPw(mPermissions, parser);
   1641                 } else if (tagName.equals("permission-trees")) {
   1642                     readPermissionsLPw(mPermissionTrees, parser);
   1643                 } else if (tagName.equals("shared-user")) {
   1644                     readSharedUserLPw(parser);
   1645                 } else if (tagName.equals("preferred-packages")) {
   1646                     // no longer used.
   1647                 } else if (tagName.equals("preferred-activities")) {
   1648                     // Upgrading from old single-user implementation;
   1649                     // these are the preferred activities for user 0.
   1650                     readPreferredActivitiesLPw(parser, 0);
   1651                 } else if (tagName.equals("updated-package")) {
   1652                     readDisabledSysPackageLPw(parser);
   1653                 } else if (tagName.equals("cleaning-package")) {
   1654                     String name = parser.getAttributeValue(null, ATTR_NAME);
   1655                     String userStr = parser.getAttributeValue(null, ATTR_USER);
   1656                     String codeStr = parser.getAttributeValue(null, ATTR_CODE);
   1657                     if (name != null) {
   1658                         int userId = 0;
   1659                         boolean andCode = true;
   1660                         try {
   1661                             if (userStr != null) {
   1662                                 userId = Integer.parseInt(userStr);
   1663                             }
   1664                         } catch (NumberFormatException e) {
   1665                         }
   1666                         if (codeStr != null) {
   1667                             andCode = Boolean.parseBoolean(codeStr);
   1668                         }
   1669                         addPackageToCleanLPw(new PackageCleanItem(userId, name, andCode));
   1670                     }
   1671                 } else if (tagName.equals("renamed-package")) {
   1672                     String nname = parser.getAttributeValue(null, "new");
   1673                     String oname = parser.getAttributeValue(null, "old");
   1674                     if (nname != null && oname != null) {
   1675                         mRenamedPackages.put(nname, oname);
   1676                     }
   1677                 } else if (tagName.equals("last-platform-version")) {
   1678                     mInternalSdkPlatform = mExternalSdkPlatform = 0;
   1679                     try {
   1680                         String internal = parser.getAttributeValue(null, "internal");
   1681                         if (internal != null) {
   1682                             mInternalSdkPlatform = Integer.parseInt(internal);
   1683                         }
   1684                         String external = parser.getAttributeValue(null, "external");
   1685                         if (external != null) {
   1686                             mExternalSdkPlatform = Integer.parseInt(external);
   1687                         }
   1688                     } catch (NumberFormatException e) {
   1689                     }
   1690                 } else if (tagName.equals("verifier")) {
   1691                     final String deviceIdentity = parser.getAttributeValue(null, "device");
   1692                     try {
   1693                         mVerifierDeviceIdentity = VerifierDeviceIdentity.parse(deviceIdentity);
   1694                     } catch (IllegalArgumentException e) {
   1695                         Slog.w(PackageManagerService.TAG, "Discard invalid verifier device id: "
   1696                                 + e.getMessage());
   1697                     }
   1698                 } else if (TAG_READ_EXTERNAL_STORAGE.equals(tagName)) {
   1699                     final String enforcement = parser.getAttributeValue(null, ATTR_ENFORCEMENT);
   1700                     mReadExternalStorageEnforced = "1".equals(enforcement);
   1701                 } else {
   1702                     Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
   1703                             + parser.getName());
   1704                     XmlUtils.skipCurrentTag(parser);
   1705                 }
   1706             }
   1707 
   1708             str.close();
   1709 
   1710         } catch (XmlPullParserException e) {
   1711             mReadMessages.append("Error reading: " + e.toString());
   1712             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
   1713             Log.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
   1714 
   1715         } catch (java.io.IOException e) {
   1716             mReadMessages.append("Error reading: " + e.toString());
   1717             PackageManagerService.reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
   1718             Log.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
   1719         }
   1720 
   1721         final int N = mPendingPackages.size();
   1722         for (int i = 0; i < N; i++) {
   1723             final PendingPackage pp = mPendingPackages.get(i);
   1724             Object idObj = getUserIdLPr(pp.sharedId);
   1725             if (idObj != null && idObj instanceof SharedUserSetting) {
   1726                 PackageSetting p = getPackageLPw(pp.name, null, pp.realName,
   1727                         (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
   1728                         pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags,
   1729                         null, true /* add */, false /* allowInstall */);
   1730                 if (p == null) {
   1731                     PackageManagerService.reportSettingsProblem(Log.WARN,
   1732                             "Unable to create application package for " + pp.name);
   1733                     continue;
   1734                 }
   1735                 p.copyFrom(pp);
   1736             } else if (idObj != null) {
   1737                 String msg = "Bad package setting: package " + pp.name + " has shared uid "
   1738                         + pp.sharedId + " that is not a shared uid\n";
   1739                 mReadMessages.append(msg);
   1740                 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
   1741             } else {
   1742                 String msg = "Bad package setting: package " + pp.name + " has shared uid "
   1743                         + pp.sharedId + " that is not defined\n";
   1744                 mReadMessages.append(msg);
   1745                 PackageManagerService.reportSettingsProblem(Log.ERROR, msg);
   1746             }
   1747         }
   1748         mPendingPackages.clear();
   1749 
   1750         if (mBackupStoppedPackagesFilename.exists()
   1751                 || mStoppedPackagesFilename.exists()) {
   1752             // Read old file
   1753             readStoppedLPw();
   1754             mBackupStoppedPackagesFilename.delete();
   1755             mStoppedPackagesFilename.delete();
   1756             // Migrate to new file format
   1757             writePackageRestrictionsLPr(0);
   1758         } else {
   1759             if (users == null) {
   1760                 readPackageRestrictionsLPr(0);
   1761             } else {
   1762                 for (UserInfo user : users) {
   1763                     readPackageRestrictionsLPr(user.id);
   1764                 }
   1765             }
   1766         }
   1767 
   1768         /*
   1769          * Make sure all the updated system packages have their shared users
   1770          * associated with them.
   1771          */
   1772         final Iterator<PackageSetting> disabledIt = mDisabledSysPackages.values().iterator();
   1773         while (disabledIt.hasNext()) {
   1774             final PackageSetting disabledPs = disabledIt.next();
   1775             final Object id = getUserIdLPr(disabledPs.appId);
   1776             if (id != null && id instanceof SharedUserSetting) {
   1777                 disabledPs.sharedUser = (SharedUserSetting) id;
   1778             }
   1779         }
   1780 
   1781         mReadMessages.append("Read completed successfully: " + mPackages.size() + " packages, "
   1782                 + mSharedUsers.size() + " shared uids\n");
   1783 
   1784         return true;
   1785     }
   1786 
   1787     void readDefaultPreferredAppsLPw(PackageManagerService service, int userId) {
   1788         // Read preferred apps from .../etc/preferred-apps directory.
   1789         File preferredDir = new File(Environment.getRootDirectory(), "etc/preferred-apps");
   1790         if (!preferredDir.exists() || !preferredDir.isDirectory()) {
   1791             return;
   1792         }
   1793         if (!preferredDir.canRead()) {
   1794             Slog.w(TAG, "Directory " + preferredDir + " cannot be read");
   1795             return;
   1796         }
   1797 
   1798         // Iterate over the files in the directory and scan .xml files
   1799         for (File f : preferredDir.listFiles()) {
   1800             if (!f.getPath().endsWith(".xml")) {
   1801                 Slog.i(TAG, "Non-xml file " + f + " in " + preferredDir + " directory, ignoring");
   1802                 continue;
   1803             }
   1804             if (!f.canRead()) {
   1805                 Slog.w(TAG, "Preferred apps file " + f + " cannot be read");
   1806                 continue;
   1807             }
   1808 
   1809             if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Reading default preferred " + f);
   1810             FileInputStream str = null;
   1811             try {
   1812                 str = new FileInputStream(f);
   1813                 XmlPullParser parser = Xml.newPullParser();
   1814                 parser.setInput(str, null);
   1815 
   1816                 int type;
   1817                 while ((type = parser.next()) != XmlPullParser.START_TAG
   1818                         && type != XmlPullParser.END_DOCUMENT) {
   1819                     ;
   1820                 }
   1821 
   1822                 if (type != XmlPullParser.START_TAG) {
   1823                     Slog.w(TAG, "Preferred apps file " + f + " does not have start tag");
   1824                     continue;
   1825                 }
   1826                 if (!"preferred-activities".equals(parser.getName())) {
   1827                     Slog.w(TAG, "Preferred apps file " + f
   1828                             + " does not start with 'preferred-activities'");
   1829                     continue;
   1830                 }
   1831                 readDefaultPreferredActivitiesLPw(service, parser, userId);
   1832             } catch (XmlPullParserException e) {
   1833                 Slog.w(TAG, "Error reading apps file " + f, e);
   1834             } catch (IOException e) {
   1835                 Slog.w(TAG, "Error reading apps file " + f, e);
   1836             } finally {
   1837                 if (str != null) {
   1838                     try {
   1839                         str.close();
   1840                     } catch (IOException e) {
   1841                     }
   1842                 }
   1843             }
   1844         }
   1845     }
   1846 
   1847     private void readDefaultPreferredActivitiesLPw(PackageManagerService service,
   1848             XmlPullParser parser, int userId)
   1849             throws XmlPullParserException, IOException {
   1850         int outerDepth = parser.getDepth();
   1851         int type;
   1852         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   1853                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1854             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   1855                 continue;
   1856             }
   1857 
   1858             String tagName = parser.getName();
   1859             if (tagName.equals(TAG_ITEM)) {
   1860                 PreferredActivity tmpPa = new PreferredActivity(parser);
   1861                 if (tmpPa.mPref.getParseError() == null) {
   1862                     // The initial preferences only specify the target activity
   1863                     // component and intent-filter, not the set of matches.  So we
   1864                     // now need to query for the matches to build the correct
   1865                     // preferred activity entry.
   1866                     if (PackageManagerService.DEBUG_PREFERRED) {
   1867                         Log.d(TAG, "Processing preferred:");
   1868                         tmpPa.dump(new LogPrinter(Log.DEBUG, TAG), "  ");
   1869                     }
   1870                     final ComponentName cn = tmpPa.mPref.mComponent;
   1871                     Intent intent = new Intent();
   1872                     int flags = 0;
   1873                     intent.setAction(tmpPa.getAction(0));
   1874                     for (int i=0; i<tmpPa.countCategories(); i++) {
   1875                         String cat = tmpPa.getCategory(i);
   1876                         if (cat.equals(Intent.CATEGORY_DEFAULT)) {
   1877                             flags |= PackageManager.MATCH_DEFAULT_ONLY;
   1878                         } else {
   1879                             intent.addCategory(cat);
   1880                         }
   1881                     }
   1882                     if (tmpPa.countDataSchemes() > 0) {
   1883                         Uri.Builder builder = new Uri.Builder();
   1884                         builder.scheme(tmpPa.getDataScheme(0));
   1885                         if (tmpPa.countDataAuthorities() > 0) {
   1886                             IntentFilter.AuthorityEntry auth = tmpPa.getDataAuthority(0);
   1887                             if (auth.getHost() != null) {
   1888                                 builder.authority(auth.getHost());
   1889                             }
   1890                         }
   1891                         if (tmpPa.countDataPaths() > 0) {
   1892                             PatternMatcher path = tmpPa.getDataPath(0);
   1893                             builder.path(path.getPath());
   1894                         }
   1895                         intent.setData(builder.build());
   1896                     } else if (tmpPa.countDataTypes() > 0) {
   1897                         intent.setType(tmpPa.getDataType(0));
   1898                     }
   1899                     List<ResolveInfo> ri = service.mActivities.queryIntent(intent,
   1900                             intent.getType(), flags, 0);
   1901                     if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Queried " + intent
   1902                             + " results: " + ri);
   1903                     int match = 0;
   1904                     if (ri != null && ri.size() > 1) {
   1905                         boolean haveAct = false;
   1906                         boolean haveNonSys = false;
   1907                         ComponentName[] set = new ComponentName[ri.size()];
   1908                         for (int i=0; i<ri.size(); i++) {
   1909                             ActivityInfo ai = ri.get(i).activityInfo;
   1910                             set[i] = new ComponentName(ai.packageName, ai.name);
   1911                             if ((ai.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
   1912                                 // If any of the matches are not system apps, then
   1913                                 // there is a third party app that is now an option...
   1914                                 // so don't set a default since we don't want to hide it.
   1915                                 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
   1916                                         + ai.packageName + "/" + ai.name + ": non-system!");
   1917                                 haveNonSys = true;
   1918                                 break;
   1919                             } else if (cn.getPackageName().equals(ai.packageName)
   1920                                     && cn.getClassName().equals(ai.name)) {
   1921                                 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
   1922                                         + ai.packageName + "/" + ai.name + ": default!");
   1923                                 haveAct = true;
   1924                                 match = ri.get(i).match;
   1925                             } else {
   1926                                 if (PackageManagerService.DEBUG_PREFERRED) Log.d(TAG, "Result "
   1927                                         + ai.packageName + "/" + ai.name + ": skipped");
   1928                             }
   1929                         }
   1930                         if (haveAct && !haveNonSys) {
   1931                             PreferredActivity pa = new PreferredActivity(tmpPa, match, set,
   1932                                     tmpPa.mPref.mComponent);
   1933                             editPreferredActivitiesLPw(userId).addFilter(pa);
   1934                         } else if (!haveNonSys) {
   1935                             Slog.w(TAG, "No component found for default preferred activity "
   1936                                     + tmpPa.mPref.mComponent);
   1937                         }
   1938                     }
   1939                 } else {
   1940                     PackageManagerService.reportSettingsProblem(Log.WARN,
   1941                             "Error in package manager settings: <preferred-activity> "
   1942                                     + tmpPa.mPref.getParseError() + " at "
   1943                                     + parser.getPositionDescription());
   1944                 }
   1945             } else {
   1946                 PackageManagerService.reportSettingsProblem(Log.WARN,
   1947                         "Unknown element under <preferred-activities>: " + parser.getName());
   1948                 XmlUtils.skipCurrentTag(parser);
   1949             }
   1950         }
   1951     }
   1952 
   1953     private int readInt(XmlPullParser parser, String ns, String name, int defValue) {
   1954         String v = parser.getAttributeValue(ns, name);
   1955         try {
   1956             if (v == null) {
   1957                 return defValue;
   1958             }
   1959             return Integer.parseInt(v);
   1960         } catch (NumberFormatException e) {
   1961             PackageManagerService.reportSettingsProblem(Log.WARN,
   1962                     "Error in package manager settings: attribute " + name
   1963                             + " has bad integer value " + v + " at "
   1964                             + parser.getPositionDescription());
   1965         }
   1966         return defValue;
   1967     }
   1968 
   1969     private void readPermissionsLPw(HashMap<String, BasePermission> out, XmlPullParser parser)
   1970             throws IOException, XmlPullParserException {
   1971         int outerDepth = parser.getDepth();
   1972         int type;
   1973         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   1974                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1975             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   1976                 continue;
   1977             }
   1978 
   1979             final String tagName = parser.getName();
   1980             if (tagName.equals(TAG_ITEM)) {
   1981                 final String name = parser.getAttributeValue(null, ATTR_NAME);
   1982                 final String sourcePackage = parser.getAttributeValue(null, "package");
   1983                 final String ptype = parser.getAttributeValue(null, "type");
   1984                 if (name != null && sourcePackage != null) {
   1985                     final boolean dynamic = "dynamic".equals(ptype);
   1986                     final BasePermission bp = new BasePermission(name, sourcePackage,
   1987                             dynamic ? BasePermission.TYPE_DYNAMIC : BasePermission.TYPE_NORMAL);
   1988                     bp.protectionLevel = readInt(parser, null, "protection",
   1989                             PermissionInfo.PROTECTION_NORMAL);
   1990                     bp.protectionLevel = PermissionInfo.fixProtectionLevel(bp.protectionLevel);
   1991                     if (dynamic) {
   1992                         PermissionInfo pi = new PermissionInfo();
   1993                         pi.packageName = sourcePackage.intern();
   1994                         pi.name = name.intern();
   1995                         pi.icon = readInt(parser, null, "icon", 0);
   1996                         pi.nonLocalizedLabel = parser.getAttributeValue(null, "label");
   1997                         pi.protectionLevel = bp.protectionLevel;
   1998                         bp.pendingInfo = pi;
   1999                     }
   2000                     out.put(bp.name, bp);
   2001                 } else {
   2002                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2003                             "Error in package manager settings: permissions has" + " no name at "
   2004                                     + parser.getPositionDescription());
   2005                 }
   2006             } else {
   2007                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2008                         "Unknown element reading permissions: " + parser.getName() + " at "
   2009                                 + parser.getPositionDescription());
   2010             }
   2011             XmlUtils.skipCurrentTag(parser);
   2012         }
   2013     }
   2014 
   2015     private void readDisabledSysPackageLPw(XmlPullParser parser) throws XmlPullParserException,
   2016             IOException {
   2017         String name = parser.getAttributeValue(null, ATTR_NAME);
   2018         String realName = parser.getAttributeValue(null, "realName");
   2019         String codePathStr = parser.getAttributeValue(null, "codePath");
   2020         String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
   2021         String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
   2022         if (resourcePathStr == null) {
   2023             resourcePathStr = codePathStr;
   2024         }
   2025         String version = parser.getAttributeValue(null, "version");
   2026         int versionCode = 0;
   2027         if (version != null) {
   2028             try {
   2029                 versionCode = Integer.parseInt(version);
   2030             } catch (NumberFormatException e) {
   2031             }
   2032         }
   2033 
   2034         int pkgFlags = 0;
   2035         pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
   2036         PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
   2037                 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
   2038         String timeStampStr = parser.getAttributeValue(null, "ft");
   2039         if (timeStampStr != null) {
   2040             try {
   2041                 long timeStamp = Long.parseLong(timeStampStr, 16);
   2042                 ps.setTimeStamp(timeStamp);
   2043             } catch (NumberFormatException e) {
   2044             }
   2045         } else {
   2046             timeStampStr = parser.getAttributeValue(null, "ts");
   2047             if (timeStampStr != null) {
   2048                 try {
   2049                     long timeStamp = Long.parseLong(timeStampStr);
   2050                     ps.setTimeStamp(timeStamp);
   2051                 } catch (NumberFormatException e) {
   2052                 }
   2053             }
   2054         }
   2055         timeStampStr = parser.getAttributeValue(null, "it");
   2056         if (timeStampStr != null) {
   2057             try {
   2058                 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
   2059             } catch (NumberFormatException e) {
   2060             }
   2061         }
   2062         timeStampStr = parser.getAttributeValue(null, "ut");
   2063         if (timeStampStr != null) {
   2064             try {
   2065                 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
   2066             } catch (NumberFormatException e) {
   2067             }
   2068         }
   2069         String idStr = parser.getAttributeValue(null, "userId");
   2070         ps.appId = idStr != null ? Integer.parseInt(idStr) : 0;
   2071         if (ps.appId <= 0) {
   2072             String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
   2073             ps.appId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
   2074         }
   2075         int outerDepth = parser.getDepth();
   2076         int type;
   2077         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2078                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2079             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2080                 continue;
   2081             }
   2082 
   2083             String tagName = parser.getName();
   2084             if (tagName.equals("perms")) {
   2085                 readGrantedPermissionsLPw(parser, ps.grantedPermissions);
   2086             } else {
   2087                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2088                         "Unknown element under <updated-package>: " + parser.getName());
   2089                 XmlUtils.skipCurrentTag(parser);
   2090             }
   2091         }
   2092         mDisabledSysPackages.put(name, ps);
   2093     }
   2094 
   2095     private void readPackageLPw(XmlPullParser parser) throws XmlPullParserException, IOException {
   2096         String name = null;
   2097         String realName = null;
   2098         String idStr = null;
   2099         String sharedIdStr = null;
   2100         String codePathStr = null;
   2101         String resourcePathStr = null;
   2102         String nativeLibraryPathStr = null;
   2103         String systemStr = null;
   2104         String installerPackageName = null;
   2105         String uidError = null;
   2106         int pkgFlags = 0;
   2107         long timeStamp = 0;
   2108         long firstInstallTime = 0;
   2109         long lastUpdateTime = 0;
   2110         PackageSettingBase packageSetting = null;
   2111         String version = null;
   2112         int versionCode = 0;
   2113         try {
   2114             name = parser.getAttributeValue(null, ATTR_NAME);
   2115             realName = parser.getAttributeValue(null, "realName");
   2116             idStr = parser.getAttributeValue(null, "userId");
   2117             uidError = parser.getAttributeValue(null, "uidError");
   2118             sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
   2119             codePathStr = parser.getAttributeValue(null, "codePath");
   2120             resourcePathStr = parser.getAttributeValue(null, "resourcePath");
   2121             nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
   2122             version = parser.getAttributeValue(null, "version");
   2123             if (version != null) {
   2124                 try {
   2125                     versionCode = Integer.parseInt(version);
   2126                 } catch (NumberFormatException e) {
   2127                 }
   2128             }
   2129             installerPackageName = parser.getAttributeValue(null, "installer");
   2130 
   2131             systemStr = parser.getAttributeValue(null, "flags");
   2132             if (systemStr != null) {
   2133                 try {
   2134                     pkgFlags = Integer.parseInt(systemStr);
   2135                 } catch (NumberFormatException e) {
   2136                 }
   2137             } else {
   2138                 // For backward compatibility
   2139                 systemStr = parser.getAttributeValue(null, "system");
   2140                 if (systemStr != null) {
   2141                     pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM
   2142                             : 0;
   2143                 } else {
   2144                     // Old settings that don't specify system... just treat
   2145                     // them as system, good enough.
   2146                     pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
   2147                 }
   2148             }
   2149             String timeStampStr = parser.getAttributeValue(null, "ft");
   2150             if (timeStampStr != null) {
   2151                 try {
   2152                     timeStamp = Long.parseLong(timeStampStr, 16);
   2153                 } catch (NumberFormatException e) {
   2154                 }
   2155             } else {
   2156                 timeStampStr = parser.getAttributeValue(null, "ts");
   2157                 if (timeStampStr != null) {
   2158                     try {
   2159                         timeStamp = Long.parseLong(timeStampStr);
   2160                     } catch (NumberFormatException e) {
   2161                     }
   2162                 }
   2163             }
   2164             timeStampStr = parser.getAttributeValue(null, "it");
   2165             if (timeStampStr != null) {
   2166                 try {
   2167                     firstInstallTime = Long.parseLong(timeStampStr, 16);
   2168                 } catch (NumberFormatException e) {
   2169                 }
   2170             }
   2171             timeStampStr = parser.getAttributeValue(null, "ut");
   2172             if (timeStampStr != null) {
   2173                 try {
   2174                     lastUpdateTime = Long.parseLong(timeStampStr, 16);
   2175                 } catch (NumberFormatException e) {
   2176                 }
   2177             }
   2178             if (PackageManagerService.DEBUG_SETTINGS)
   2179                 Log.v(PackageManagerService.TAG, "Reading package: " + name + " userId=" + idStr
   2180                         + " sharedUserId=" + sharedIdStr);
   2181             int userId = idStr != null ? Integer.parseInt(idStr) : 0;
   2182             if (resourcePathStr == null) {
   2183                 resourcePathStr = codePathStr;
   2184             }
   2185             if (realName != null) {
   2186                 realName = realName.intern();
   2187             }
   2188             if (name == null) {
   2189                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2190                         "Error in package manager settings: <package> has no name at "
   2191                                 + parser.getPositionDescription());
   2192             } else if (codePathStr == null) {
   2193                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2194                         "Error in package manager settings: <package> has no codePath at "
   2195                                 + parser.getPositionDescription());
   2196             } else if (userId > 0) {
   2197                 packageSetting = addPackageLPw(name.intern(), realName, new File(codePathStr),
   2198                         new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
   2199                         pkgFlags);
   2200                 if (PackageManagerService.DEBUG_SETTINGS)
   2201                     Log.i(PackageManagerService.TAG, "Reading package " + name + ": userId="
   2202                             + userId + " pkg=" + packageSetting);
   2203                 if (packageSetting == null) {
   2204                     PackageManagerService.reportSettingsProblem(Log.ERROR, "Failure adding uid "
   2205                             + userId + " while parsing settings at "
   2206                             + parser.getPositionDescription());
   2207                 } else {
   2208                     packageSetting.setTimeStamp(timeStamp);
   2209                     packageSetting.firstInstallTime = firstInstallTime;
   2210                     packageSetting.lastUpdateTime = lastUpdateTime;
   2211                 }
   2212             } else if (sharedIdStr != null) {
   2213                 userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
   2214                 if (userId > 0) {
   2215                     packageSetting = new PendingPackage(name.intern(), realName, new File(
   2216                             codePathStr), new File(resourcePathStr), nativeLibraryPathStr, userId,
   2217                             versionCode, pkgFlags);
   2218                     packageSetting.setTimeStamp(timeStamp);
   2219                     packageSetting.firstInstallTime = firstInstallTime;
   2220                     packageSetting.lastUpdateTime = lastUpdateTime;
   2221                     mPendingPackages.add((PendingPackage) packageSetting);
   2222                     if (PackageManagerService.DEBUG_SETTINGS)
   2223                         Log.i(PackageManagerService.TAG, "Reading package " + name
   2224                                 + ": sharedUserId=" + userId + " pkg=" + packageSetting);
   2225                 } else {
   2226                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2227                             "Error in package manager settings: package " + name
   2228                                     + " has bad sharedId " + sharedIdStr + " at "
   2229                                     + parser.getPositionDescription());
   2230                 }
   2231             } else {
   2232                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2233                         "Error in package manager settings: package " + name + " has bad userId "
   2234                                 + idStr + " at " + parser.getPositionDescription());
   2235             }
   2236         } catch (NumberFormatException e) {
   2237             PackageManagerService.reportSettingsProblem(Log.WARN,
   2238                     "Error in package manager settings: package " + name + " has bad userId "
   2239                             + idStr + " at " + parser.getPositionDescription());
   2240         }
   2241         if (packageSetting != null) {
   2242             packageSetting.uidError = "true".equals(uidError);
   2243             packageSetting.installerPackageName = installerPackageName;
   2244             packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
   2245             // Handle legacy string here for single-user mode
   2246             final String enabledStr = parser.getAttributeValue(null, ATTR_ENABLED);
   2247             if (enabledStr != null) {
   2248                 try {
   2249                     packageSetting.setEnabled(Integer.parseInt(enabledStr), 0 /* userId */, null);
   2250                 } catch (NumberFormatException e) {
   2251                     if (enabledStr.equalsIgnoreCase("true")) {
   2252                         packageSetting.setEnabled(COMPONENT_ENABLED_STATE_ENABLED, 0, null);
   2253                     } else if (enabledStr.equalsIgnoreCase("false")) {
   2254                         packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 0, null);
   2255                     } else if (enabledStr.equalsIgnoreCase("default")) {
   2256                         packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
   2257                     } else {
   2258                         PackageManagerService.reportSettingsProblem(Log.WARN,
   2259                                 "Error in package manager settings: package " + name
   2260                                         + " has bad enabled value: " + idStr + " at "
   2261                                         + parser.getPositionDescription());
   2262                     }
   2263                 }
   2264             } else {
   2265                 packageSetting.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 0, null);
   2266             }
   2267 
   2268             final String installStatusStr = parser.getAttributeValue(null, "installStatus");
   2269             if (installStatusStr != null) {
   2270                 if (installStatusStr.equalsIgnoreCase("false")) {
   2271                     packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_INCOMPLETE;
   2272                 } else {
   2273                     packageSetting.installStatus = PackageSettingBase.PKG_INSTALL_COMPLETE;
   2274                 }
   2275             }
   2276 
   2277             int outerDepth = parser.getDepth();
   2278             int type;
   2279             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2280                     && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2281                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2282                     continue;
   2283                 }
   2284 
   2285                 String tagName = parser.getName();
   2286                 // Legacy
   2287                 if (tagName.equals(TAG_DISABLED_COMPONENTS)) {
   2288                     readDisabledComponentsLPw(packageSetting, parser, 0);
   2289                 } else if (tagName.equals(TAG_ENABLED_COMPONENTS)) {
   2290                     readEnabledComponentsLPw(packageSetting, parser, 0);
   2291                 } else if (tagName.equals("sigs")) {
   2292                     packageSetting.signatures.readXml(parser, mPastSignatures);
   2293                 } else if (tagName.equals("perms")) {
   2294                     readGrantedPermissionsLPw(parser, packageSetting.grantedPermissions);
   2295                     packageSetting.permissionsFixed = true;
   2296                 } else {
   2297                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2298                             "Unknown element under <package>: " + parser.getName());
   2299                     XmlUtils.skipCurrentTag(parser);
   2300                 }
   2301             }
   2302         } else {
   2303             XmlUtils.skipCurrentTag(parser);
   2304         }
   2305     }
   2306 
   2307     private void readDisabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
   2308             int userId) throws IOException, XmlPullParserException {
   2309         int outerDepth = parser.getDepth();
   2310         int type;
   2311         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2312                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2313             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2314                 continue;
   2315             }
   2316 
   2317             String tagName = parser.getName();
   2318             if (tagName.equals(TAG_ITEM)) {
   2319                 String name = parser.getAttributeValue(null, ATTR_NAME);
   2320                 if (name != null) {
   2321                     packageSetting.addDisabledComponent(name.intern(), userId);
   2322                 } else {
   2323                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2324                             "Error in package manager settings: <disabled-components> has"
   2325                                     + " no name at " + parser.getPositionDescription());
   2326                 }
   2327             } else {
   2328                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2329                         "Unknown element under <disabled-components>: " + parser.getName());
   2330             }
   2331             XmlUtils.skipCurrentTag(parser);
   2332         }
   2333     }
   2334 
   2335     private void readEnabledComponentsLPw(PackageSettingBase packageSetting, XmlPullParser parser,
   2336             int userId) throws IOException, XmlPullParserException {
   2337         int outerDepth = parser.getDepth();
   2338         int type;
   2339         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2340                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2341             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2342                 continue;
   2343             }
   2344 
   2345             String tagName = parser.getName();
   2346             if (tagName.equals(TAG_ITEM)) {
   2347                 String name = parser.getAttributeValue(null, ATTR_NAME);
   2348                 if (name != null) {
   2349                     packageSetting.addEnabledComponent(name.intern(), userId);
   2350                 } else {
   2351                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2352                             "Error in package manager settings: <enabled-components> has"
   2353                                     + " no name at " + parser.getPositionDescription());
   2354                 }
   2355             } else {
   2356                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2357                         "Unknown element under <enabled-components>: " + parser.getName());
   2358             }
   2359             XmlUtils.skipCurrentTag(parser);
   2360         }
   2361     }
   2362 
   2363     private void readSharedUserLPw(XmlPullParser parser) throws XmlPullParserException,IOException {
   2364         String name = null;
   2365         String idStr = null;
   2366         int pkgFlags = 0;
   2367         SharedUserSetting su = null;
   2368         try {
   2369             name = parser.getAttributeValue(null, ATTR_NAME);
   2370             idStr = parser.getAttributeValue(null, "userId");
   2371             int userId = idStr != null ? Integer.parseInt(idStr) : 0;
   2372             if ("true".equals(parser.getAttributeValue(null, "system"))) {
   2373                 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
   2374             }
   2375             if (name == null) {
   2376                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2377                         "Error in package manager settings: <shared-user> has no name at "
   2378                                 + parser.getPositionDescription());
   2379             } else if (userId == 0) {
   2380                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2381                         "Error in package manager settings: shared-user " + name
   2382                                 + " has bad userId " + idStr + " at "
   2383                                 + parser.getPositionDescription());
   2384             } else {
   2385                 if ((su = addSharedUserLPw(name.intern(), userId, pkgFlags)) == null) {
   2386                     PackageManagerService
   2387                             .reportSettingsProblem(Log.ERROR, "Occurred while parsing settings at "
   2388                                     + parser.getPositionDescription());
   2389                 }
   2390             }
   2391         } catch (NumberFormatException e) {
   2392             PackageManagerService.reportSettingsProblem(Log.WARN,
   2393                     "Error in package manager settings: package " + name + " has bad userId "
   2394                             + idStr + " at " + parser.getPositionDescription());
   2395         }
   2396         ;
   2397 
   2398         if (su != null) {
   2399             int outerDepth = parser.getDepth();
   2400             int type;
   2401             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2402                     && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2403                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2404                     continue;
   2405                 }
   2406 
   2407                 String tagName = parser.getName();
   2408                 if (tagName.equals("sigs")) {
   2409                     su.signatures.readXml(parser, mPastSignatures);
   2410                 } else if (tagName.equals("perms")) {
   2411                     readGrantedPermissionsLPw(parser, su.grantedPermissions);
   2412                 } else {
   2413                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2414                             "Unknown element under <shared-user>: " + parser.getName());
   2415                     XmlUtils.skipCurrentTag(parser);
   2416                 }
   2417             }
   2418 
   2419         } else {
   2420             XmlUtils.skipCurrentTag(parser);
   2421         }
   2422     }
   2423 
   2424     private void readGrantedPermissionsLPw(XmlPullParser parser, HashSet<String> outPerms)
   2425             throws IOException, XmlPullParserException {
   2426         int outerDepth = parser.getDepth();
   2427         int type;
   2428         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2429                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   2430             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2431                 continue;
   2432             }
   2433 
   2434             String tagName = parser.getName();
   2435             if (tagName.equals(TAG_ITEM)) {
   2436                 String name = parser.getAttributeValue(null, ATTR_NAME);
   2437                 if (name != null) {
   2438                     outPerms.add(name.intern());
   2439                 } else {
   2440                     PackageManagerService.reportSettingsProblem(Log.WARN,
   2441                             "Error in package manager settings: <perms> has" + " no name at "
   2442                                     + parser.getPositionDescription());
   2443                 }
   2444             } else {
   2445                 PackageManagerService.reportSettingsProblem(Log.WARN,
   2446                         "Unknown element under <perms>: " + parser.getName());
   2447             }
   2448             XmlUtils.skipCurrentTag(parser);
   2449         }
   2450     }
   2451 
   2452     void createNewUserLILPw(PackageManagerService service, Installer installer,
   2453             int userHandle, File path) {
   2454         path.mkdir();
   2455         FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
   2456                 | FileUtils.S_IXOTH, -1, -1);
   2457         for (PackageSetting ps : mPackages.values()) {
   2458             // Only system apps are initially installed.
   2459             ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle);
   2460             // Need to create a data directory for all apps under this user.
   2461             installer.createUserData(ps.name,
   2462                     UserHandle.getUid(userHandle, ps.appId), userHandle);
   2463         }
   2464         readDefaultPreferredAppsLPw(service, userHandle);
   2465         writePackageRestrictionsLPr(userHandle);
   2466     }
   2467 
   2468     void removeUserLPr(int userId) {
   2469         Set<Entry<String, PackageSetting>> entries = mPackages.entrySet();
   2470         for (Entry<String, PackageSetting> entry : entries) {
   2471             entry.getValue().removeUser(userId);
   2472         }
   2473         mPreferredActivities.remove(userId);
   2474         File file = getUserPackagesStateFile(userId);
   2475         file.delete();
   2476         file = getUserPackagesStateBackupFile(userId);
   2477         file.delete();
   2478     }
   2479 
   2480     // Returns -1 if we could not find an available UserId to assign
   2481     private int newUserIdLPw(Object obj) {
   2482         // Let's be stupidly inefficient for now...
   2483         final int N = mUserIds.size();
   2484         for (int i = 0; i < N; i++) {
   2485             if (mUserIds.get(i) == null) {
   2486                 mUserIds.set(i, obj);
   2487                 return Process.FIRST_APPLICATION_UID + i;
   2488             }
   2489         }
   2490 
   2491         // None left?
   2492         if (N > (Process.LAST_APPLICATION_UID-Process.FIRST_APPLICATION_UID)) {
   2493             return -1;
   2494         }
   2495 
   2496         mUserIds.add(obj);
   2497         return Process.FIRST_APPLICATION_UID + N;
   2498     }
   2499 
   2500     public VerifierDeviceIdentity getVerifierDeviceIdentityLPw() {
   2501         if (mVerifierDeviceIdentity == null) {
   2502             mVerifierDeviceIdentity = VerifierDeviceIdentity.generate();
   2503 
   2504             writeLPr();
   2505         }
   2506 
   2507         return mVerifierDeviceIdentity;
   2508     }
   2509 
   2510     public PackageSetting getDisabledSystemPkgLPr(String name) {
   2511         PackageSetting ps = mDisabledSysPackages.get(name);
   2512         return ps;
   2513     }
   2514 
   2515     private String compToString(HashSet<String> cmp) {
   2516         return cmp != null ? Arrays.toString(cmp.toArray()) : "[]";
   2517     }
   2518 
   2519     boolean isEnabledLPr(ComponentInfo componentInfo, int flags, int userId) {
   2520         if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
   2521             return true;
   2522         }
   2523         final String pkgName = componentInfo.packageName;
   2524         final PackageSetting packageSettings = mPackages.get(pkgName);
   2525         if (PackageManagerService.DEBUG_SETTINGS) {
   2526             Log.v(PackageManagerService.TAG, "isEnabledLock - packageName = "
   2527                     + componentInfo.packageName + " componentName = " + componentInfo.name);
   2528             Log.v(PackageManagerService.TAG, "enabledComponents: "
   2529                     + compToString(packageSettings.getEnabledComponents(userId)));
   2530             Log.v(PackageManagerService.TAG, "disabledComponents: "
   2531                     + compToString(packageSettings.getDisabledComponents(userId)));
   2532         }
   2533         if (packageSettings == null) {
   2534             return false;
   2535         }
   2536         PackageUserState ustate = packageSettings.readUserState(userId);
   2537         if ((flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0) {
   2538             if (ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
   2539                 return true;
   2540             }
   2541         }
   2542         if (ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED
   2543                 || ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_USER
   2544                 || ustate.enabled == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED
   2545                 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
   2546                     && ustate.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
   2547             return false;
   2548         }
   2549         if (ustate.enabledComponents != null
   2550                 && ustate.enabledComponents.contains(componentInfo.name)) {
   2551             return true;
   2552         }
   2553         if (ustate.disabledComponents != null
   2554                 && ustate.disabledComponents.contains(componentInfo.name)) {
   2555             return false;
   2556         }
   2557         return componentInfo.enabled;
   2558     }
   2559 
   2560     String getInstallerPackageNameLPr(String packageName) {
   2561         final PackageSetting pkg = mPackages.get(packageName);
   2562         if (pkg == null) {
   2563             throw new IllegalArgumentException("Unknown package: " + packageName);
   2564         }
   2565         return pkg.installerPackageName;
   2566     }
   2567 
   2568     int getApplicationEnabledSettingLPr(String packageName, int userId) {
   2569         final PackageSetting pkg = mPackages.get(packageName);
   2570         if (pkg == null) {
   2571             throw new IllegalArgumentException("Unknown package: " + packageName);
   2572         }
   2573         return pkg.getEnabled(userId);
   2574     }
   2575 
   2576     int getComponentEnabledSettingLPr(ComponentName componentName, int userId) {
   2577         final String packageName = componentName.getPackageName();
   2578         final PackageSetting pkg = mPackages.get(packageName);
   2579         if (pkg == null) {
   2580             throw new IllegalArgumentException("Unknown component: " + componentName);
   2581         }
   2582         final String classNameStr = componentName.getClassName();
   2583         return pkg.getCurrentEnabledStateLPr(classNameStr, userId);
   2584     }
   2585 
   2586     boolean setPackageStoppedStateLPw(String packageName, boolean stopped,
   2587             boolean allowedByPermission, int uid, int userId) {
   2588         int appId = UserHandle.getAppId(uid);
   2589         final PackageSetting pkgSetting = mPackages.get(packageName);
   2590         if (pkgSetting == null) {
   2591             throw new IllegalArgumentException("Unknown package: " + packageName);
   2592         }
   2593         if (!allowedByPermission && (appId != pkgSetting.appId)) {
   2594             throw new SecurityException(
   2595                     "Permission Denial: attempt to change stopped state from pid="
   2596                     + Binder.getCallingPid()
   2597                     + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
   2598         }
   2599         if (DEBUG_STOPPED) {
   2600             if (stopped) {
   2601                 RuntimeException e = new RuntimeException("here");
   2602                 e.fillInStackTrace();
   2603                 Slog.i(TAG, "Stopping package " + packageName, e);
   2604             }
   2605         }
   2606         if (pkgSetting.getStopped(userId) != stopped) {
   2607             pkgSetting.setStopped(stopped, userId);
   2608             // pkgSetting.pkg.mSetStopped = stopped;
   2609             if (pkgSetting.getNotLaunched(userId)) {
   2610                 if (pkgSetting.installerPackageName != null) {
   2611                     PackageManagerService.sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH,
   2612                             pkgSetting.name, null,
   2613                             pkgSetting.installerPackageName, null, new int[] {userId});
   2614                 }
   2615                 pkgSetting.setNotLaunched(false, userId);
   2616             }
   2617             return true;
   2618         }
   2619         return false;
   2620     }
   2621 
   2622     private List<UserInfo> getAllUsers() {
   2623         long id = Binder.clearCallingIdentity();
   2624         try {
   2625             return UserManagerService.getInstance().getUsers(false);
   2626         } catch (NullPointerException npe) {
   2627             // packagemanager not yet initialized
   2628         } finally {
   2629             Binder.restoreCallingIdentity(id);
   2630         }
   2631         return null;
   2632     }
   2633 
   2634     static final void printFlags(PrintWriter pw, int val, Object[] spec) {
   2635         pw.print("[ ");
   2636         for (int i=0; i<spec.length; i+=2) {
   2637             int mask = (Integer)spec[i];
   2638             if ((val & mask) != 0) {
   2639                 pw.print(spec[i+1]);
   2640                 pw.print(" ");
   2641             }
   2642         }
   2643         pw.print("]");
   2644     }
   2645 
   2646     static final Object[] FLAG_DUMP_SPEC = new Object[] {
   2647         ApplicationInfo.FLAG_SYSTEM, "SYSTEM",
   2648         ApplicationInfo.FLAG_DEBUGGABLE, "DEBUGGABLE",
   2649         ApplicationInfo.FLAG_HAS_CODE, "HAS_CODE",
   2650         ApplicationInfo.FLAG_PERSISTENT, "PERSISTENT",
   2651         ApplicationInfo.FLAG_FACTORY_TEST, "FACTORY_TEST",
   2652         ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING, "ALLOW_TASK_REPARENTING",
   2653         ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA, "ALLOW_CLEAR_USER_DATA",
   2654         ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, "UPDATED_SYSTEM_APP",
   2655         ApplicationInfo.FLAG_TEST_ONLY, "TEST_ONLY",
   2656         ApplicationInfo.FLAG_VM_SAFE_MODE, "VM_SAFE_MODE",
   2657         ApplicationInfo.FLAG_ALLOW_BACKUP, "ALLOW_BACKUP",
   2658         ApplicationInfo.FLAG_KILL_AFTER_RESTORE, "KILL_AFTER_RESTORE",
   2659         ApplicationInfo.FLAG_RESTORE_ANY_VERSION, "RESTORE_ANY_VERSION",
   2660         ApplicationInfo.FLAG_EXTERNAL_STORAGE, "EXTERNAL_STORAGE",
   2661         ApplicationInfo.FLAG_LARGE_HEAP, "LARGE_HEAP",
   2662         ApplicationInfo.FLAG_FORWARD_LOCK, "FORWARD_LOCK",
   2663         ApplicationInfo.FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
   2664     };
   2665 
   2666     void dumpPackageLPr(PrintWriter pw, String prefix, PackageSetting ps, SimpleDateFormat sdf,
   2667             Date date, List<UserInfo> users) {
   2668         pw.print(prefix); pw.print("Package [");
   2669             pw.print(ps.realName != null ? ps.realName : ps.name);
   2670             pw.print("] (");
   2671             pw.print(Integer.toHexString(System.identityHashCode(ps)));
   2672             pw.println("):");
   2673 
   2674         if (ps.realName != null) {
   2675             pw.print(prefix); pw.print("  compat name=");
   2676             pw.println(ps.name);
   2677         }
   2678 
   2679         pw.print(prefix); pw.print("  userId="); pw.print(ps.appId);
   2680                 pw.print(" gids="); pw.println(PackageManagerService.arrayToString(ps.gids));
   2681         if (ps.sharedUser != null) {
   2682             pw.print(prefix); pw.print("  sharedUser="); pw.println(ps.sharedUser);
   2683         }
   2684         pw.print(prefix); pw.print("  pkg="); pw.println(ps.pkg);
   2685         pw.print(prefix); pw.print("  codePath="); pw.println(ps.codePathString);
   2686         pw.print(prefix); pw.print("  resourcePath="); pw.println(ps.resourcePathString);
   2687         pw.print(prefix); pw.print("  nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
   2688         pw.print(prefix); pw.print("  versionCode="); pw.print(ps.versionCode);
   2689         if (ps.pkg != null) {
   2690             pw.print(" targetSdk="); pw.print(ps.pkg.applicationInfo.targetSdkVersion);
   2691         }
   2692         pw.println();
   2693         if (ps.pkg != null) {
   2694             pw.print(prefix); pw.print("  versionName="); pw.println(ps.pkg.mVersionName);
   2695             pw.print(prefix); pw.print("  applicationInfo=");
   2696                 pw.println(ps.pkg.applicationInfo.toString());
   2697             pw.print(prefix); pw.print("  flags="); printFlags(pw, ps.pkg.applicationInfo.flags,
   2698                     FLAG_DUMP_SPEC); pw.println();
   2699             pw.print(prefix); pw.print("  dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
   2700             if (ps.pkg.mOperationPending) {
   2701                 pw.print(prefix); pw.println("  mOperationPending=true");
   2702             }
   2703             pw.print(prefix); pw.print("  supportsScreens=[");
   2704             boolean first = true;
   2705             if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
   2706                 if (!first)
   2707                     pw.print(", ");
   2708                 first = false;
   2709                 pw.print("small");
   2710             }
   2711             if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
   2712                 if (!first)
   2713                     pw.print(", ");
   2714                 first = false;
   2715                 pw.print("medium");
   2716             }
   2717             if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
   2718                 if (!first)
   2719                     pw.print(", ");
   2720                 first = false;
   2721                 pw.print("large");
   2722             }
   2723             if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
   2724                 if (!first)
   2725                     pw.print(", ");
   2726                 first = false;
   2727                 pw.print("xlarge");
   2728             }
   2729             if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
   2730                 if (!first)
   2731                     pw.print(", ");
   2732                 first = false;
   2733                 pw.print("resizeable");
   2734             }
   2735             if ((ps.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
   2736                 if (!first)
   2737                     pw.print(", ");
   2738                 first = false;
   2739                 pw.print("anyDensity");
   2740             }
   2741             pw.println("]");
   2742             if (ps.pkg.libraryNames != null && ps.pkg.libraryNames.size() > 0) {
   2743                 pw.print(prefix); pw.println("  libraries:");
   2744                 for (int i=0; i<ps.pkg.libraryNames.size(); i++) {
   2745                     pw.print(prefix); pw.print("    "); pw.println(ps.pkg.libraryNames.get(i));
   2746                 }
   2747             }
   2748             if (ps.pkg.usesLibraries != null && ps.pkg.usesLibraries.size() > 0) {
   2749                 pw.print(prefix); pw.println("  usesLibraries:");
   2750                 for (int i=0; i<ps.pkg.usesLibraries.size(); i++) {
   2751                     pw.print(prefix); pw.print("    "); pw.println(ps.pkg.usesLibraries.get(i));
   2752                 }
   2753             }
   2754             if (ps.pkg.usesOptionalLibraries != null
   2755                     && ps.pkg.usesOptionalLibraries.size() > 0) {
   2756                 pw.print(prefix); pw.println("  usesOptionalLibraries:");
   2757                 for (int i=0; i<ps.pkg.usesOptionalLibraries.size(); i++) {
   2758                     pw.print(prefix); pw.print("    ");
   2759                         pw.println(ps.pkg.usesOptionalLibraries.get(i));
   2760                 }
   2761             }
   2762             if (ps.pkg.usesLibraryFiles != null
   2763                     && ps.pkg.usesLibraryFiles.length > 0) {
   2764                 pw.print(prefix); pw.println("  usesLibraryFiles:");
   2765                 for (int i=0; i<ps.pkg.usesLibraryFiles.length; i++) {
   2766                     pw.print(prefix); pw.print("    "); pw.println(ps.pkg.usesLibraryFiles[i]);
   2767                 }
   2768             }
   2769         }
   2770         pw.print(prefix); pw.print("  timeStamp=");
   2771             date.setTime(ps.timeStamp);
   2772             pw.println(sdf.format(date));
   2773         pw.print(prefix); pw.print("  firstInstallTime=");
   2774             date.setTime(ps.firstInstallTime);
   2775             pw.println(sdf.format(date));
   2776         pw.print(prefix); pw.print("  lastUpdateTime=");
   2777             date.setTime(ps.lastUpdateTime);
   2778             pw.println(sdf.format(date));
   2779         if (ps.installerPackageName != null) {
   2780             pw.print(prefix); pw.print("  installerPackageName=");
   2781                     pw.println(ps.installerPackageName);
   2782         }
   2783         pw.print(prefix); pw.print("  signatures="); pw.println(ps.signatures);
   2784         pw.print(prefix); pw.print("  permissionsFixed="); pw.print(ps.permissionsFixed);
   2785                 pw.print(" haveGids="); pw.print(ps.haveGids);
   2786                 pw.print(" installStatus="); pw.println(ps.installStatus);
   2787         pw.print(prefix); pw.print("  pkgFlags="); printFlags(pw, ps.pkgFlags, FLAG_DUMP_SPEC);
   2788                 pw.println();
   2789         for (UserInfo user : users) {
   2790             pw.print(prefix); pw.print("  User "); pw.print(user.id); pw.print(": ");
   2791             pw.print(" installed=");
   2792             pw.print(ps.getInstalled(user.id));
   2793             pw.print(" stopped=");
   2794             pw.print(ps.getStopped(user.id));
   2795             pw.print(" notLaunched=");
   2796             pw.print(ps.getNotLaunched(user.id));
   2797             pw.print(" enabled=");
   2798             pw.println(ps.getEnabled(user.id));
   2799             String lastDisabledAppCaller = ps.getLastDisabledAppCaller(user.id);
   2800             if (lastDisabledAppCaller != null) {
   2801                 pw.print(prefix); pw.print("    lastDisabledCaller: ");
   2802                         pw.println(lastDisabledAppCaller);
   2803             }
   2804             HashSet<String> cmp = ps.getDisabledComponents(user.id);
   2805             if (cmp != null && cmp.size() > 0) {
   2806                 pw.print(prefix); pw.println("    disabledComponents:");
   2807                 for (String s : cmp) {
   2808                     pw.print(prefix); pw.print("    "); pw.println(s);
   2809                 }
   2810             }
   2811             cmp = ps.getEnabledComponents(user.id);
   2812             if (cmp != null && cmp.size() > 0) {
   2813                 pw.print(prefix); pw.println("    enabledComponents:");
   2814                 for (String s : cmp) {
   2815                     pw.print(prefix); pw.print("    "); pw.println(s);
   2816                 }
   2817             }
   2818         }
   2819         if (ps.grantedPermissions.size() > 0) {
   2820             pw.print(prefix); pw.println("  grantedPermissions:");
   2821             for (String s : ps.grantedPermissions) {
   2822                 pw.print(prefix); pw.print("    "); pw.println(s);
   2823             }
   2824         }
   2825     }
   2826 
   2827     void dumpPackagesLPr(PrintWriter pw, String packageName, DumpState dumpState) {
   2828         final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   2829         final Date date = new Date();
   2830         boolean printedSomething = false;
   2831         List<UserInfo> users = getAllUsers();
   2832         for (final PackageSetting ps : mPackages.values()) {
   2833             if (packageName != null && !packageName.equals(ps.realName)
   2834                     && !packageName.equals(ps.name)) {
   2835                 continue;
   2836             }
   2837 
   2838             if (packageName != null) {
   2839                 dumpState.setSharedUser(ps.sharedUser);
   2840             }
   2841 
   2842             if (!printedSomething) {
   2843                 if (dumpState.onTitlePrinted())
   2844                     pw.println(" ");
   2845                 pw.println("Packages:");
   2846                 printedSomething = true;
   2847             }
   2848             dumpPackageLPr(pw, "  ", ps, sdf, date, users);
   2849         }
   2850 
   2851         printedSomething = false;
   2852         if (mRenamedPackages.size() > 0) {
   2853             for (final Map.Entry<String, String> e : mRenamedPackages.entrySet()) {
   2854                 if (packageName != null && !packageName.equals(e.getKey())
   2855                         && !packageName.equals(e.getValue())) {
   2856                     continue;
   2857                 }
   2858                 if (!printedSomething) {
   2859                     if (dumpState.onTitlePrinted())
   2860                         pw.println(" ");
   2861                     pw.println("Renamed packages:");
   2862                     printedSomething = true;
   2863                 }
   2864                 pw.print("  ");
   2865                 pw.print(e.getKey());
   2866                 pw.print(" -> ");
   2867                 pw.println(e.getValue());
   2868             }
   2869         }
   2870 
   2871         printedSomething = false;
   2872         if (mDisabledSysPackages.size() > 0) {
   2873             for (final PackageSetting ps : mDisabledSysPackages.values()) {
   2874                 if (packageName != null && !packageName.equals(ps.realName)
   2875                         && !packageName.equals(ps.name)) {
   2876                     continue;
   2877                 }
   2878                 if (!printedSomething) {
   2879                     if (dumpState.onTitlePrinted())
   2880                         pw.println(" ");
   2881                     pw.println("Hidden system packages:");
   2882                     printedSomething = true;
   2883                 }
   2884                 dumpPackageLPr(pw, "  ", ps, sdf, date, users);
   2885             }
   2886         }
   2887     }
   2888 
   2889     void dumpPermissionsLPr(PrintWriter pw, String packageName, DumpState dumpState) {
   2890         boolean printedSomething = false;
   2891         for (BasePermission p : mPermissions.values()) {
   2892             if (packageName != null && !packageName.equals(p.sourcePackage)) {
   2893                 continue;
   2894             }
   2895             if (!printedSomething) {
   2896                 if (dumpState.onTitlePrinted())
   2897                     pw.println(" ");
   2898                 pw.println("Permissions:");
   2899                 printedSomething = true;
   2900             }
   2901             pw.print("  Permission ["); pw.print(p.name); pw.print("] (");
   2902                     pw.print(Integer.toHexString(System.identityHashCode(p)));
   2903                     pw.println("):");
   2904             pw.print("    sourcePackage="); pw.println(p.sourcePackage);
   2905             pw.print("    uid="); pw.print(p.uid);
   2906                     pw.print(" gids="); pw.print(PackageManagerService.arrayToString(p.gids));
   2907                     pw.print(" type="); pw.print(p.type);
   2908                     pw.print(" prot=");
   2909                     pw.println(PermissionInfo.protectionToString(p.protectionLevel));
   2910             if (p.packageSetting != null) {
   2911                 pw.print("    packageSetting="); pw.println(p.packageSetting);
   2912             }
   2913             if (p.perm != null) {
   2914                 pw.print("    perm="); pw.println(p.perm);
   2915             }
   2916             if (READ_EXTERNAL_STORAGE.equals(p.name)) {
   2917                 pw.print("    enforced=");
   2918                 pw.println(mReadExternalStorageEnforced);
   2919             }
   2920         }
   2921     }
   2922 
   2923     void dumpSharedUsersLPr(PrintWriter pw, String packageName, DumpState dumpState) {
   2924         boolean printedSomething = false;
   2925         for (SharedUserSetting su : mSharedUsers.values()) {
   2926             if (packageName != null && su != dumpState.getSharedUser()) {
   2927                 continue;
   2928             }
   2929             if (!printedSomething) {
   2930                 if (dumpState.onTitlePrinted())
   2931                     pw.println(" ");
   2932                 pw.println("Shared users:");
   2933                 printedSomething = true;
   2934             }
   2935             pw.print("  SharedUser [");
   2936             pw.print(su.name);
   2937             pw.print("] (");
   2938             pw.print(Integer.toHexString(System.identityHashCode(su)));
   2939                     pw.println("):");
   2940             pw.print("    userId=");
   2941             pw.print(su.userId);
   2942             pw.print(" gids=");
   2943             pw.println(PackageManagerService.arrayToString(su.gids));
   2944             pw.println("    grantedPermissions:");
   2945             for (String s : su.grantedPermissions) {
   2946                 pw.print("      ");
   2947                 pw.println(s);
   2948             }
   2949         }
   2950     }
   2951 
   2952     void dumpReadMessagesLPr(PrintWriter pw, DumpState dumpState) {
   2953         pw.println("Settings parse messages:");
   2954         pw.print(mReadMessages.toString());
   2955     }
   2956 }
   2957