Home | History | Annotate | Download | only in pm
      1 /*
      2  * Copyright (C) 2007 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 android.content.pm;
     18 
     19 import android.content.ComponentName;
     20 import android.content.Intent;
     21 import android.content.IntentFilter;
     22 import android.content.res.AssetManager;
     23 import android.content.res.Configuration;
     24 import android.content.res.Resources;
     25 import android.content.res.TypedArray;
     26 import android.content.res.XmlResourceParser;
     27 import android.os.Build;
     28 import android.os.Bundle;
     29 import android.os.PatternMatcher;
     30 import android.os.UserHandle;
     31 import android.util.AttributeSet;
     32 import android.util.Base64;
     33 import android.util.DisplayMetrics;
     34 import android.util.Log;
     35 import android.util.Slog;
     36 import android.util.TypedValue;
     37 
     38 import java.io.BufferedInputStream;
     39 import java.io.File;
     40 import java.io.IOException;
     41 import java.io.InputStream;
     42 import java.io.PrintWriter;
     43 import java.lang.ref.WeakReference;
     44 import java.security.KeyFactory;
     45 import java.security.NoSuchAlgorithmException;
     46 import java.security.PublicKey;
     47 import java.security.cert.Certificate;
     48 import java.security.cert.CertificateEncodingException;
     49 import java.security.spec.EncodedKeySpec;
     50 import java.security.spec.InvalidKeySpecException;
     51 import java.security.spec.X509EncodedKeySpec;
     52 import java.util.ArrayList;
     53 import java.util.Enumeration;
     54 import java.util.HashMap;
     55 import java.util.HashSet;
     56 import java.util.Iterator;
     57 import java.util.List;
     58 import java.util.Map;
     59 import java.util.Set;
     60 import java.util.jar.JarEntry;
     61 import java.util.jar.JarFile;
     62 import java.util.zip.ZipEntry;
     63 
     64 import com.android.internal.util.XmlUtils;
     65 
     66 import org.xmlpull.v1.XmlPullParser;
     67 import org.xmlpull.v1.XmlPullParserException;
     68 
     69 /**
     70  * Package archive parsing
     71  *
     72  * {@hide}
     73  */
     74 public class PackageParser {
     75     private static final boolean DEBUG_JAR = false;
     76     private static final boolean DEBUG_PARSER = false;
     77     private static final boolean DEBUG_BACKUP = false;
     78 
     79     /** File name in an APK for the Android manifest. */
     80     private static final String ANDROID_MANIFEST_FILENAME = "AndroidManifest.xml";
     81 
     82     /** @hide */
     83     public static class NewPermissionInfo {
     84         public final String name;
     85         public final int sdkVersion;
     86         public final int fileVersion;
     87 
     88         public NewPermissionInfo(String name, int sdkVersion, int fileVersion) {
     89             this.name = name;
     90             this.sdkVersion = sdkVersion;
     91             this.fileVersion = fileVersion;
     92         }
     93     }
     94 
     95     /** @hide */
     96     public static class SplitPermissionInfo {
     97         public final String rootPerm;
     98         public final String[] newPerms;
     99         public final int targetSdk;
    100 
    101         public SplitPermissionInfo(String rootPerm, String[] newPerms, int targetSdk) {
    102             this.rootPerm = rootPerm;
    103             this.newPerms = newPerms;
    104             this.targetSdk = targetSdk;
    105         }
    106     }
    107 
    108     /**
    109      * List of new permissions that have been added since 1.0.
    110      * NOTE: These must be declared in SDK version order, with permissions
    111      * added to older SDKs appearing before those added to newer SDKs.
    112      * If sdkVersion is 0, then this is not a permission that we want to
    113      * automatically add to older apps, but we do want to allow it to be
    114      * granted during a platform update.
    115      * @hide
    116      */
    117     public static final PackageParser.NewPermissionInfo NEW_PERMISSIONS[] =
    118         new PackageParser.NewPermissionInfo[] {
    119             new PackageParser.NewPermissionInfo(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
    120                     android.os.Build.VERSION_CODES.DONUT, 0),
    121             new PackageParser.NewPermissionInfo(android.Manifest.permission.READ_PHONE_STATE,
    122                     android.os.Build.VERSION_CODES.DONUT, 0)
    123     };
    124 
    125     /**
    126      * List of permissions that have been split into more granular or dependent
    127      * permissions.
    128      * @hide
    129      */
    130     public static final PackageParser.SplitPermissionInfo SPLIT_PERMISSIONS[] =
    131         new PackageParser.SplitPermissionInfo[] {
    132             // READ_EXTERNAL_STORAGE is always required when an app requests
    133             // WRITE_EXTERNAL_STORAGE, because we can't have an app that has
    134             // write access without read access.  The hack here with the target
    135             // target SDK version ensures that this grant is always done.
    136             new PackageParser.SplitPermissionInfo(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
    137                     new String[] { android.Manifest.permission.READ_EXTERNAL_STORAGE },
    138                     android.os.Build.VERSION_CODES.CUR_DEVELOPMENT+1),
    139             new PackageParser.SplitPermissionInfo(android.Manifest.permission.READ_CONTACTS,
    140                     new String[] { android.Manifest.permission.READ_CALL_LOG },
    141                     android.os.Build.VERSION_CODES.JELLY_BEAN),
    142             new PackageParser.SplitPermissionInfo(android.Manifest.permission.WRITE_CONTACTS,
    143                     new String[] { android.Manifest.permission.WRITE_CALL_LOG },
    144                     android.os.Build.VERSION_CODES.JELLY_BEAN)
    145     };
    146 
    147     private String mArchiveSourcePath;
    148     private String[] mSeparateProcesses;
    149     private boolean mOnlyCoreApps;
    150     private static final int SDK_VERSION = Build.VERSION.SDK_INT;
    151     private static final String SDK_CODENAME = "REL".equals(Build.VERSION.CODENAME)
    152             ? null : Build.VERSION.CODENAME;
    153 
    154     private int mParseError = PackageManager.INSTALL_SUCCEEDED;
    155 
    156     private static final Object mSync = new Object();
    157     private static WeakReference<byte[]> mReadBuffer;
    158 
    159     private static boolean sCompatibilityModeEnabled = true;
    160     private static final int PARSE_DEFAULT_INSTALL_LOCATION =
    161             PackageInfo.INSTALL_LOCATION_UNSPECIFIED;
    162 
    163     static class ParsePackageItemArgs {
    164         final Package owner;
    165         final String[] outError;
    166         final int nameRes;
    167         final int labelRes;
    168         final int iconRes;
    169         final int logoRes;
    170 
    171         String tag;
    172         TypedArray sa;
    173 
    174         ParsePackageItemArgs(Package _owner, String[] _outError,
    175                 int _nameRes, int _labelRes, int _iconRes, int _logoRes) {
    176             owner = _owner;
    177             outError = _outError;
    178             nameRes = _nameRes;
    179             labelRes = _labelRes;
    180             iconRes = _iconRes;
    181             logoRes = _logoRes;
    182         }
    183     }
    184 
    185     static class ParseComponentArgs extends ParsePackageItemArgs {
    186         final String[] sepProcesses;
    187         final int processRes;
    188         final int descriptionRes;
    189         final int enabledRes;
    190         int flags;
    191 
    192         ParseComponentArgs(Package _owner, String[] _outError,
    193                 int _nameRes, int _labelRes, int _iconRes, int _logoRes,
    194                 String[] _sepProcesses, int _processRes,
    195                 int _descriptionRes, int _enabledRes) {
    196             super(_owner, _outError, _nameRes, _labelRes, _iconRes, _logoRes);
    197             sepProcesses = _sepProcesses;
    198             processRes = _processRes;
    199             descriptionRes = _descriptionRes;
    200             enabledRes = _enabledRes;
    201         }
    202     }
    203 
    204     /* Light weight package info.
    205      * @hide
    206      */
    207     public static class PackageLite {
    208         public final String packageName;
    209         public final int versionCode;
    210         public final int installLocation;
    211         public final VerifierInfo[] verifiers;
    212 
    213         public PackageLite(String packageName, int versionCode,
    214                 int installLocation, List<VerifierInfo> verifiers) {
    215             this.packageName = packageName;
    216             this.versionCode = versionCode;
    217             this.installLocation = installLocation;
    218             this.verifiers = verifiers.toArray(new VerifierInfo[verifiers.size()]);
    219         }
    220     }
    221 
    222     private ParsePackageItemArgs mParseInstrumentationArgs;
    223     private ParseComponentArgs mParseActivityArgs;
    224     private ParseComponentArgs mParseActivityAliasArgs;
    225     private ParseComponentArgs mParseServiceArgs;
    226     private ParseComponentArgs mParseProviderArgs;
    227 
    228     /** If set to true, we will only allow package files that exactly match
    229      *  the DTD.  Otherwise, we try to get as much from the package as we
    230      *  can without failing.  This should normally be set to false, to
    231      *  support extensions to the DTD in future versions. */
    232     private static final boolean RIGID_PARSER = false;
    233 
    234     private static final String TAG = "PackageParser";
    235 
    236     public PackageParser(String archiveSourcePath) {
    237         mArchiveSourcePath = archiveSourcePath;
    238     }
    239 
    240     public void setSeparateProcesses(String[] procs) {
    241         mSeparateProcesses = procs;
    242     }
    243 
    244     public void setOnlyCoreApps(boolean onlyCoreApps) {
    245         mOnlyCoreApps = onlyCoreApps;
    246     }
    247 
    248     private static final boolean isPackageFilename(String name) {
    249         return name.endsWith(".apk");
    250     }
    251 
    252     /*
    253     public static PackageInfo generatePackageInfo(PackageParser.Package p,
    254             int gids[], int flags, long firstInstallTime, long lastUpdateTime,
    255             HashSet<String> grantedPermissions) {
    256         PackageUserState state = new PackageUserState();
    257         return generatePackageInfo(p, gids, flags, firstInstallTime, lastUpdateTime,
    258                 grantedPermissions, state, UserHandle.getCallingUserId());
    259     }
    260     */
    261 
    262     /**
    263      * Generate and return the {@link PackageInfo} for a parsed package.
    264      *
    265      * @param p the parsed package.
    266      * @param flags indicating which optional information is included.
    267      */
    268     public static PackageInfo generatePackageInfo(PackageParser.Package p,
    269             int gids[], int flags, long firstInstallTime, long lastUpdateTime,
    270             HashSet<String> grantedPermissions, PackageUserState state) {
    271 
    272         return generatePackageInfo(p, gids, flags, firstInstallTime, lastUpdateTime,
    273                 grantedPermissions, state, UserHandle.getCallingUserId());
    274     }
    275 
    276     /**
    277      * Returns true if the package is installed and not blocked, or if the caller
    278      * explicitly wanted all uninstalled and blocked packages as well.
    279      */
    280     private static boolean checkUseInstalledOrBlocked(int flags, PackageUserState state) {
    281         return (state.installed && !state.blocked)
    282                 || (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
    283     }
    284 
    285     public static boolean isAvailable(PackageUserState state) {
    286         return checkUseInstalledOrBlocked(0, state);
    287     }
    288 
    289     public static PackageInfo generatePackageInfo(PackageParser.Package p,
    290             int gids[], int flags, long firstInstallTime, long lastUpdateTime,
    291             HashSet<String> grantedPermissions, PackageUserState state, int userId) {
    292 
    293         if (!checkUseInstalledOrBlocked(flags, state)) {
    294             return null;
    295         }
    296         PackageInfo pi = new PackageInfo();
    297         pi.packageName = p.packageName;
    298         pi.versionCode = p.mVersionCode;
    299         pi.versionName = p.mVersionName;
    300         pi.sharedUserId = p.mSharedUserId;
    301         pi.sharedUserLabel = p.mSharedUserLabel;
    302         pi.applicationInfo = generateApplicationInfo(p, flags, state, userId);
    303         pi.installLocation = p.installLocation;
    304         if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0
    305                 || (pi.applicationInfo.flags&ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
    306             pi.requiredForAllUsers = p.mRequiredForAllUsers;
    307         }
    308         pi.restrictedAccountType = p.mRestrictedAccountType;
    309         pi.requiredAccountType = p.mRequiredAccountType;
    310         pi.firstInstallTime = firstInstallTime;
    311         pi.lastUpdateTime = lastUpdateTime;
    312         if ((flags&PackageManager.GET_GIDS) != 0) {
    313             pi.gids = gids;
    314         }
    315         if ((flags&PackageManager.GET_CONFIGURATIONS) != 0) {
    316             int N = p.configPreferences.size();
    317             if (N > 0) {
    318                 pi.configPreferences = new ConfigurationInfo[N];
    319                 p.configPreferences.toArray(pi.configPreferences);
    320             }
    321             N = p.reqFeatures != null ? p.reqFeatures.size() : 0;
    322             if (N > 0) {
    323                 pi.reqFeatures = new FeatureInfo[N];
    324                 p.reqFeatures.toArray(pi.reqFeatures);
    325             }
    326         }
    327         if ((flags&PackageManager.GET_ACTIVITIES) != 0) {
    328             int N = p.activities.size();
    329             if (N > 0) {
    330                 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    331                     pi.activities = new ActivityInfo[N];
    332                 } else {
    333                     int num = 0;
    334                     for (int i=0; i<N; i++) {
    335                         if (p.activities.get(i).info.enabled) num++;
    336                     }
    337                     pi.activities = new ActivityInfo[num];
    338                 }
    339                 for (int i=0, j=0; i<N; i++) {
    340                     final Activity activity = p.activities.get(i);
    341                     if (activity.info.enabled
    342                         || (flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    343                         pi.activities[j++] = generateActivityInfo(p.activities.get(i), flags,
    344                                 state, userId);
    345                     }
    346                 }
    347             }
    348         }
    349         if ((flags&PackageManager.GET_RECEIVERS) != 0) {
    350             int N = p.receivers.size();
    351             if (N > 0) {
    352                 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    353                     pi.receivers = new ActivityInfo[N];
    354                 } else {
    355                     int num = 0;
    356                     for (int i=0; i<N; i++) {
    357                         if (p.receivers.get(i).info.enabled) num++;
    358                     }
    359                     pi.receivers = new ActivityInfo[num];
    360                 }
    361                 for (int i=0, j=0; i<N; i++) {
    362                     final Activity activity = p.receivers.get(i);
    363                     if (activity.info.enabled
    364                         || (flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    365                         pi.receivers[j++] = generateActivityInfo(p.receivers.get(i), flags,
    366                                 state, userId);
    367                     }
    368                 }
    369             }
    370         }
    371         if ((flags&PackageManager.GET_SERVICES) != 0) {
    372             int N = p.services.size();
    373             if (N > 0) {
    374                 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    375                     pi.services = new ServiceInfo[N];
    376                 } else {
    377                     int num = 0;
    378                     for (int i=0; i<N; i++) {
    379                         if (p.services.get(i).info.enabled) num++;
    380                     }
    381                     pi.services = new ServiceInfo[num];
    382                 }
    383                 for (int i=0, j=0; i<N; i++) {
    384                     final Service service = p.services.get(i);
    385                     if (service.info.enabled
    386                         || (flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    387                         pi.services[j++] = generateServiceInfo(p.services.get(i), flags,
    388                                 state, userId);
    389                     }
    390                 }
    391             }
    392         }
    393         if ((flags&PackageManager.GET_PROVIDERS) != 0) {
    394             int N = p.providers.size();
    395             if (N > 0) {
    396                 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    397                     pi.providers = new ProviderInfo[N];
    398                 } else {
    399                     int num = 0;
    400                     for (int i=0; i<N; i++) {
    401                         if (p.providers.get(i).info.enabled) num++;
    402                     }
    403                     pi.providers = new ProviderInfo[num];
    404                 }
    405                 for (int i=0, j=0; i<N; i++) {
    406                     final Provider provider = p.providers.get(i);
    407                     if (provider.info.enabled
    408                         || (flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
    409                         pi.providers[j++] = generateProviderInfo(p.providers.get(i), flags,
    410                                 state, userId);
    411                     }
    412                 }
    413             }
    414         }
    415         if ((flags&PackageManager.GET_INSTRUMENTATION) != 0) {
    416             int N = p.instrumentation.size();
    417             if (N > 0) {
    418                 pi.instrumentation = new InstrumentationInfo[N];
    419                 for (int i=0; i<N; i++) {
    420                     pi.instrumentation[i] = generateInstrumentationInfo(
    421                             p.instrumentation.get(i), flags);
    422                 }
    423             }
    424         }
    425         if ((flags&PackageManager.GET_PERMISSIONS) != 0) {
    426             int N = p.permissions.size();
    427             if (N > 0) {
    428                 pi.permissions = new PermissionInfo[N];
    429                 for (int i=0; i<N; i++) {
    430                     pi.permissions[i] = generatePermissionInfo(p.permissions.get(i), flags);
    431                 }
    432             }
    433             N = p.requestedPermissions.size();
    434             if (N > 0) {
    435                 pi.requestedPermissions = new String[N];
    436                 pi.requestedPermissionsFlags = new int[N];
    437                 for (int i=0; i<N; i++) {
    438                     final String perm = p.requestedPermissions.get(i);
    439                     pi.requestedPermissions[i] = perm;
    440                     if (p.requestedPermissionsRequired.get(i)) {
    441                         pi.requestedPermissionsFlags[i] |= PackageInfo.REQUESTED_PERMISSION_REQUIRED;
    442                     }
    443                     if (grantedPermissions != null && grantedPermissions.contains(perm)) {
    444                         pi.requestedPermissionsFlags[i] |= PackageInfo.REQUESTED_PERMISSION_GRANTED;
    445                     }
    446                 }
    447             }
    448         }
    449         if ((flags&PackageManager.GET_SIGNATURES) != 0) {
    450            int N = (p.mSignatures != null) ? p.mSignatures.length : 0;
    451            if (N > 0) {
    452                 pi.signatures = new Signature[N];
    453                 System.arraycopy(p.mSignatures, 0, pi.signatures, 0, N);
    454             }
    455         }
    456         return pi;
    457     }
    458 
    459     private Certificate[] loadCertificates(JarFile jarFile, JarEntry je,
    460             byte[] readBuffer) {
    461         try {
    462             // We must read the stream for the JarEntry to retrieve
    463             // its certificates.
    464             InputStream is = new BufferedInputStream(jarFile.getInputStream(je));
    465             while (is.read(readBuffer, 0, readBuffer.length) != -1) {
    466                 // not using
    467             }
    468             is.close();
    469             return je != null ? je.getCertificates() : null;
    470         } catch (IOException e) {
    471             Slog.w(TAG, "Exception reading " + je.getName() + " in "
    472                     + jarFile.getName(), e);
    473         } catch (RuntimeException e) {
    474             Slog.w(TAG, "Exception reading " + je.getName() + " in "
    475                     + jarFile.getName(), e);
    476         }
    477         return null;
    478     }
    479 
    480     public final static int PARSE_IS_SYSTEM = 1<<0;
    481     public final static int PARSE_CHATTY = 1<<1;
    482     public final static int PARSE_MUST_BE_APK = 1<<2;
    483     public final static int PARSE_IGNORE_PROCESSES = 1<<3;
    484     public final static int PARSE_FORWARD_LOCK = 1<<4;
    485     public final static int PARSE_ON_SDCARD = 1<<5;
    486     public final static int PARSE_IS_SYSTEM_DIR = 1<<6;
    487     public final static int PARSE_IS_PRIVILEGED = 1<<7;
    488 
    489     public int getParseError() {
    490         return mParseError;
    491     }
    492 
    493     public Package parsePackage(File sourceFile, String destCodePath,
    494             DisplayMetrics metrics, int flags) {
    495         mParseError = PackageManager.INSTALL_SUCCEEDED;
    496 
    497         mArchiveSourcePath = sourceFile.getPath();
    498         if (!sourceFile.isFile()) {
    499             Slog.w(TAG, "Skipping dir: " + mArchiveSourcePath);
    500             mParseError = PackageManager.INSTALL_PARSE_FAILED_NOT_APK;
    501             return null;
    502         }
    503         if (!isPackageFilename(sourceFile.getName())
    504                 && (flags&PARSE_MUST_BE_APK) != 0) {
    505             if ((flags&PARSE_IS_SYSTEM) == 0) {
    506                 // We expect to have non-.apk files in the system dir,
    507                 // so don't warn about them.
    508                 Slog.w(TAG, "Skipping non-package file: " + mArchiveSourcePath);
    509             }
    510             mParseError = PackageManager.INSTALL_PARSE_FAILED_NOT_APK;
    511             return null;
    512         }
    513 
    514         if (DEBUG_JAR)
    515             Slog.d(TAG, "Scanning package: " + mArchiveSourcePath);
    516 
    517         XmlResourceParser parser = null;
    518         AssetManager assmgr = null;
    519         Resources res = null;
    520         boolean assetError = true;
    521         try {
    522             assmgr = new AssetManager();
    523             int cookie = assmgr.addAssetPath(mArchiveSourcePath);
    524             if (cookie != 0) {
    525                 res = new Resources(assmgr, metrics, null);
    526                 assmgr.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    527                         Build.VERSION.RESOURCES_SDK_INT);
    528                 parser = assmgr.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);
    529                 assetError = false;
    530             } else {
    531                 Slog.w(TAG, "Failed adding asset path:"+mArchiveSourcePath);
    532             }
    533         } catch (Exception e) {
    534             Slog.w(TAG, "Unable to read AndroidManifest.xml of "
    535                     + mArchiveSourcePath, e);
    536         }
    537         if (assetError) {
    538             if (assmgr != null) assmgr.close();
    539             mParseError = PackageManager.INSTALL_PARSE_FAILED_BAD_MANIFEST;
    540             return null;
    541         }
    542         String[] errorText = new String[1];
    543         Package pkg = null;
    544         Exception errorException = null;
    545         try {
    546             // XXXX todo: need to figure out correct configuration.
    547             pkg = parsePackage(res, parser, flags, errorText);
    548         } catch (Exception e) {
    549             errorException = e;
    550             mParseError = PackageManager.INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
    551         }
    552 
    553 
    554         if (pkg == null) {
    555             // If we are only parsing core apps, then a null with INSTALL_SUCCEEDED
    556             // just means to skip this app so don't make a fuss about it.
    557             if (!mOnlyCoreApps || mParseError != PackageManager.INSTALL_SUCCEEDED) {
    558                 if (errorException != null) {
    559                     Slog.w(TAG, mArchiveSourcePath, errorException);
    560                 } else {
    561                     Slog.w(TAG, mArchiveSourcePath + " (at "
    562                             + parser.getPositionDescription()
    563                             + "): " + errorText[0]);
    564                 }
    565                 if (mParseError == PackageManager.INSTALL_SUCCEEDED) {
    566                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
    567                 }
    568             }
    569             parser.close();
    570             assmgr.close();
    571             return null;
    572         }
    573 
    574         parser.close();
    575         assmgr.close();
    576 
    577         // Set code and resource paths
    578         pkg.mPath = destCodePath;
    579         pkg.mScanPath = mArchiveSourcePath;
    580         //pkg.applicationInfo.sourceDir = destCodePath;
    581         //pkg.applicationInfo.publicSourceDir = destRes;
    582         pkg.mSignatures = null;
    583 
    584         return pkg;
    585     }
    586 
    587     /**
    588      * Gathers the {@link ManifestDigest} for {@code pkg} if it exists in the
    589      * APK. If it successfully scanned the package and found the
    590      * {@code AndroidManifest.xml}, {@code true} is returned.
    591      */
    592     public boolean collectManifestDigest(Package pkg) {
    593         try {
    594             final JarFile jarFile = new JarFile(mArchiveSourcePath);
    595             try {
    596                 final ZipEntry je = jarFile.getEntry(ANDROID_MANIFEST_FILENAME);
    597                 if (je != null) {
    598                     pkg.manifestDigest = ManifestDigest.fromInputStream(jarFile.getInputStream(je));
    599                 }
    600             } finally {
    601                 jarFile.close();
    602             }
    603             return true;
    604         } catch (IOException e) {
    605             return false;
    606         }
    607     }
    608 
    609     public boolean collectCertificates(Package pkg, int flags) {
    610         pkg.mSignatures = null;
    611 
    612         WeakReference<byte[]> readBufferRef;
    613         byte[] readBuffer = null;
    614         synchronized (mSync) {
    615             readBufferRef = mReadBuffer;
    616             if (readBufferRef != null) {
    617                 mReadBuffer = null;
    618                 readBuffer = readBufferRef.get();
    619             }
    620             if (readBuffer == null) {
    621                 readBuffer = new byte[8192];
    622                 readBufferRef = new WeakReference<byte[]>(readBuffer);
    623             }
    624         }
    625 
    626         try {
    627             JarFile jarFile = new JarFile(mArchiveSourcePath);
    628 
    629             Certificate[] certs = null;
    630 
    631             if ((flags&PARSE_IS_SYSTEM) != 0) {
    632                 // If this package comes from the system image, then we
    633                 // can trust it...  we'll just use the AndroidManifest.xml
    634                 // to retrieve its signatures, not validating all of the
    635                 // files.
    636                 JarEntry jarEntry = jarFile.getJarEntry(ANDROID_MANIFEST_FILENAME);
    637                 certs = loadCertificates(jarFile, jarEntry, readBuffer);
    638                 if (certs == null) {
    639                     Slog.e(TAG, "Package " + pkg.packageName
    640                             + " has no certificates at entry "
    641                             + jarEntry.getName() + "; ignoring!");
    642                     jarFile.close();
    643                     mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
    644                     return false;
    645                 }
    646                 if (DEBUG_JAR) {
    647                     Slog.i(TAG, "File " + mArchiveSourcePath + ": entry=" + jarEntry
    648                             + " certs=" + (certs != null ? certs.length : 0));
    649                     if (certs != null) {
    650                         final int N = certs.length;
    651                         for (int i=0; i<N; i++) {
    652                             Slog.i(TAG, "  Public key: "
    653                                     + certs[i].getPublicKey().getEncoded()
    654                                     + " " + certs[i].getPublicKey());
    655                         }
    656                     }
    657                 }
    658             } else {
    659                 Enumeration<JarEntry> entries = jarFile.entries();
    660                 while (entries.hasMoreElements()) {
    661                     final JarEntry je = entries.nextElement();
    662                     if (je.isDirectory()) continue;
    663 
    664                     final String name = je.getName();
    665 
    666                     if (name.startsWith("META-INF/"))
    667                         continue;
    668 
    669                     if (ANDROID_MANIFEST_FILENAME.equals(name)) {
    670                         pkg.manifestDigest =
    671                                 ManifestDigest.fromInputStream(jarFile.getInputStream(je));
    672                     }
    673 
    674                     final Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
    675                     if (DEBUG_JAR) {
    676                         Slog.i(TAG, "File " + mArchiveSourcePath + " entry " + je.getName()
    677                                 + ": certs=" + certs + " ("
    678                                 + (certs != null ? certs.length : 0) + ")");
    679                     }
    680 
    681                     if (localCerts == null) {
    682                         Slog.e(TAG, "Package " + pkg.packageName
    683                                 + " has no certificates at entry "
    684                                 + je.getName() + "; ignoring!");
    685                         jarFile.close();
    686                         mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
    687                         return false;
    688                     } else if (certs == null) {
    689                         certs = localCerts;
    690                     } else {
    691                         // Ensure all certificates match.
    692                         for (int i=0; i<certs.length; i++) {
    693                             boolean found = false;
    694                             for (int j=0; j<localCerts.length; j++) {
    695                                 if (certs[i] != null &&
    696                                         certs[i].equals(localCerts[j])) {
    697                                     found = true;
    698                                     break;
    699                                 }
    700                             }
    701                             if (!found || certs.length != localCerts.length) {
    702                                 Slog.e(TAG, "Package " + pkg.packageName
    703                                         + " has mismatched certificates at entry "
    704                                         + je.getName() + "; ignoring!");
    705                                 jarFile.close();
    706                                 mParseError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
    707                                 return false;
    708                             }
    709                         }
    710                     }
    711                 }
    712             }
    713             jarFile.close();
    714 
    715             synchronized (mSync) {
    716                 mReadBuffer = readBufferRef;
    717             }
    718 
    719             if (certs != null && certs.length > 0) {
    720                 final int N = certs.length;
    721                 pkg.mSignatures = new Signature[certs.length];
    722                 for (int i=0; i<N; i++) {
    723                     pkg.mSignatures[i] = new Signature(
    724                             certs[i].getEncoded());
    725                 }
    726             } else {
    727                 Slog.e(TAG, "Package " + pkg.packageName
    728                         + " has no certificates; ignoring!");
    729                 mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
    730                 return false;
    731             }
    732 
    733             // Add the signing KeySet to the system
    734             pkg.mSigningKeys = new HashSet<PublicKey>();
    735             for (int i=0; i < certs.length; i++) {
    736                 pkg.mSigningKeys.add(certs[i].getPublicKey());
    737             }
    738 
    739         } catch (CertificateEncodingException e) {
    740             Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
    741             mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
    742             return false;
    743         } catch (IOException e) {
    744             Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
    745             mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
    746             return false;
    747         } catch (RuntimeException e) {
    748             Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
    749             mParseError = PackageManager.INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
    750             return false;
    751         }
    752 
    753         return true;
    754     }
    755 
    756     /*
    757      * Utility method that retrieves just the package name and install
    758      * location from the apk location at the given file path.
    759      * @param packageFilePath file location of the apk
    760      * @param flags Special parse flags
    761      * @return PackageLite object with package information or null on failure.
    762      */
    763     public static PackageLite parsePackageLite(String packageFilePath, int flags) {
    764         AssetManager assmgr = null;
    765         final XmlResourceParser parser;
    766         final Resources res;
    767         try {
    768             assmgr = new AssetManager();
    769             assmgr.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    770                     Build.VERSION.RESOURCES_SDK_INT);
    771 
    772             int cookie = assmgr.addAssetPath(packageFilePath);
    773             if (cookie == 0) {
    774                 return null;
    775             }
    776 
    777             final DisplayMetrics metrics = new DisplayMetrics();
    778             metrics.setToDefaults();
    779             res = new Resources(assmgr, metrics, null);
    780             parser = assmgr.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);
    781         } catch (Exception e) {
    782             if (assmgr != null) assmgr.close();
    783             Slog.w(TAG, "Unable to read AndroidManifest.xml of "
    784                     + packageFilePath, e);
    785             return null;
    786         }
    787 
    788         final AttributeSet attrs = parser;
    789         final String errors[] = new String[1];
    790         PackageLite packageLite = null;
    791         try {
    792             packageLite = parsePackageLite(res, parser, attrs, flags, errors);
    793         } catch (IOException e) {
    794             Slog.w(TAG, packageFilePath, e);
    795         } catch (XmlPullParserException e) {
    796             Slog.w(TAG, packageFilePath, e);
    797         } finally {
    798             if (parser != null) parser.close();
    799             if (assmgr != null) assmgr.close();
    800         }
    801         if (packageLite == null) {
    802             Slog.e(TAG, "parsePackageLite error: " + errors[0]);
    803             return null;
    804         }
    805         return packageLite;
    806     }
    807 
    808     private static String validateName(String name, boolean requiresSeparator) {
    809         final int N = name.length();
    810         boolean hasSep = false;
    811         boolean front = true;
    812         for (int i=0; i<N; i++) {
    813             final char c = name.charAt(i);
    814             if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
    815                 front = false;
    816                 continue;
    817             }
    818             if (!front) {
    819                 if ((c >= '0' && c <= '9') || c == '_') {
    820                     continue;
    821                 }
    822             }
    823             if (c == '.') {
    824                 hasSep = true;
    825                 front = true;
    826                 continue;
    827             }
    828             return "bad character '" + c + "'";
    829         }
    830         return hasSep || !requiresSeparator
    831                 ? null : "must have at least one '.' separator";
    832     }
    833 
    834     private static String parsePackageName(XmlPullParser parser,
    835             AttributeSet attrs, int flags, String[] outError)
    836             throws IOException, XmlPullParserException {
    837 
    838         int type;
    839         while ((type = parser.next()) != XmlPullParser.START_TAG
    840                 && type != XmlPullParser.END_DOCUMENT) {
    841             ;
    842         }
    843 
    844         if (type != XmlPullParser.START_TAG) {
    845             outError[0] = "No start tag found";
    846             return null;
    847         }
    848         if (DEBUG_PARSER)
    849             Slog.v(TAG, "Root element name: '" + parser.getName() + "'");
    850         if (!parser.getName().equals("manifest")) {
    851             outError[0] = "No <manifest> tag";
    852             return null;
    853         }
    854         String pkgName = attrs.getAttributeValue(null, "package");
    855         if (pkgName == null || pkgName.length() == 0) {
    856             outError[0] = "<manifest> does not specify package";
    857             return null;
    858         }
    859         String nameError = validateName(pkgName, true);
    860         if (nameError != null && !"android".equals(pkgName)) {
    861             outError[0] = "<manifest> specifies bad package name \""
    862                 + pkgName + "\": " + nameError;
    863             return null;
    864         }
    865 
    866         return pkgName.intern();
    867     }
    868 
    869     private static PackageLite parsePackageLite(Resources res, XmlPullParser parser,
    870             AttributeSet attrs, int flags, String[] outError) throws IOException,
    871             XmlPullParserException {
    872 
    873         int type;
    874         while ((type = parser.next()) != XmlPullParser.START_TAG
    875                 && type != XmlPullParser.END_DOCUMENT) {
    876             ;
    877         }
    878 
    879         if (type != XmlPullParser.START_TAG) {
    880             outError[0] = "No start tag found";
    881             return null;
    882         }
    883         if (DEBUG_PARSER)
    884             Slog.v(TAG, "Root element name: '" + parser.getName() + "'");
    885         if (!parser.getName().equals("manifest")) {
    886             outError[0] = "No <manifest> tag";
    887             return null;
    888         }
    889         String pkgName = attrs.getAttributeValue(null, "package");
    890         if (pkgName == null || pkgName.length() == 0) {
    891             outError[0] = "<manifest> does not specify package";
    892             return null;
    893         }
    894         String nameError = validateName(pkgName, true);
    895         if (nameError != null && !"android".equals(pkgName)) {
    896             outError[0] = "<manifest> specifies bad package name \""
    897                 + pkgName + "\": " + nameError;
    898             return null;
    899         }
    900         int installLocation = PARSE_DEFAULT_INSTALL_LOCATION;
    901         int versionCode = 0;
    902         int numFound = 0;
    903         for (int i = 0; i < attrs.getAttributeCount(); i++) {
    904             String attr = attrs.getAttributeName(i);
    905             if (attr.equals("installLocation")) {
    906                 installLocation = attrs.getAttributeIntValue(i,
    907                         PARSE_DEFAULT_INSTALL_LOCATION);
    908                 numFound++;
    909             } else if (attr.equals("versionCode")) {
    910                 versionCode = attrs.getAttributeIntValue(i, 0);
    911                 numFound++;
    912             }
    913             if (numFound >= 2) {
    914                 break;
    915             }
    916         }
    917 
    918         // Only search the tree when the tag is directly below <manifest>
    919         final int searchDepth = parser.getDepth() + 1;
    920 
    921         final List<VerifierInfo> verifiers = new ArrayList<VerifierInfo>();
    922         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
    923                 && (type != XmlPullParser.END_TAG || parser.getDepth() >= searchDepth)) {
    924             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
    925                 continue;
    926             }
    927 
    928             if (parser.getDepth() == searchDepth && "package-verifier".equals(parser.getName())) {
    929                 final VerifierInfo verifier = parseVerifier(res, parser, attrs, flags, outError);
    930                 if (verifier != null) {
    931                     verifiers.add(verifier);
    932                 }
    933             }
    934         }
    935 
    936         return new PackageLite(pkgName.intern(), versionCode, installLocation, verifiers);
    937     }
    938 
    939     /**
    940      * Temporary.
    941      */
    942     static public Signature stringToSignature(String str) {
    943         final int N = str.length();
    944         byte[] sig = new byte[N];
    945         for (int i=0; i<N; i++) {
    946             sig[i] = (byte)str.charAt(i);
    947         }
    948         return new Signature(sig);
    949     }
    950 
    951     private Package parsePackage(
    952         Resources res, XmlResourceParser parser, int flags, String[] outError)
    953         throws XmlPullParserException, IOException {
    954         AttributeSet attrs = parser;
    955 
    956         mParseInstrumentationArgs = null;
    957         mParseActivityArgs = null;
    958         mParseServiceArgs = null;
    959         mParseProviderArgs = null;
    960 
    961         String pkgName = parsePackageName(parser, attrs, flags, outError);
    962         if (pkgName == null) {
    963             mParseError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
    964             return null;
    965         }
    966         int type;
    967 
    968         if (mOnlyCoreApps) {
    969             boolean core = attrs.getAttributeBooleanValue(null, "coreApp", false);
    970             if (!core) {
    971                 mParseError = PackageManager.INSTALL_SUCCEEDED;
    972                 return null;
    973             }
    974         }
    975 
    976         final Package pkg = new Package(pkgName);
    977         boolean foundApp = false;
    978 
    979         TypedArray sa = res.obtainAttributes(attrs,
    980                 com.android.internal.R.styleable.AndroidManifest);
    981         pkg.mVersionCode = sa.getInteger(
    982                 com.android.internal.R.styleable.AndroidManifest_versionCode, 0);
    983         pkg.mVersionName = sa.getNonConfigurationString(
    984                 com.android.internal.R.styleable.AndroidManifest_versionName, 0);
    985         if (pkg.mVersionName != null) {
    986             pkg.mVersionName = pkg.mVersionName.intern();
    987         }
    988         String str = sa.getNonConfigurationString(
    989                 com.android.internal.R.styleable.AndroidManifest_sharedUserId, 0);
    990         if (str != null && str.length() > 0) {
    991             String nameError = validateName(str, true);
    992             if (nameError != null && !"android".equals(pkgName)) {
    993                 outError[0] = "<manifest> specifies bad sharedUserId name \""
    994                     + str + "\": " + nameError;
    995                 mParseError = PackageManager.INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID;
    996                 return null;
    997             }
    998             pkg.mSharedUserId = str.intern();
    999             pkg.mSharedUserLabel = sa.getResourceId(
   1000                     com.android.internal.R.styleable.AndroidManifest_sharedUserLabel, 0);
   1001         }
   1002         sa.recycle();
   1003 
   1004         pkg.installLocation = sa.getInteger(
   1005                 com.android.internal.R.styleable.AndroidManifest_installLocation,
   1006                 PARSE_DEFAULT_INSTALL_LOCATION);
   1007         pkg.applicationInfo.installLocation = pkg.installLocation;
   1008 
   1009         /* Set the global "forward lock" flag */
   1010         if ((flags & PARSE_FORWARD_LOCK) != 0) {
   1011             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FORWARD_LOCK;
   1012         }
   1013 
   1014         /* Set the global "on SD card" flag */
   1015         if ((flags & PARSE_ON_SDCARD) != 0) {
   1016             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
   1017         }
   1018 
   1019         // Resource boolean are -1, so 1 means we don't know the value.
   1020         int supportsSmallScreens = 1;
   1021         int supportsNormalScreens = 1;
   1022         int supportsLargeScreens = 1;
   1023         int supportsXLargeScreens = 1;
   1024         int resizeable = 1;
   1025         int anyDensity = 1;
   1026 
   1027         int outerDepth = parser.getDepth();
   1028         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   1029                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1030             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   1031                 continue;
   1032             }
   1033 
   1034             String tagName = parser.getName();
   1035             if (tagName.equals("application")) {
   1036                 if (foundApp) {
   1037                     if (RIGID_PARSER) {
   1038                         outError[0] = "<manifest> has more than one <application>";
   1039                         mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1040                         return null;
   1041                     } else {
   1042                         Slog.w(TAG, "<manifest> has more than one <application>");
   1043                         XmlUtils.skipCurrentTag(parser);
   1044                         continue;
   1045                     }
   1046                 }
   1047 
   1048                 foundApp = true;
   1049                 if (!parseApplication(pkg, res, parser, attrs, flags, outError)) {
   1050                     return null;
   1051                 }
   1052             } else if (tagName.equals("keys")) {
   1053                 if (!parseKeys(pkg, res, parser, attrs, outError)) {
   1054                     return null;
   1055                 }
   1056             } else if (tagName.equals("permission-group")) {
   1057                 if (parsePermissionGroup(pkg, flags, res, parser, attrs, outError) == null) {
   1058                     return null;
   1059                 }
   1060             } else if (tagName.equals("permission")) {
   1061                 if (parsePermission(pkg, res, parser, attrs, outError) == null) {
   1062                     return null;
   1063                 }
   1064             } else if (tagName.equals("permission-tree")) {
   1065                 if (parsePermissionTree(pkg, res, parser, attrs, outError) == null) {
   1066                     return null;
   1067                 }
   1068             } else if (tagName.equals("uses-permission")) {
   1069                 if (!parseUsesPermission(pkg, res, parser, attrs, outError)) {
   1070                     return null;
   1071                 }
   1072 
   1073             } else if (tagName.equals("uses-configuration")) {
   1074                 ConfigurationInfo cPref = new ConfigurationInfo();
   1075                 sa = res.obtainAttributes(attrs,
   1076                         com.android.internal.R.styleable.AndroidManifestUsesConfiguration);
   1077                 cPref.reqTouchScreen = sa.getInt(
   1078                         com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqTouchScreen,
   1079                         Configuration.TOUCHSCREEN_UNDEFINED);
   1080                 cPref.reqKeyboardType = sa.getInt(
   1081                         com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqKeyboardType,
   1082                         Configuration.KEYBOARD_UNDEFINED);
   1083                 if (sa.getBoolean(
   1084                         com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqHardKeyboard,
   1085                         false)) {
   1086                     cPref.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
   1087                 }
   1088                 cPref.reqNavigation = sa.getInt(
   1089                         com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqNavigation,
   1090                         Configuration.NAVIGATION_UNDEFINED);
   1091                 if (sa.getBoolean(
   1092                         com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqFiveWayNav,
   1093                         false)) {
   1094                     cPref.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
   1095                 }
   1096                 sa.recycle();
   1097                 pkg.configPreferences.add(cPref);
   1098 
   1099                 XmlUtils.skipCurrentTag(parser);
   1100 
   1101             } else if (tagName.equals("uses-feature")) {
   1102                 FeatureInfo fi = new FeatureInfo();
   1103                 sa = res.obtainAttributes(attrs,
   1104                         com.android.internal.R.styleable.AndroidManifestUsesFeature);
   1105                 // Note: don't allow this value to be a reference to a resource
   1106                 // that may change.
   1107                 fi.name = sa.getNonResourceString(
   1108                         com.android.internal.R.styleable.AndroidManifestUsesFeature_name);
   1109                 if (fi.name == null) {
   1110                     fi.reqGlEsVersion = sa.getInt(
   1111                             com.android.internal.R.styleable.AndroidManifestUsesFeature_glEsVersion,
   1112                             FeatureInfo.GL_ES_VERSION_UNDEFINED);
   1113                 }
   1114                 if (sa.getBoolean(
   1115                         com.android.internal.R.styleable.AndroidManifestUsesFeature_required,
   1116                         true)) {
   1117                     fi.flags |= FeatureInfo.FLAG_REQUIRED;
   1118                 }
   1119                 sa.recycle();
   1120                 if (pkg.reqFeatures == null) {
   1121                     pkg.reqFeatures = new ArrayList<FeatureInfo>();
   1122                 }
   1123                 pkg.reqFeatures.add(fi);
   1124 
   1125                 if (fi.name == null) {
   1126                     ConfigurationInfo cPref = new ConfigurationInfo();
   1127                     cPref.reqGlEsVersion = fi.reqGlEsVersion;
   1128                     pkg.configPreferences.add(cPref);
   1129                 }
   1130 
   1131                 XmlUtils.skipCurrentTag(parser);
   1132 
   1133             } else if (tagName.equals("uses-sdk")) {
   1134                 if (SDK_VERSION > 0) {
   1135                     sa = res.obtainAttributes(attrs,
   1136                             com.android.internal.R.styleable.AndroidManifestUsesSdk);
   1137 
   1138                     int minVers = 0;
   1139                     String minCode = null;
   1140                     int targetVers = 0;
   1141                     String targetCode = null;
   1142 
   1143                     TypedValue val = sa.peekValue(
   1144                             com.android.internal.R.styleable.AndroidManifestUsesSdk_minSdkVersion);
   1145                     if (val != null) {
   1146                         if (val.type == TypedValue.TYPE_STRING && val.string != null) {
   1147                             targetCode = minCode = val.string.toString();
   1148                         } else {
   1149                             // If it's not a string, it's an integer.
   1150                             targetVers = minVers = val.data;
   1151                         }
   1152                     }
   1153 
   1154                     val = sa.peekValue(
   1155                             com.android.internal.R.styleable.AndroidManifestUsesSdk_targetSdkVersion);
   1156                     if (val != null) {
   1157                         if (val.type == TypedValue.TYPE_STRING && val.string != null) {
   1158                             targetCode = minCode = val.string.toString();
   1159                         } else {
   1160                             // If it's not a string, it's an integer.
   1161                             targetVers = val.data;
   1162                         }
   1163                     }
   1164 
   1165                     sa.recycle();
   1166 
   1167                     if (minCode != null) {
   1168                         if (!minCode.equals(SDK_CODENAME)) {
   1169                             if (SDK_CODENAME != null) {
   1170                                 outError[0] = "Requires development platform " + minCode
   1171                                         + " (current platform is " + SDK_CODENAME + ")";
   1172                             } else {
   1173                                 outError[0] = "Requires development platform " + minCode
   1174                                         + " but this is a release platform.";
   1175                             }
   1176                             mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
   1177                             return null;
   1178                         }
   1179                     } else if (minVers > SDK_VERSION) {
   1180                         outError[0] = "Requires newer sdk version #" + minVers
   1181                                 + " (current version is #" + SDK_VERSION + ")";
   1182                         mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
   1183                         return null;
   1184                     }
   1185 
   1186                     if (targetCode != null) {
   1187                         if (!targetCode.equals(SDK_CODENAME)) {
   1188                             if (SDK_CODENAME != null) {
   1189                                 outError[0] = "Requires development platform " + targetCode
   1190                                         + " (current platform is " + SDK_CODENAME + ")";
   1191                             } else {
   1192                                 outError[0] = "Requires development platform " + targetCode
   1193                                         + " but this is a release platform.";
   1194                             }
   1195                             mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
   1196                             return null;
   1197                         }
   1198                         // If the code matches, it definitely targets this SDK.
   1199                         pkg.applicationInfo.targetSdkVersion
   1200                                 = android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
   1201                     } else {
   1202                         pkg.applicationInfo.targetSdkVersion = targetVers;
   1203                     }
   1204                 }
   1205 
   1206                 XmlUtils.skipCurrentTag(parser);
   1207 
   1208             } else if (tagName.equals("supports-screens")) {
   1209                 sa = res.obtainAttributes(attrs,
   1210                         com.android.internal.R.styleable.AndroidManifestSupportsScreens);
   1211 
   1212                 pkg.applicationInfo.requiresSmallestWidthDp = sa.getInteger(
   1213                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_requiresSmallestWidthDp,
   1214                         0);
   1215                 pkg.applicationInfo.compatibleWidthLimitDp = sa.getInteger(
   1216                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_compatibleWidthLimitDp,
   1217                         0);
   1218                 pkg.applicationInfo.largestWidthLimitDp = sa.getInteger(
   1219                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_largestWidthLimitDp,
   1220                         0);
   1221 
   1222                 // This is a trick to get a boolean and still able to detect
   1223                 // if a value was actually set.
   1224                 supportsSmallScreens = sa.getInteger(
   1225                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_smallScreens,
   1226                         supportsSmallScreens);
   1227                 supportsNormalScreens = sa.getInteger(
   1228                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_normalScreens,
   1229                         supportsNormalScreens);
   1230                 supportsLargeScreens = sa.getInteger(
   1231                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_largeScreens,
   1232                         supportsLargeScreens);
   1233                 supportsXLargeScreens = sa.getInteger(
   1234                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_xlargeScreens,
   1235                         supportsXLargeScreens);
   1236                 resizeable = sa.getInteger(
   1237                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_resizeable,
   1238                         resizeable);
   1239                 anyDensity = sa.getInteger(
   1240                         com.android.internal.R.styleable.AndroidManifestSupportsScreens_anyDensity,
   1241                         anyDensity);
   1242 
   1243                 sa.recycle();
   1244 
   1245                 XmlUtils.skipCurrentTag(parser);
   1246 
   1247             } else if (tagName.equals("protected-broadcast")) {
   1248                 sa = res.obtainAttributes(attrs,
   1249                         com.android.internal.R.styleable.AndroidManifestProtectedBroadcast);
   1250 
   1251                 // Note: don't allow this value to be a reference to a resource
   1252                 // that may change.
   1253                 String name = sa.getNonResourceString(
   1254                         com.android.internal.R.styleable.AndroidManifestProtectedBroadcast_name);
   1255 
   1256                 sa.recycle();
   1257 
   1258                 if (name != null && (flags&PARSE_IS_SYSTEM) != 0) {
   1259                     if (pkg.protectedBroadcasts == null) {
   1260                         pkg.protectedBroadcasts = new ArrayList<String>();
   1261                     }
   1262                     if (!pkg.protectedBroadcasts.contains(name)) {
   1263                         pkg.protectedBroadcasts.add(name.intern());
   1264                     }
   1265                 }
   1266 
   1267                 XmlUtils.skipCurrentTag(parser);
   1268 
   1269             } else if (tagName.equals("instrumentation")) {
   1270                 if (parseInstrumentation(pkg, res, parser, attrs, outError) == null) {
   1271                     return null;
   1272                 }
   1273 
   1274             } else if (tagName.equals("original-package")) {
   1275                 sa = res.obtainAttributes(attrs,
   1276                         com.android.internal.R.styleable.AndroidManifestOriginalPackage);
   1277 
   1278                 String orig =sa.getNonConfigurationString(
   1279                         com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
   1280                 if (!pkg.packageName.equals(orig)) {
   1281                     if (pkg.mOriginalPackages == null) {
   1282                         pkg.mOriginalPackages = new ArrayList<String>();
   1283                         pkg.mRealPackage = pkg.packageName;
   1284                     }
   1285                     pkg.mOriginalPackages.add(orig);
   1286                 }
   1287 
   1288                 sa.recycle();
   1289 
   1290                 XmlUtils.skipCurrentTag(parser);
   1291 
   1292             } else if (tagName.equals("adopt-permissions")) {
   1293                 sa = res.obtainAttributes(attrs,
   1294                         com.android.internal.R.styleable.AndroidManifestOriginalPackage);
   1295 
   1296                 String name = sa.getNonConfigurationString(
   1297                         com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
   1298 
   1299                 sa.recycle();
   1300 
   1301                 if (name != null) {
   1302                     if (pkg.mAdoptPermissions == null) {
   1303                         pkg.mAdoptPermissions = new ArrayList<String>();
   1304                     }
   1305                     pkg.mAdoptPermissions.add(name);
   1306                 }
   1307 
   1308                 XmlUtils.skipCurrentTag(parser);
   1309 
   1310             } else if (tagName.equals("uses-gl-texture")) {
   1311                 // Just skip this tag
   1312                 XmlUtils.skipCurrentTag(parser);
   1313                 continue;
   1314 
   1315             } else if (tagName.equals("compatible-screens")) {
   1316                 // Just skip this tag
   1317                 XmlUtils.skipCurrentTag(parser);
   1318                 continue;
   1319             } else if (tagName.equals("supports-input")) {
   1320                 XmlUtils.skipCurrentTag(parser);
   1321                 continue;
   1322 
   1323             } else if (tagName.equals("eat-comment")) {
   1324                 // Just skip this tag
   1325                 XmlUtils.skipCurrentTag(parser);
   1326                 continue;
   1327 
   1328             } else if (RIGID_PARSER) {
   1329                 outError[0] = "Bad element under <manifest>: "
   1330                     + parser.getName();
   1331                 mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1332                 return null;
   1333 
   1334             } else {
   1335                 Slog.w(TAG, "Unknown element under <manifest>: " + parser.getName()
   1336                         + " at " + mArchiveSourcePath + " "
   1337                         + parser.getPositionDescription());
   1338                 XmlUtils.skipCurrentTag(parser);
   1339                 continue;
   1340             }
   1341         }
   1342 
   1343         if (!foundApp && pkg.instrumentation.size() == 0) {
   1344             outError[0] = "<manifest> does not contain an <application> or <instrumentation>";
   1345             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_EMPTY;
   1346         }
   1347 
   1348         final int NP = PackageParser.NEW_PERMISSIONS.length;
   1349         StringBuilder implicitPerms = null;
   1350         for (int ip=0; ip<NP; ip++) {
   1351             final PackageParser.NewPermissionInfo npi
   1352                     = PackageParser.NEW_PERMISSIONS[ip];
   1353             if (pkg.applicationInfo.targetSdkVersion >= npi.sdkVersion) {
   1354                 break;
   1355             }
   1356             if (!pkg.requestedPermissions.contains(npi.name)) {
   1357                 if (implicitPerms == null) {
   1358                     implicitPerms = new StringBuilder(128);
   1359                     implicitPerms.append(pkg.packageName);
   1360                     implicitPerms.append(": compat added ");
   1361                 } else {
   1362                     implicitPerms.append(' ');
   1363                 }
   1364                 implicitPerms.append(npi.name);
   1365                 pkg.requestedPermissions.add(npi.name);
   1366                 pkg.requestedPermissionsRequired.add(Boolean.TRUE);
   1367             }
   1368         }
   1369         if (implicitPerms != null) {
   1370             Slog.i(TAG, implicitPerms.toString());
   1371         }
   1372 
   1373         final int NS = PackageParser.SPLIT_PERMISSIONS.length;
   1374         for (int is=0; is<NS; is++) {
   1375             final PackageParser.SplitPermissionInfo spi
   1376                     = PackageParser.SPLIT_PERMISSIONS[is];
   1377             if (pkg.applicationInfo.targetSdkVersion >= spi.targetSdk
   1378                     || !pkg.requestedPermissions.contains(spi.rootPerm)) {
   1379                 continue;
   1380             }
   1381             for (int in=0; in<spi.newPerms.length; in++) {
   1382                 final String perm = spi.newPerms[in];
   1383                 if (!pkg.requestedPermissions.contains(perm)) {
   1384                     pkg.requestedPermissions.add(perm);
   1385                     pkg.requestedPermissionsRequired.add(Boolean.TRUE);
   1386                 }
   1387             }
   1388         }
   1389 
   1390         if (supportsSmallScreens < 0 || (supportsSmallScreens > 0
   1391                 && pkg.applicationInfo.targetSdkVersion
   1392                         >= android.os.Build.VERSION_CODES.DONUT)) {
   1393             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS;
   1394         }
   1395         if (supportsNormalScreens != 0) {
   1396             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS;
   1397         }
   1398         if (supportsLargeScreens < 0 || (supportsLargeScreens > 0
   1399                 && pkg.applicationInfo.targetSdkVersion
   1400                         >= android.os.Build.VERSION_CODES.DONUT)) {
   1401             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS;
   1402         }
   1403         if (supportsXLargeScreens < 0 || (supportsXLargeScreens > 0
   1404                 && pkg.applicationInfo.targetSdkVersion
   1405                         >= android.os.Build.VERSION_CODES.GINGERBREAD)) {
   1406             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS;
   1407         }
   1408         if (resizeable < 0 || (resizeable > 0
   1409                 && pkg.applicationInfo.targetSdkVersion
   1410                         >= android.os.Build.VERSION_CODES.DONUT)) {
   1411             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS;
   1412         }
   1413         if (anyDensity < 0 || (anyDensity > 0
   1414                 && pkg.applicationInfo.targetSdkVersion
   1415                         >= android.os.Build.VERSION_CODES.DONUT)) {
   1416             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES;
   1417         }
   1418 
   1419         /*
   1420          * b/8528162: Ignore the <uses-permission android:required> attribute if
   1421          * targetSdkVersion < JELLY_BEAN_MR2. There are lots of apps in the wild
   1422          * which are improperly using this attribute, even though it never worked.
   1423          */
   1424         if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR2) {
   1425             for (int i = 0; i < pkg.requestedPermissionsRequired.size(); i++) {
   1426                 pkg.requestedPermissionsRequired.set(i, Boolean.TRUE);
   1427             }
   1428         }
   1429 
   1430         return pkg;
   1431     }
   1432 
   1433     private boolean parseUsesPermission(Package pkg, Resources res, XmlResourceParser parser,
   1434                                         AttributeSet attrs, String[] outError)
   1435             throws XmlPullParserException, IOException {
   1436         TypedArray sa = res.obtainAttributes(attrs,
   1437                 com.android.internal.R.styleable.AndroidManifestUsesPermission);
   1438 
   1439         // Note: don't allow this value to be a reference to a resource
   1440         // that may change.
   1441         String name = sa.getNonResourceString(
   1442                 com.android.internal.R.styleable.AndroidManifestUsesPermission_name);
   1443 /*
   1444         boolean required = sa.getBoolean(
   1445                 com.android.internal.R.styleable.AndroidManifestUsesPermission_required, true);
   1446 */
   1447         boolean required = true; // Optional <uses-permission> not supported
   1448 
   1449         int maxSdkVersion = 0;
   1450         TypedValue val = sa.peekValue(
   1451                 com.android.internal.R.styleable.AndroidManifestUsesPermission_maxSdkVersion);
   1452         if (val != null) {
   1453             if (val.type >= TypedValue.TYPE_FIRST_INT && val.type <= TypedValue.TYPE_LAST_INT) {
   1454                 maxSdkVersion = val.data;
   1455             }
   1456         }
   1457 
   1458         sa.recycle();
   1459 
   1460         if ((maxSdkVersion == 0) || (maxSdkVersion >= Build.VERSION.RESOURCES_SDK_INT)) {
   1461             if (name != null) {
   1462                 int index = pkg.requestedPermissions.indexOf(name);
   1463                 if (index == -1) {
   1464                     pkg.requestedPermissions.add(name.intern());
   1465                     pkg.requestedPermissionsRequired.add(required ? Boolean.TRUE : Boolean.FALSE);
   1466                 } else {
   1467                     if (pkg.requestedPermissionsRequired.get(index) != required) {
   1468                         outError[0] = "conflicting <uses-permission> entries";
   1469                         mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1470                         return false;
   1471                     }
   1472                 }
   1473             }
   1474         }
   1475 
   1476         XmlUtils.skipCurrentTag(parser);
   1477         return true;
   1478     }
   1479 
   1480     private static String buildClassName(String pkg, CharSequence clsSeq,
   1481             String[] outError) {
   1482         if (clsSeq == null || clsSeq.length() <= 0) {
   1483             outError[0] = "Empty class name in package " + pkg;
   1484             return null;
   1485         }
   1486         String cls = clsSeq.toString();
   1487         char c = cls.charAt(0);
   1488         if (c == '.') {
   1489             return (pkg + cls).intern();
   1490         }
   1491         if (cls.indexOf('.') < 0) {
   1492             StringBuilder b = new StringBuilder(pkg);
   1493             b.append('.');
   1494             b.append(cls);
   1495             return b.toString().intern();
   1496         }
   1497         if (c >= 'a' && c <= 'z') {
   1498             return cls.intern();
   1499         }
   1500         outError[0] = "Bad class name " + cls + " in package " + pkg;
   1501         return null;
   1502     }
   1503 
   1504     private static String buildCompoundName(String pkg,
   1505             CharSequence procSeq, String type, String[] outError) {
   1506         String proc = procSeq.toString();
   1507         char c = proc.charAt(0);
   1508         if (pkg != null && c == ':') {
   1509             if (proc.length() < 2) {
   1510                 outError[0] = "Bad " + type + " name " + proc + " in package " + pkg
   1511                         + ": must be at least two characters";
   1512                 return null;
   1513             }
   1514             String subName = proc.substring(1);
   1515             String nameError = validateName(subName, false);
   1516             if (nameError != null) {
   1517                 outError[0] = "Invalid " + type + " name " + proc + " in package "
   1518                         + pkg + ": " + nameError;
   1519                 return null;
   1520             }
   1521             return (pkg + proc).intern();
   1522         }
   1523         String nameError = validateName(proc, true);
   1524         if (nameError != null && !"system".equals(proc)) {
   1525             outError[0] = "Invalid " + type + " name " + proc + " in package "
   1526                     + pkg + ": " + nameError;
   1527             return null;
   1528         }
   1529         return proc.intern();
   1530     }
   1531 
   1532     private static String buildProcessName(String pkg, String defProc,
   1533             CharSequence procSeq, int flags, String[] separateProcesses,
   1534             String[] outError) {
   1535         if ((flags&PARSE_IGNORE_PROCESSES) != 0 && !"system".equals(procSeq)) {
   1536             return defProc != null ? defProc : pkg;
   1537         }
   1538         if (separateProcesses != null) {
   1539             for (int i=separateProcesses.length-1; i>=0; i--) {
   1540                 String sp = separateProcesses[i];
   1541                 if (sp.equals(pkg) || sp.equals(defProc) || sp.equals(procSeq)) {
   1542                     return pkg;
   1543                 }
   1544             }
   1545         }
   1546         if (procSeq == null || procSeq.length() <= 0) {
   1547             return defProc;
   1548         }
   1549         return buildCompoundName(pkg, procSeq, "process", outError);
   1550     }
   1551 
   1552     private static String buildTaskAffinityName(String pkg, String defProc,
   1553             CharSequence procSeq, String[] outError) {
   1554         if (procSeq == null) {
   1555             return defProc;
   1556         }
   1557         if (procSeq.length() <= 0) {
   1558             return null;
   1559         }
   1560         return buildCompoundName(pkg, procSeq, "taskAffinity", outError);
   1561     }
   1562 
   1563     private boolean parseKeys(Package owner, Resources res,
   1564             XmlPullParser parser, AttributeSet attrs, String[] outError)
   1565             throws XmlPullParserException, IOException {
   1566         // we've encountered the 'keys' tag
   1567         // all the keys and keysets that we want must be defined here
   1568         // so we're going to iterate over the parser and pull out the things we want
   1569         int outerDepth = parser.getDepth();
   1570 
   1571         int type;
   1572         PublicKey currentKey = null;
   1573         int currentKeyDepth = -1;
   1574         Map<PublicKey, Set<String>> definedKeySets = new HashMap<PublicKey, Set<String>>();
   1575         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   1576                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   1577             if (type == XmlPullParser.END_TAG) {
   1578                 if (parser.getDepth() == currentKeyDepth) {
   1579                     currentKey = null;
   1580                     currentKeyDepth = -1;
   1581                 }
   1582                 continue;
   1583             }
   1584             String tagname = parser.getName();
   1585             if (tagname.equals("publicKey")) {
   1586                 final TypedArray sa = res.obtainAttributes(attrs,
   1587                         com.android.internal.R.styleable.PublicKey);
   1588                 final String encodedKey = sa.getNonResourceString(
   1589                     com.android.internal.R.styleable.PublicKey_value);
   1590                 currentKey = parsePublicKey(encodedKey);
   1591                 if (currentKey == null) {
   1592                     Slog.w(TAG, "No valid key in 'publicKey' tag at "
   1593                             + parser.getPositionDescription());
   1594                     sa.recycle();
   1595                     continue;
   1596                 }
   1597                 currentKeyDepth = parser.getDepth();
   1598                 definedKeySets.put(currentKey, new HashSet<String>());
   1599                 sa.recycle();
   1600             } else if (tagname.equals("keyset")) {
   1601                 if (currentKey == null) {
   1602                     Slog.i(TAG, "'keyset' not in 'publicKey' tag at "
   1603                             + parser.getPositionDescription());
   1604                     continue;
   1605                 }
   1606                 final TypedArray sa = res.obtainAttributes(attrs,
   1607                         com.android.internal.R.styleable.KeySet);
   1608                 final String name = sa.getNonResourceString(
   1609                     com.android.internal.R.styleable.KeySet_name);
   1610                 definedKeySets.get(currentKey).add(name);
   1611                 sa.recycle();
   1612             } else if (RIGID_PARSER) {
   1613                 Slog.w(TAG, "Bad element under <keys>: " + parser.getName()
   1614                         + " at " + mArchiveSourcePath + " "
   1615                         + parser.getPositionDescription());
   1616                 return false;
   1617             } else {
   1618                 Slog.w(TAG, "Unknown element under <keys>: " + parser.getName()
   1619                         + " at " + mArchiveSourcePath + " "
   1620                         + parser.getPositionDescription());
   1621                 XmlUtils.skipCurrentTag(parser);
   1622                 continue;
   1623             }
   1624         }
   1625 
   1626         owner.mKeySetMapping = new HashMap<String, Set<PublicKey>>();
   1627         for (Map.Entry<PublicKey, Set<String>> e : definedKeySets.entrySet()) {
   1628             PublicKey key = e.getKey();
   1629             Set<String> keySetNames = e.getValue();
   1630             for (String alias : keySetNames) {
   1631                 if (owner.mKeySetMapping.containsKey(alias)) {
   1632                     owner.mKeySetMapping.get(alias).add(key);
   1633                 } else {
   1634                     Set<PublicKey> keys = new HashSet<PublicKey>();
   1635                     keys.add(key);
   1636                     owner.mKeySetMapping.put(alias, keys);
   1637                 }
   1638             }
   1639         }
   1640 
   1641         return true;
   1642     }
   1643 
   1644     private PermissionGroup parsePermissionGroup(Package owner, int flags, Resources res,
   1645             XmlPullParser parser, AttributeSet attrs, String[] outError)
   1646         throws XmlPullParserException, IOException {
   1647         PermissionGroup perm = new PermissionGroup(owner);
   1648 
   1649         TypedArray sa = res.obtainAttributes(attrs,
   1650                 com.android.internal.R.styleable.AndroidManifestPermissionGroup);
   1651 
   1652         if (!parsePackageItemInfo(owner, perm.info, outError,
   1653                 "<permission-group>", sa,
   1654                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_name,
   1655                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_label,
   1656                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_icon,
   1657                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_logo)) {
   1658             sa.recycle();
   1659             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1660             return null;
   1661         }
   1662 
   1663         perm.info.descriptionRes = sa.getResourceId(
   1664                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_description,
   1665                 0);
   1666         perm.info.flags = sa.getInt(
   1667                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_permissionGroupFlags, 0);
   1668         perm.info.priority = sa.getInt(
   1669                 com.android.internal.R.styleable.AndroidManifestPermissionGroup_priority, 0);
   1670         if (perm.info.priority > 0 && (flags&PARSE_IS_SYSTEM) == 0) {
   1671             perm.info.priority = 0;
   1672         }
   1673 
   1674         sa.recycle();
   1675 
   1676         if (!parseAllMetaData(res, parser, attrs, "<permission-group>", perm,
   1677                 outError)) {
   1678             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1679             return null;
   1680         }
   1681 
   1682         owner.permissionGroups.add(perm);
   1683 
   1684         return perm;
   1685     }
   1686 
   1687     private Permission parsePermission(Package owner, Resources res,
   1688             XmlPullParser parser, AttributeSet attrs, String[] outError)
   1689         throws XmlPullParserException, IOException {
   1690         Permission perm = new Permission(owner);
   1691 
   1692         TypedArray sa = res.obtainAttributes(attrs,
   1693                 com.android.internal.R.styleable.AndroidManifestPermission);
   1694 
   1695         if (!parsePackageItemInfo(owner, perm.info, outError,
   1696                 "<permission>", sa,
   1697                 com.android.internal.R.styleable.AndroidManifestPermission_name,
   1698                 com.android.internal.R.styleable.AndroidManifestPermission_label,
   1699                 com.android.internal.R.styleable.AndroidManifestPermission_icon,
   1700                 com.android.internal.R.styleable.AndroidManifestPermission_logo)) {
   1701             sa.recycle();
   1702             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1703             return null;
   1704         }
   1705 
   1706         // Note: don't allow this value to be a reference to a resource
   1707         // that may change.
   1708         perm.info.group = sa.getNonResourceString(
   1709                 com.android.internal.R.styleable.AndroidManifestPermission_permissionGroup);
   1710         if (perm.info.group != null) {
   1711             perm.info.group = perm.info.group.intern();
   1712         }
   1713 
   1714         perm.info.descriptionRes = sa.getResourceId(
   1715                 com.android.internal.R.styleable.AndroidManifestPermission_description,
   1716                 0);
   1717 
   1718         perm.info.protectionLevel = sa.getInt(
   1719                 com.android.internal.R.styleable.AndroidManifestPermission_protectionLevel,
   1720                 PermissionInfo.PROTECTION_NORMAL);
   1721 
   1722         perm.info.flags = sa.getInt(
   1723                 com.android.internal.R.styleable.AndroidManifestPermission_permissionFlags, 0);
   1724 
   1725         sa.recycle();
   1726 
   1727         if (perm.info.protectionLevel == -1) {
   1728             outError[0] = "<permission> does not specify protectionLevel";
   1729             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1730             return null;
   1731         }
   1732 
   1733         perm.info.protectionLevel = PermissionInfo.fixProtectionLevel(perm.info.protectionLevel);
   1734 
   1735         if ((perm.info.protectionLevel&PermissionInfo.PROTECTION_MASK_FLAGS) != 0) {
   1736             if ((perm.info.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) !=
   1737                     PermissionInfo.PROTECTION_SIGNATURE) {
   1738                 outError[0] = "<permission>  protectionLevel specifies a flag but is "
   1739                         + "not based on signature type";
   1740                 mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1741                 return null;
   1742             }
   1743         }
   1744 
   1745         if (!parseAllMetaData(res, parser, attrs, "<permission>", perm,
   1746                 outError)) {
   1747             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1748             return null;
   1749         }
   1750 
   1751         owner.permissions.add(perm);
   1752 
   1753         return perm;
   1754     }
   1755 
   1756     private Permission parsePermissionTree(Package owner, Resources res,
   1757             XmlPullParser parser, AttributeSet attrs, String[] outError)
   1758         throws XmlPullParserException, IOException {
   1759         Permission perm = new Permission(owner);
   1760 
   1761         TypedArray sa = res.obtainAttributes(attrs,
   1762                 com.android.internal.R.styleable.AndroidManifestPermissionTree);
   1763 
   1764         if (!parsePackageItemInfo(owner, perm.info, outError,
   1765                 "<permission-tree>", sa,
   1766                 com.android.internal.R.styleable.AndroidManifestPermissionTree_name,
   1767                 com.android.internal.R.styleable.AndroidManifestPermissionTree_label,
   1768                 com.android.internal.R.styleable.AndroidManifestPermissionTree_icon,
   1769                 com.android.internal.R.styleable.AndroidManifestPermissionTree_logo)) {
   1770             sa.recycle();
   1771             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1772             return null;
   1773         }
   1774 
   1775         sa.recycle();
   1776 
   1777         int index = perm.info.name.indexOf('.');
   1778         if (index > 0) {
   1779             index = perm.info.name.indexOf('.', index+1);
   1780         }
   1781         if (index < 0) {
   1782             outError[0] = "<permission-tree> name has less than three segments: "
   1783                 + perm.info.name;
   1784             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1785             return null;
   1786         }
   1787 
   1788         perm.info.descriptionRes = 0;
   1789         perm.info.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
   1790         perm.tree = true;
   1791 
   1792         if (!parseAllMetaData(res, parser, attrs, "<permission-tree>", perm,
   1793                 outError)) {
   1794             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1795             return null;
   1796         }
   1797 
   1798         owner.permissions.add(perm);
   1799 
   1800         return perm;
   1801     }
   1802 
   1803     private Instrumentation parseInstrumentation(Package owner, Resources res,
   1804             XmlPullParser parser, AttributeSet attrs, String[] outError)
   1805         throws XmlPullParserException, IOException {
   1806         TypedArray sa = res.obtainAttributes(attrs,
   1807                 com.android.internal.R.styleable.AndroidManifestInstrumentation);
   1808 
   1809         if (mParseInstrumentationArgs == null) {
   1810             mParseInstrumentationArgs = new ParsePackageItemArgs(owner, outError,
   1811                     com.android.internal.R.styleable.AndroidManifestInstrumentation_name,
   1812                     com.android.internal.R.styleable.AndroidManifestInstrumentation_label,
   1813                     com.android.internal.R.styleable.AndroidManifestInstrumentation_icon,
   1814                     com.android.internal.R.styleable.AndroidManifestInstrumentation_logo);
   1815             mParseInstrumentationArgs.tag = "<instrumentation>";
   1816         }
   1817 
   1818         mParseInstrumentationArgs.sa = sa;
   1819 
   1820         Instrumentation a = new Instrumentation(mParseInstrumentationArgs,
   1821                 new InstrumentationInfo());
   1822         if (outError[0] != null) {
   1823             sa.recycle();
   1824             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1825             return null;
   1826         }
   1827 
   1828         String str;
   1829         // Note: don't allow this value to be a reference to a resource
   1830         // that may change.
   1831         str = sa.getNonResourceString(
   1832                 com.android.internal.R.styleable.AndroidManifestInstrumentation_targetPackage);
   1833         a.info.targetPackage = str != null ? str.intern() : null;
   1834 
   1835         a.info.handleProfiling = sa.getBoolean(
   1836                 com.android.internal.R.styleable.AndroidManifestInstrumentation_handleProfiling,
   1837                 false);
   1838 
   1839         a.info.functionalTest = sa.getBoolean(
   1840                 com.android.internal.R.styleable.AndroidManifestInstrumentation_functionalTest,
   1841                 false);
   1842 
   1843         sa.recycle();
   1844 
   1845         if (a.info.targetPackage == null) {
   1846             outError[0] = "<instrumentation> does not specify targetPackage";
   1847             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1848             return null;
   1849         }
   1850 
   1851         if (!parseAllMetaData(res, parser, attrs, "<instrumentation>", a,
   1852                 outError)) {
   1853             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1854             return null;
   1855         }
   1856 
   1857         owner.instrumentation.add(a);
   1858 
   1859         return a;
   1860     }
   1861 
   1862     private boolean parseApplication(Package owner, Resources res,
   1863             XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
   1864         throws XmlPullParserException, IOException {
   1865         final ApplicationInfo ai = owner.applicationInfo;
   1866         final String pkgName = owner.applicationInfo.packageName;
   1867 
   1868         TypedArray sa = res.obtainAttributes(attrs,
   1869                 com.android.internal.R.styleable.AndroidManifestApplication);
   1870 
   1871         String name = sa.getNonConfigurationString(
   1872                 com.android.internal.R.styleable.AndroidManifestApplication_name, 0);
   1873         if (name != null) {
   1874             ai.className = buildClassName(pkgName, name, outError);
   1875             if (ai.className == null) {
   1876                 sa.recycle();
   1877                 mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   1878                 return false;
   1879             }
   1880         }
   1881 
   1882         String manageSpaceActivity = sa.getNonConfigurationString(
   1883                 com.android.internal.R.styleable.AndroidManifestApplication_manageSpaceActivity,
   1884                 Configuration.NATIVE_CONFIG_VERSION);
   1885         if (manageSpaceActivity != null) {
   1886             ai.manageSpaceActivityName = buildClassName(pkgName, manageSpaceActivity,
   1887                     outError);
   1888         }
   1889 
   1890         boolean allowBackup = sa.getBoolean(
   1891                 com.android.internal.R.styleable.AndroidManifestApplication_allowBackup, true);
   1892         if (allowBackup) {
   1893             ai.flags |= ApplicationInfo.FLAG_ALLOW_BACKUP;
   1894 
   1895             // backupAgent, killAfterRestore, and restoreAnyVersion are only relevant
   1896             // if backup is possible for the given application.
   1897             String backupAgent = sa.getNonConfigurationString(
   1898                     com.android.internal.R.styleable.AndroidManifestApplication_backupAgent,
   1899                     Configuration.NATIVE_CONFIG_VERSION);
   1900             if (backupAgent != null) {
   1901                 ai.backupAgentName = buildClassName(pkgName, backupAgent, outError);
   1902                 if (DEBUG_BACKUP) {
   1903                     Slog.v(TAG, "android:backupAgent = " + ai.backupAgentName
   1904                             + " from " + pkgName + "+" + backupAgent);
   1905                 }
   1906 
   1907                 if (sa.getBoolean(
   1908                         com.android.internal.R.styleable.AndroidManifestApplication_killAfterRestore,
   1909                         true)) {
   1910                     ai.flags |= ApplicationInfo.FLAG_KILL_AFTER_RESTORE;
   1911                 }
   1912                 if (sa.getBoolean(
   1913                         com.android.internal.R.styleable.AndroidManifestApplication_restoreAnyVersion,
   1914                         false)) {
   1915                     ai.flags |= ApplicationInfo.FLAG_RESTORE_ANY_VERSION;
   1916                 }
   1917             }
   1918         }
   1919 
   1920         TypedValue v = sa.peekValue(
   1921                 com.android.internal.R.styleable.AndroidManifestApplication_label);
   1922         if (v != null && (ai.labelRes=v.resourceId) == 0) {
   1923             ai.nonLocalizedLabel = v.coerceToString();
   1924         }
   1925 
   1926         ai.icon = sa.getResourceId(
   1927                 com.android.internal.R.styleable.AndroidManifestApplication_icon, 0);
   1928         ai.logo = sa.getResourceId(
   1929                 com.android.internal.R.styleable.AndroidManifestApplication_logo, 0);
   1930         ai.theme = sa.getResourceId(
   1931                 com.android.internal.R.styleable.AndroidManifestApplication_theme, 0);
   1932         ai.descriptionRes = sa.getResourceId(
   1933                 com.android.internal.R.styleable.AndroidManifestApplication_description, 0);
   1934 
   1935         if ((flags&PARSE_IS_SYSTEM) != 0) {
   1936             if (sa.getBoolean(
   1937                     com.android.internal.R.styleable.AndroidManifestApplication_persistent,
   1938                     false)) {
   1939                 ai.flags |= ApplicationInfo.FLAG_PERSISTENT;
   1940             }
   1941         }
   1942 
   1943         if (sa.getBoolean(
   1944                 com.android.internal.R.styleable.AndroidManifestApplication_requiredForAllUsers,
   1945                 false)) {
   1946             owner.mRequiredForAllUsers = true;
   1947         }
   1948 
   1949         String restrictedAccountType = sa.getString(com.android.internal.R.styleable
   1950                 .AndroidManifestApplication_restrictedAccountType);
   1951         if (restrictedAccountType != null && restrictedAccountType.length() > 0) {
   1952             owner.mRestrictedAccountType = restrictedAccountType;
   1953         }
   1954 
   1955         String requiredAccountType = sa.getString(com.android.internal.R.styleable
   1956                 .AndroidManifestApplication_requiredAccountType);
   1957         if (requiredAccountType != null && requiredAccountType.length() > 0) {
   1958             owner.mRequiredAccountType = requiredAccountType;
   1959         }
   1960 
   1961         if (sa.getBoolean(
   1962                 com.android.internal.R.styleable.AndroidManifestApplication_debuggable,
   1963                 false)) {
   1964             ai.flags |= ApplicationInfo.FLAG_DEBUGGABLE;
   1965         }
   1966 
   1967         if (sa.getBoolean(
   1968                 com.android.internal.R.styleable.AndroidManifestApplication_vmSafeMode,
   1969                 false)) {
   1970             ai.flags |= ApplicationInfo.FLAG_VM_SAFE_MODE;
   1971         }
   1972 
   1973         boolean hardwareAccelerated = sa.getBoolean(
   1974                 com.android.internal.R.styleable.AndroidManifestApplication_hardwareAccelerated,
   1975                 owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH);
   1976 
   1977         if (sa.getBoolean(
   1978                 com.android.internal.R.styleable.AndroidManifestApplication_hasCode,
   1979                 true)) {
   1980             ai.flags |= ApplicationInfo.FLAG_HAS_CODE;
   1981         }
   1982 
   1983         if (sa.getBoolean(
   1984                 com.android.internal.R.styleable.AndroidManifestApplication_allowTaskReparenting,
   1985                 false)) {
   1986             ai.flags |= ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING;
   1987         }
   1988 
   1989         if (sa.getBoolean(
   1990                 com.android.internal.R.styleable.AndroidManifestApplication_allowClearUserData,
   1991                 true)) {
   1992             ai.flags |= ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA;
   1993         }
   1994 
   1995         if (sa.getBoolean(
   1996                 com.android.internal.R.styleable.AndroidManifestApplication_testOnly,
   1997                 false)) {
   1998             ai.flags |= ApplicationInfo.FLAG_TEST_ONLY;
   1999         }
   2000 
   2001         if (sa.getBoolean(
   2002                 com.android.internal.R.styleable.AndroidManifestApplication_largeHeap,
   2003                 false)) {
   2004             ai.flags |= ApplicationInfo.FLAG_LARGE_HEAP;
   2005         }
   2006 
   2007         if (sa.getBoolean(
   2008                 com.android.internal.R.styleable.AndroidManifestApplication_supportsRtl,
   2009                 false /* default is no RTL support*/)) {
   2010             ai.flags |= ApplicationInfo.FLAG_SUPPORTS_RTL;
   2011         }
   2012 
   2013         String str;
   2014         str = sa.getNonConfigurationString(
   2015                 com.android.internal.R.styleable.AndroidManifestApplication_permission, 0);
   2016         ai.permission = (str != null && str.length() > 0) ? str.intern() : null;
   2017 
   2018         if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
   2019             str = sa.getNonConfigurationString(
   2020                     com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity,
   2021                     Configuration.NATIVE_CONFIG_VERSION);
   2022         } else {
   2023             // Some older apps have been seen to use a resource reference
   2024             // here that on older builds was ignored (with a warning).  We
   2025             // need to continue to do this for them so they don't break.
   2026             str = sa.getNonResourceString(
   2027                     com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity);
   2028         }
   2029         ai.taskAffinity = buildTaskAffinityName(ai.packageName, ai.packageName,
   2030                 str, outError);
   2031 
   2032         if (outError[0] == null) {
   2033             CharSequence pname;
   2034             if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
   2035                 pname = sa.getNonConfigurationString(
   2036                         com.android.internal.R.styleable.AndroidManifestApplication_process,
   2037                         Configuration.NATIVE_CONFIG_VERSION);
   2038             } else {
   2039                 // Some older apps have been seen to use a resource reference
   2040                 // here that on older builds was ignored (with a warning).  We
   2041                 // need to continue to do this for them so they don't break.
   2042                 pname = sa.getNonResourceString(
   2043                         com.android.internal.R.styleable.AndroidManifestApplication_process);
   2044             }
   2045             ai.processName = buildProcessName(ai.packageName, null, pname,
   2046                     flags, mSeparateProcesses, outError);
   2047 
   2048             ai.enabled = sa.getBoolean(
   2049                     com.android.internal.R.styleable.AndroidManifestApplication_enabled, true);
   2050 
   2051             if (false) {
   2052                 if (sa.getBoolean(
   2053                         com.android.internal.R.styleable.AndroidManifestApplication_cantSaveState,
   2054                         false)) {
   2055                     ai.flags |= ApplicationInfo.FLAG_CANT_SAVE_STATE;
   2056 
   2057                     // A heavy-weight application can not be in a custom process.
   2058                     // We can do direct compare because we intern all strings.
   2059                     if (ai.processName != null && ai.processName != ai.packageName) {
   2060                         outError[0] = "cantSaveState applications can not use custom processes";
   2061                     }
   2062                 }
   2063             }
   2064         }
   2065 
   2066         ai.uiOptions = sa.getInt(
   2067                 com.android.internal.R.styleable.AndroidManifestApplication_uiOptions, 0);
   2068 
   2069         sa.recycle();
   2070 
   2071         if (outError[0] != null) {
   2072             mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2073             return false;
   2074         }
   2075 
   2076         final int innerDepth = parser.getDepth();
   2077 
   2078         int type;
   2079         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   2080                 && (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
   2081             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2082                 continue;
   2083             }
   2084 
   2085             String tagName = parser.getName();
   2086             if (tagName.equals("activity")) {
   2087                 Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false,
   2088                         hardwareAccelerated);
   2089                 if (a == null) {
   2090                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2091                     return false;
   2092                 }
   2093 
   2094                 owner.activities.add(a);
   2095 
   2096             } else if (tagName.equals("receiver")) {
   2097                 Activity a = parseActivity(owner, res, parser, attrs, flags, outError, true, false);
   2098                 if (a == null) {
   2099                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2100                     return false;
   2101                 }
   2102 
   2103                 owner.receivers.add(a);
   2104 
   2105             } else if (tagName.equals("service")) {
   2106                 Service s = parseService(owner, res, parser, attrs, flags, outError);
   2107                 if (s == null) {
   2108                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2109                     return false;
   2110                 }
   2111 
   2112                 owner.services.add(s);
   2113 
   2114             } else if (tagName.equals("provider")) {
   2115                 Provider p = parseProvider(owner, res, parser, attrs, flags, outError);
   2116                 if (p == null) {
   2117                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2118                     return false;
   2119                 }
   2120 
   2121                 owner.providers.add(p);
   2122 
   2123             } else if (tagName.equals("activity-alias")) {
   2124                 Activity a = parseActivityAlias(owner, res, parser, attrs, flags, outError);
   2125                 if (a == null) {
   2126                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2127                     return false;
   2128                 }
   2129 
   2130                 owner.activities.add(a);
   2131 
   2132             } else if (parser.getName().equals("meta-data")) {
   2133                 // note: application meta-data is stored off to the side, so it can
   2134                 // remain null in the primary copy (we like to avoid extra copies because
   2135                 // it can be large)
   2136                 if ((owner.mAppMetaData = parseMetaData(res, parser, attrs, owner.mAppMetaData,
   2137                         outError)) == null) {
   2138                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2139                     return false;
   2140                 }
   2141 
   2142             } else if (tagName.equals("library")) {
   2143                 sa = res.obtainAttributes(attrs,
   2144                         com.android.internal.R.styleable.AndroidManifestLibrary);
   2145 
   2146                 // Note: don't allow this value to be a reference to a resource
   2147                 // that may change.
   2148                 String lname = sa.getNonResourceString(
   2149                         com.android.internal.R.styleable.AndroidManifestLibrary_name);
   2150 
   2151                 sa.recycle();
   2152 
   2153                 if (lname != null) {
   2154                     if (owner.libraryNames == null) {
   2155                         owner.libraryNames = new ArrayList<String>();
   2156                     }
   2157                     if (!owner.libraryNames.contains(lname)) {
   2158                         owner.libraryNames.add(lname.intern());
   2159                     }
   2160                 }
   2161 
   2162                 XmlUtils.skipCurrentTag(parser);
   2163 
   2164             } else if (tagName.equals("uses-library")) {
   2165                 sa = res.obtainAttributes(attrs,
   2166                         com.android.internal.R.styleable.AndroidManifestUsesLibrary);
   2167 
   2168                 // Note: don't allow this value to be a reference to a resource
   2169                 // that may change.
   2170                 String lname = sa.getNonResourceString(
   2171                         com.android.internal.R.styleable.AndroidManifestUsesLibrary_name);
   2172                 boolean req = sa.getBoolean(
   2173                         com.android.internal.R.styleable.AndroidManifestUsesLibrary_required,
   2174                         true);
   2175 
   2176                 sa.recycle();
   2177 
   2178                 if (lname != null) {
   2179                     if (req) {
   2180                         if (owner.usesLibraries == null) {
   2181                             owner.usesLibraries = new ArrayList<String>();
   2182                         }
   2183                         if (!owner.usesLibraries.contains(lname)) {
   2184                             owner.usesLibraries.add(lname.intern());
   2185                         }
   2186                     } else {
   2187                         if (owner.usesOptionalLibraries == null) {
   2188                             owner.usesOptionalLibraries = new ArrayList<String>();
   2189                         }
   2190                         if (!owner.usesOptionalLibraries.contains(lname)) {
   2191                             owner.usesOptionalLibraries.add(lname.intern());
   2192                         }
   2193                     }
   2194                 }
   2195 
   2196                 XmlUtils.skipCurrentTag(parser);
   2197 
   2198             } else if (tagName.equals("uses-package")) {
   2199                 // Dependencies for app installers; we don't currently try to
   2200                 // enforce this.
   2201                 XmlUtils.skipCurrentTag(parser);
   2202 
   2203             } else {
   2204                 if (!RIGID_PARSER) {
   2205                     Slog.w(TAG, "Unknown element under <application>: " + tagName
   2206                             + " at " + mArchiveSourcePath + " "
   2207                             + parser.getPositionDescription());
   2208                     XmlUtils.skipCurrentTag(parser);
   2209                     continue;
   2210                 } else {
   2211                     outError[0] = "Bad element under <application>: " + tagName;
   2212                     mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
   2213                     return false;
   2214                 }
   2215             }
   2216         }
   2217 
   2218         return true;
   2219     }
   2220 
   2221     private boolean parsePackageItemInfo(Package owner, PackageItemInfo outInfo,
   2222             String[] outError, String tag, TypedArray sa,
   2223             int nameRes, int labelRes, int iconRes, int logoRes) {
   2224         String name = sa.getNonConfigurationString(nameRes, 0);
   2225         if (name == null) {
   2226             outError[0] = tag + " does not specify android:name";
   2227             return false;
   2228         }
   2229 
   2230         outInfo.name
   2231             = buildClassName(owner.applicationInfo.packageName, name, outError);
   2232         if (outInfo.name == null) {
   2233             return false;
   2234         }
   2235 
   2236         int iconVal = sa.getResourceId(iconRes, 0);
   2237         if (iconVal != 0) {
   2238             outInfo.icon = iconVal;
   2239             outInfo.nonLocalizedLabel = null;
   2240         }
   2241 
   2242         int logoVal = sa.getResourceId(logoRes, 0);
   2243         if (logoVal != 0) {
   2244             outInfo.logo = logoVal;
   2245         }
   2246 
   2247         TypedValue v = sa.peekValue(labelRes);
   2248         if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
   2249             outInfo.nonLocalizedLabel = v.coerceToString();
   2250         }
   2251 
   2252         outInfo.packageName = owner.packageName;
   2253 
   2254         return true;
   2255     }
   2256 
   2257     private Activity parseActivity(Package owner, Resources res,
   2258             XmlPullParser parser, AttributeSet attrs, int flags, String[] outError,
   2259             boolean receiver, boolean hardwareAccelerated)
   2260             throws XmlPullParserException, IOException {
   2261         TypedArray sa = res.obtainAttributes(attrs,
   2262                 com.android.internal.R.styleable.AndroidManifestActivity);
   2263 
   2264         if (mParseActivityArgs == null) {
   2265             mParseActivityArgs = new ParseComponentArgs(owner, outError,
   2266                     com.android.internal.R.styleable.AndroidManifestActivity_name,
   2267                     com.android.internal.R.styleable.AndroidManifestActivity_label,
   2268                     com.android.internal.R.styleable.AndroidManifestActivity_icon,
   2269                     com.android.internal.R.styleable.AndroidManifestActivity_logo,
   2270                     mSeparateProcesses,
   2271                     com.android.internal.R.styleable.AndroidManifestActivity_process,
   2272                     com.android.internal.R.styleable.AndroidManifestActivity_description,
   2273                     com.android.internal.R.styleable.AndroidManifestActivity_enabled);
   2274         }
   2275 
   2276         mParseActivityArgs.tag = receiver ? "<receiver>" : "<activity>";
   2277         mParseActivityArgs.sa = sa;
   2278         mParseActivityArgs.flags = flags;
   2279 
   2280         Activity a = new Activity(mParseActivityArgs, new ActivityInfo());
   2281         if (outError[0] != null) {
   2282             sa.recycle();
   2283             return null;
   2284         }
   2285 
   2286         boolean setExported = sa.hasValue(
   2287                 com.android.internal.R.styleable.AndroidManifestActivity_exported);
   2288         if (setExported) {
   2289             a.info.exported = sa.getBoolean(
   2290                     com.android.internal.R.styleable.AndroidManifestActivity_exported, false);
   2291         }
   2292 
   2293         a.info.theme = sa.getResourceId(
   2294                 com.android.internal.R.styleable.AndroidManifestActivity_theme, 0);
   2295 
   2296         a.info.uiOptions = sa.getInt(
   2297                 com.android.internal.R.styleable.AndroidManifestActivity_uiOptions,
   2298                 a.info.applicationInfo.uiOptions);
   2299 
   2300         String parentName = sa.getNonConfigurationString(
   2301                 com.android.internal.R.styleable.AndroidManifestActivity_parentActivityName,
   2302                 Configuration.NATIVE_CONFIG_VERSION);
   2303         if (parentName != null) {
   2304             String parentClassName = buildClassName(a.info.packageName, parentName, outError);
   2305             if (outError[0] == null) {
   2306                 a.info.parentActivityName = parentClassName;
   2307             } else {
   2308                 Log.e(TAG, "Activity " + a.info.name + " specified invalid parentActivityName " +
   2309                         parentName);
   2310                 outError[0] = null;
   2311             }
   2312         }
   2313 
   2314         String str;
   2315         str = sa.getNonConfigurationString(
   2316                 com.android.internal.R.styleable.AndroidManifestActivity_permission, 0);
   2317         if (str == null) {
   2318             a.info.permission = owner.applicationInfo.permission;
   2319         } else {
   2320             a.info.permission = str.length() > 0 ? str.toString().intern() : null;
   2321         }
   2322 
   2323         str = sa.getNonConfigurationString(
   2324                 com.android.internal.R.styleable.AndroidManifestActivity_taskAffinity,
   2325                 Configuration.NATIVE_CONFIG_VERSION);
   2326         a.info.taskAffinity = buildTaskAffinityName(owner.applicationInfo.packageName,
   2327                 owner.applicationInfo.taskAffinity, str, outError);
   2328 
   2329         a.info.flags = 0;
   2330         if (sa.getBoolean(
   2331                 com.android.internal.R.styleable.AndroidManifestActivity_multiprocess,
   2332                 false)) {
   2333             a.info.flags |= ActivityInfo.FLAG_MULTIPROCESS;
   2334         }
   2335 
   2336         if (sa.getBoolean(
   2337                 com.android.internal.R.styleable.AndroidManifestActivity_finishOnTaskLaunch,
   2338                 false)) {
   2339             a.info.flags |= ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH;
   2340         }
   2341 
   2342         if (sa.getBoolean(
   2343                 com.android.internal.R.styleable.AndroidManifestActivity_clearTaskOnLaunch,
   2344                 false)) {
   2345             a.info.flags |= ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH;
   2346         }
   2347 
   2348         if (sa.getBoolean(
   2349                 com.android.internal.R.styleable.AndroidManifestActivity_noHistory,
   2350                 false)) {
   2351             a.info.flags |= ActivityInfo.FLAG_NO_HISTORY;
   2352         }
   2353 
   2354         if (sa.getBoolean(
   2355                 com.android.internal.R.styleable.AndroidManifestActivity_alwaysRetainTaskState,
   2356                 false)) {
   2357             a.info.flags |= ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE;
   2358         }
   2359 
   2360         if (sa.getBoolean(
   2361                 com.android.internal.R.styleable.AndroidManifestActivity_stateNotNeeded,
   2362                 false)) {
   2363             a.info.flags |= ActivityInfo.FLAG_STATE_NOT_NEEDED;
   2364         }
   2365 
   2366         if (sa.getBoolean(
   2367                 com.android.internal.R.styleable.AndroidManifestActivity_excludeFromRecents,
   2368                 false)) {
   2369             a.info.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
   2370         }
   2371 
   2372         if (sa.getBoolean(
   2373                 com.android.internal.R.styleable.AndroidManifestActivity_allowTaskReparenting,
   2374                 (owner.applicationInfo.flags&ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING) != 0)) {
   2375             a.info.flags |= ActivityInfo.FLAG_ALLOW_TASK_REPARENTING;
   2376         }
   2377 
   2378         if (sa.getBoolean(
   2379                 com.android.internal.R.styleable.AndroidManifestActivity_finishOnCloseSystemDialogs,
   2380                 false)) {
   2381             a.info.flags |= ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
   2382         }
   2383 
   2384         if (sa.getBoolean(
   2385                 com.android.internal.R.styleable.AndroidManifestActivity_showOnLockScreen,
   2386                 false)) {
   2387             a.info.flags |= ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN;
   2388         }
   2389 
   2390         if (sa.getBoolean(
   2391                 com.android.internal.R.styleable.AndroidManifestActivity_immersive,
   2392                 false)) {
   2393             a.info.flags |= ActivityInfo.FLAG_IMMERSIVE;
   2394         }
   2395 
   2396         if (!receiver) {
   2397             if (sa.getBoolean(
   2398                     com.android.internal.R.styleable.AndroidManifestActivity_hardwareAccelerated,
   2399                     hardwareAccelerated)) {
   2400                 a.info.flags |= ActivityInfo.FLAG_HARDWARE_ACCELERATED;
   2401             }
   2402 
   2403             a.info.launchMode = sa.getInt(
   2404                     com.android.internal.R.styleable.AndroidManifestActivity_launchMode,
   2405                     ActivityInfo.LAUNCH_MULTIPLE);
   2406             a.info.screenOrientation = sa.getInt(
   2407                     com.android.internal.R.styleable.AndroidManifestActivity_screenOrientation,
   2408                     ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
   2409             a.info.configChanges = sa.getInt(
   2410                     com.android.internal.R.styleable.AndroidManifestActivity_configChanges,
   2411                     0);
   2412             a.info.softInputMode = sa.getInt(
   2413                     com.android.internal.R.styleable.AndroidManifestActivity_windowSoftInputMode,
   2414                     0);
   2415         } else {
   2416             a.info.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
   2417             a.info.configChanges = 0;
   2418         }
   2419 
   2420         if (receiver) {
   2421             if (sa.getBoolean(
   2422                     com.android.internal.R.styleable.AndroidManifestActivity_singleUser,
   2423                     false)) {
   2424                 a.info.flags |= ActivityInfo.FLAG_SINGLE_USER;
   2425                 if (a.info.exported) {
   2426                     Slog.w(TAG, "Activity exported request ignored due to singleUser: "
   2427                             + a.className + " at " + mArchiveSourcePath + " "
   2428                             + parser.getPositionDescription());
   2429                     a.info.exported = false;
   2430                 }
   2431                 setExported = true;
   2432             }
   2433             if (sa.getBoolean(
   2434                     com.android.internal.R.styleable.AndroidManifestActivity_primaryUserOnly,
   2435                     false)) {
   2436                 a.info.flags |= ActivityInfo.FLAG_PRIMARY_USER_ONLY;
   2437             }
   2438         }
   2439 
   2440         sa.recycle();
   2441 
   2442         if (receiver && (owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
   2443             // A heavy-weight application can not have receives in its main process
   2444             // We can do direct compare because we intern all strings.
   2445             if (a.info.processName == owner.packageName) {
   2446                 outError[0] = "Heavy-weight applications can not have receivers in main process";
   2447             }
   2448         }
   2449 
   2450         if (outError[0] != null) {
   2451             return null;
   2452         }
   2453 
   2454         int outerDepth = parser.getDepth();
   2455         int type;
   2456         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   2457                && (type != XmlPullParser.END_TAG
   2458                        || parser.getDepth() > outerDepth)) {
   2459             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2460                 continue;
   2461             }
   2462 
   2463             if (parser.getName().equals("intent-filter")) {
   2464                 ActivityIntentInfo intent = new ActivityIntentInfo(a);
   2465                 if (!parseIntent(res, parser, attrs, true, intent, outError)) {
   2466                     return null;
   2467                 }
   2468                 if (intent.countActions() == 0) {
   2469                     Slog.w(TAG, "No actions in intent filter at "
   2470                             + mArchiveSourcePath + " "
   2471                             + parser.getPositionDescription());
   2472                 } else {
   2473                     a.intents.add(intent);
   2474                 }
   2475             } else if (!receiver && parser.getName().equals("preferred")) {
   2476                 ActivityIntentInfo intent = new ActivityIntentInfo(a);
   2477                 if (!parseIntent(res, parser, attrs, false, intent, outError)) {
   2478                     return null;
   2479                 }
   2480                 if (intent.countActions() == 0) {
   2481                     Slog.w(TAG, "No actions in preferred at "
   2482                             + mArchiveSourcePath + " "
   2483                             + parser.getPositionDescription());
   2484                 } else {
   2485                     if (owner.preferredActivityFilters == null) {
   2486                         owner.preferredActivityFilters = new ArrayList<ActivityIntentInfo>();
   2487                     }
   2488                     owner.preferredActivityFilters.add(intent);
   2489                 }
   2490             } else if (parser.getName().equals("meta-data")) {
   2491                 if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
   2492                         outError)) == null) {
   2493                     return null;
   2494                 }
   2495             } else {
   2496                 if (!RIGID_PARSER) {
   2497                     Slog.w(TAG, "Problem in package " + mArchiveSourcePath + ":");
   2498                     if (receiver) {
   2499                         Slog.w(TAG, "Unknown element under <receiver>: " + parser.getName()
   2500                                 + " at " + mArchiveSourcePath + " "
   2501                                 + parser.getPositionDescription());
   2502                     } else {
   2503                         Slog.w(TAG, "Unknown element under <activity>: " + parser.getName()
   2504                                 + " at " + mArchiveSourcePath + " "
   2505                                 + parser.getPositionDescription());
   2506                     }
   2507                     XmlUtils.skipCurrentTag(parser);
   2508                     continue;
   2509                 } else {
   2510                     if (receiver) {
   2511                         outError[0] = "Bad element under <receiver>: " + parser.getName();
   2512                     } else {
   2513                         outError[0] = "Bad element under <activity>: " + parser.getName();
   2514                     }
   2515                     return null;
   2516                 }
   2517             }
   2518         }
   2519 
   2520         if (!setExported) {
   2521             a.info.exported = a.intents.size() > 0;
   2522         }
   2523 
   2524         return a;
   2525     }
   2526 
   2527     private Activity parseActivityAlias(Package owner, Resources res,
   2528             XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
   2529             throws XmlPullParserException, IOException {
   2530         TypedArray sa = res.obtainAttributes(attrs,
   2531                 com.android.internal.R.styleable.AndroidManifestActivityAlias);
   2532 
   2533         String targetActivity = sa.getNonConfigurationString(
   2534                 com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity,
   2535                 Configuration.NATIVE_CONFIG_VERSION);
   2536         if (targetActivity == null) {
   2537             outError[0] = "<activity-alias> does not specify android:targetActivity";
   2538             sa.recycle();
   2539             return null;
   2540         }
   2541 
   2542         targetActivity = buildClassName(owner.applicationInfo.packageName,
   2543                 targetActivity, outError);
   2544         if (targetActivity == null) {
   2545             sa.recycle();
   2546             return null;
   2547         }
   2548 
   2549         if (mParseActivityAliasArgs == null) {
   2550             mParseActivityAliasArgs = new ParseComponentArgs(owner, outError,
   2551                     com.android.internal.R.styleable.AndroidManifestActivityAlias_name,
   2552                     com.android.internal.R.styleable.AndroidManifestActivityAlias_label,
   2553                     com.android.internal.R.styleable.AndroidManifestActivityAlias_icon,
   2554                     com.android.internal.R.styleable.AndroidManifestActivityAlias_logo,
   2555                     mSeparateProcesses,
   2556                     0,
   2557                     com.android.internal.R.styleable.AndroidManifestActivityAlias_description,
   2558                     com.android.internal.R.styleable.AndroidManifestActivityAlias_enabled);
   2559             mParseActivityAliasArgs.tag = "<activity-alias>";
   2560         }
   2561 
   2562         mParseActivityAliasArgs.sa = sa;
   2563         mParseActivityAliasArgs.flags = flags;
   2564 
   2565         Activity target = null;
   2566 
   2567         final int NA = owner.activities.size();
   2568         for (int i=0; i<NA; i++) {
   2569             Activity t = owner.activities.get(i);
   2570             if (targetActivity.equals(t.info.name)) {
   2571                 target = t;
   2572                 break;
   2573             }
   2574         }
   2575 
   2576         if (target == null) {
   2577             outError[0] = "<activity-alias> target activity " + targetActivity
   2578                     + " not found in manifest";
   2579             sa.recycle();
   2580             return null;
   2581         }
   2582 
   2583         ActivityInfo info = new ActivityInfo();
   2584         info.targetActivity = targetActivity;
   2585         info.configChanges = target.info.configChanges;
   2586         info.flags = target.info.flags;
   2587         info.icon = target.info.icon;
   2588         info.logo = target.info.logo;
   2589         info.labelRes = target.info.labelRes;
   2590         info.nonLocalizedLabel = target.info.nonLocalizedLabel;
   2591         info.launchMode = target.info.launchMode;
   2592         info.processName = target.info.processName;
   2593         if (info.descriptionRes == 0) {
   2594             info.descriptionRes = target.info.descriptionRes;
   2595         }
   2596         info.screenOrientation = target.info.screenOrientation;
   2597         info.taskAffinity = target.info.taskAffinity;
   2598         info.theme = target.info.theme;
   2599         info.softInputMode = target.info.softInputMode;
   2600         info.uiOptions = target.info.uiOptions;
   2601         info.parentActivityName = target.info.parentActivityName;
   2602 
   2603         Activity a = new Activity(mParseActivityAliasArgs, info);
   2604         if (outError[0] != null) {
   2605             sa.recycle();
   2606             return null;
   2607         }
   2608 
   2609         final boolean setExported = sa.hasValue(
   2610                 com.android.internal.R.styleable.AndroidManifestActivityAlias_exported);
   2611         if (setExported) {
   2612             a.info.exported = sa.getBoolean(
   2613                     com.android.internal.R.styleable.AndroidManifestActivityAlias_exported, false);
   2614         }
   2615 
   2616         String str;
   2617         str = sa.getNonConfigurationString(
   2618                 com.android.internal.R.styleable.AndroidManifestActivityAlias_permission, 0);
   2619         if (str != null) {
   2620             a.info.permission = str.length() > 0 ? str.toString().intern() : null;
   2621         }
   2622 
   2623         String parentName = sa.getNonConfigurationString(
   2624                 com.android.internal.R.styleable.AndroidManifestActivityAlias_parentActivityName,
   2625                 Configuration.NATIVE_CONFIG_VERSION);
   2626         if (parentName != null) {
   2627             String parentClassName = buildClassName(a.info.packageName, parentName, outError);
   2628             if (outError[0] == null) {
   2629                 a.info.parentActivityName = parentClassName;
   2630             } else {
   2631                 Log.e(TAG, "Activity alias " + a.info.name +
   2632                         " specified invalid parentActivityName " + parentName);
   2633                 outError[0] = null;
   2634             }
   2635         }
   2636 
   2637         sa.recycle();
   2638 
   2639         if (outError[0] != null) {
   2640             return null;
   2641         }
   2642 
   2643         int outerDepth = parser.getDepth();
   2644         int type;
   2645         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   2646                && (type != XmlPullParser.END_TAG
   2647                        || parser.getDepth() > outerDepth)) {
   2648             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2649                 continue;
   2650             }
   2651 
   2652             if (parser.getName().equals("intent-filter")) {
   2653                 ActivityIntentInfo intent = new ActivityIntentInfo(a);
   2654                 if (!parseIntent(res, parser, attrs, true, intent, outError)) {
   2655                     return null;
   2656                 }
   2657                 if (intent.countActions() == 0) {
   2658                     Slog.w(TAG, "No actions in intent filter at "
   2659                             + mArchiveSourcePath + " "
   2660                             + parser.getPositionDescription());
   2661                 } else {
   2662                     a.intents.add(intent);
   2663                 }
   2664             } else if (parser.getName().equals("meta-data")) {
   2665                 if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
   2666                         outError)) == null) {
   2667                     return null;
   2668                 }
   2669             } else {
   2670                 if (!RIGID_PARSER) {
   2671                     Slog.w(TAG, "Unknown element under <activity-alias>: " + parser.getName()
   2672                             + " at " + mArchiveSourcePath + " "
   2673                             + parser.getPositionDescription());
   2674                     XmlUtils.skipCurrentTag(parser);
   2675                     continue;
   2676                 } else {
   2677                     outError[0] = "Bad element under <activity-alias>: " + parser.getName();
   2678                     return null;
   2679                 }
   2680             }
   2681         }
   2682 
   2683         if (!setExported) {
   2684             a.info.exported = a.intents.size() > 0;
   2685         }
   2686 
   2687         return a;
   2688     }
   2689 
   2690     private Provider parseProvider(Package owner, Resources res,
   2691             XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
   2692             throws XmlPullParserException, IOException {
   2693         TypedArray sa = res.obtainAttributes(attrs,
   2694                 com.android.internal.R.styleable.AndroidManifestProvider);
   2695 
   2696         if (mParseProviderArgs == null) {
   2697             mParseProviderArgs = new ParseComponentArgs(owner, outError,
   2698                     com.android.internal.R.styleable.AndroidManifestProvider_name,
   2699                     com.android.internal.R.styleable.AndroidManifestProvider_label,
   2700                     com.android.internal.R.styleable.AndroidManifestProvider_icon,
   2701                     com.android.internal.R.styleable.AndroidManifestProvider_logo,
   2702                     mSeparateProcesses,
   2703                     com.android.internal.R.styleable.AndroidManifestProvider_process,
   2704                     com.android.internal.R.styleable.AndroidManifestProvider_description,
   2705                     com.android.internal.R.styleable.AndroidManifestProvider_enabled);
   2706             mParseProviderArgs.tag = "<provider>";
   2707         }
   2708 
   2709         mParseProviderArgs.sa = sa;
   2710         mParseProviderArgs.flags = flags;
   2711 
   2712         Provider p = new Provider(mParseProviderArgs, new ProviderInfo());
   2713         if (outError[0] != null) {
   2714             sa.recycle();
   2715             return null;
   2716         }
   2717 
   2718         boolean providerExportedDefault = false;
   2719 
   2720         if (owner.applicationInfo.targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
   2721             // For compatibility, applications targeting API level 16 or lower
   2722             // should have their content providers exported by default, unless they
   2723             // specify otherwise.
   2724             providerExportedDefault = true;
   2725         }
   2726 
   2727         p.info.exported = sa.getBoolean(
   2728                 com.android.internal.R.styleable.AndroidManifestProvider_exported,
   2729                 providerExportedDefault);
   2730 
   2731         String cpname = sa.getNonConfigurationString(
   2732                 com.android.internal.R.styleable.AndroidManifestProvider_authorities, 0);
   2733 
   2734         p.info.isSyncable = sa.getBoolean(
   2735                 com.android.internal.R.styleable.AndroidManifestProvider_syncable,
   2736                 false);
   2737 
   2738         String permission = sa.getNonConfigurationString(
   2739                 com.android.internal.R.styleable.AndroidManifestProvider_permission, 0);
   2740         String str = sa.getNonConfigurationString(
   2741                 com.android.internal.R.styleable.AndroidManifestProvider_readPermission, 0);
   2742         if (str == null) {
   2743             str = permission;
   2744         }
   2745         if (str == null) {
   2746             p.info.readPermission = owner.applicationInfo.permission;
   2747         } else {
   2748             p.info.readPermission =
   2749                 str.length() > 0 ? str.toString().intern() : null;
   2750         }
   2751         str = sa.getNonConfigurationString(
   2752                 com.android.internal.R.styleable.AndroidManifestProvider_writePermission, 0);
   2753         if (str == null) {
   2754             str = permission;
   2755         }
   2756         if (str == null) {
   2757             p.info.writePermission = owner.applicationInfo.permission;
   2758         } else {
   2759             p.info.writePermission =
   2760                 str.length() > 0 ? str.toString().intern() : null;
   2761         }
   2762 
   2763         p.info.grantUriPermissions = sa.getBoolean(
   2764                 com.android.internal.R.styleable.AndroidManifestProvider_grantUriPermissions,
   2765                 false);
   2766 
   2767         p.info.multiprocess = sa.getBoolean(
   2768                 com.android.internal.R.styleable.AndroidManifestProvider_multiprocess,
   2769                 false);
   2770 
   2771         p.info.initOrder = sa.getInt(
   2772                 com.android.internal.R.styleable.AndroidManifestProvider_initOrder,
   2773                 0);
   2774 
   2775         p.info.flags = 0;
   2776 
   2777         if (sa.getBoolean(
   2778                 com.android.internal.R.styleable.AndroidManifestProvider_singleUser,
   2779                 false)) {
   2780             p.info.flags |= ProviderInfo.FLAG_SINGLE_USER;
   2781             if (p.info.exported) {
   2782                 Slog.w(TAG, "Provider exported request ignored due to singleUser: "
   2783                         + p.className + " at " + mArchiveSourcePath + " "
   2784                         + parser.getPositionDescription());
   2785                 p.info.exported = false;
   2786             }
   2787         }
   2788 
   2789         sa.recycle();
   2790 
   2791         if ((owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
   2792             // A heavy-weight application can not have providers in its main process
   2793             // We can do direct compare because we intern all strings.
   2794             if (p.info.processName == owner.packageName) {
   2795                 outError[0] = "Heavy-weight applications can not have providers in main process";
   2796                 return null;
   2797             }
   2798         }
   2799 
   2800         if (cpname == null) {
   2801             outError[0] = "<provider> does not include authorities attribute";
   2802             return null;
   2803         }
   2804         p.info.authority = cpname.intern();
   2805 
   2806         if (!parseProviderTags(res, parser, attrs, p, outError)) {
   2807             return null;
   2808         }
   2809 
   2810         return p;
   2811     }
   2812 
   2813     private boolean parseProviderTags(Resources res,
   2814             XmlPullParser parser, AttributeSet attrs,
   2815             Provider outInfo, String[] outError)
   2816             throws XmlPullParserException, IOException {
   2817         int outerDepth = parser.getDepth();
   2818         int type;
   2819         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   2820                && (type != XmlPullParser.END_TAG
   2821                        || parser.getDepth() > outerDepth)) {
   2822             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   2823                 continue;
   2824             }
   2825 
   2826             if (parser.getName().equals("intent-filter")) {
   2827                 ProviderIntentInfo intent = new ProviderIntentInfo(outInfo);
   2828                 if (!parseIntent(res, parser, attrs, true, intent, outError)) {
   2829                     return false;
   2830                 }
   2831                 outInfo.intents.add(intent);
   2832 
   2833             } else if (parser.getName().equals("meta-data")) {
   2834                 if ((outInfo.metaData=parseMetaData(res, parser, attrs,
   2835                         outInfo.metaData, outError)) == null) {
   2836                     return false;
   2837                 }
   2838 
   2839             } else if (parser.getName().equals("grant-uri-permission")) {
   2840                 TypedArray sa = res.obtainAttributes(attrs,
   2841                         com.android.internal.R.styleable.AndroidManifestGrantUriPermission);
   2842 
   2843                 PatternMatcher pa = null;
   2844 
   2845                 String str = sa.getNonConfigurationString(
   2846                         com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path, 0);
   2847                 if (str != null) {
   2848                     pa = new PatternMatcher(str, PatternMatcher.PATTERN_LITERAL);
   2849                 }
   2850 
   2851                 str = sa.getNonConfigurationString(
   2852                         com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix, 0);
   2853                 if (str != null) {
   2854                     pa = new PatternMatcher(str, PatternMatcher.PATTERN_PREFIX);
   2855                 }
   2856 
   2857                 str = sa.getNonConfigurationString(
   2858                         com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern, 0);
   2859                 if (str != null) {
   2860                     pa = new PatternMatcher(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
   2861                 }
   2862 
   2863                 sa.recycle();
   2864 
   2865                 if (pa != null) {
   2866                     if (outInfo.info.uriPermissionPatterns == null) {
   2867                         outInfo.info.uriPermissionPatterns = new PatternMatcher[1];
   2868                         outInfo.info.uriPermissionPatterns[0] = pa;
   2869                     } else {
   2870                         final int N = outInfo.info.uriPermissionPatterns.length;
   2871                         PatternMatcher[] newp = new PatternMatcher[N+1];
   2872                         System.arraycopy(outInfo.info.uriPermissionPatterns, 0, newp, 0, N);
   2873                         newp[N] = pa;
   2874                         outInfo.info.uriPermissionPatterns = newp;
   2875                     }
   2876                     outInfo.info.grantUriPermissions = true;
   2877                 } else {
   2878                     if (!RIGID_PARSER) {
   2879                         Slog.w(TAG, "Unknown element under <path-permission>: "
   2880                                 + parser.getName() + " at " + mArchiveSourcePath + " "
   2881                                 + parser.getPositionDescription());
   2882                         XmlUtils.skipCurrentTag(parser);
   2883                         continue;
   2884                     } else {
   2885                         outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
   2886                         return false;
   2887                     }
   2888                 }
   2889                 XmlUtils.skipCurrentTag(parser);
   2890 
   2891             } else if (parser.getName().equals("path-permission")) {
   2892                 TypedArray sa = res.obtainAttributes(attrs,
   2893                         com.android.internal.R.styleable.AndroidManifestPathPermission);
   2894 
   2895                 PathPermission pa = null;
   2896 
   2897                 String permission = sa.getNonConfigurationString(
   2898                         com.android.internal.R.styleable.AndroidManifestPathPermission_permission, 0);
   2899                 String readPermission = sa.getNonConfigurationString(
   2900                         com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission, 0);
   2901                 if (readPermission == null) {
   2902                     readPermission = permission;
   2903                 }
   2904                 String writePermission = sa.getNonConfigurationString(
   2905                         com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission, 0);
   2906                 if (writePermission == null) {
   2907                     writePermission = permission;
   2908                 }
   2909 
   2910                 boolean havePerm = false;
   2911                 if (readPermission != null) {
   2912                     readPermission = readPermission.intern();
   2913                     havePerm = true;
   2914                 }
   2915                 if (writePermission != null) {
   2916                     writePermission = writePermission.intern();
   2917                     havePerm = true;
   2918                 }
   2919 
   2920                 if (!havePerm) {
   2921                     if (!RIGID_PARSER) {
   2922                         Slog.w(TAG, "No readPermission or writePermssion for <path-permission>: "
   2923                                 + parser.getName() + " at " + mArchiveSourcePath + " "
   2924                                 + parser.getPositionDescription());
   2925                         XmlUtils.skipCurrentTag(parser);
   2926                         continue;
   2927                     } else {
   2928                         outError[0] = "No readPermission or writePermssion for <path-permission>";
   2929                         return false;
   2930                     }
   2931                 }
   2932 
   2933                 String path = sa.getNonConfigurationString(
   2934                         com.android.internal.R.styleable.AndroidManifestPathPermission_path, 0);
   2935                 if (path != null) {
   2936                     pa = new PathPermission(path,
   2937                             PatternMatcher.PATTERN_LITERAL, readPermission, writePermission);
   2938                 }
   2939 
   2940                 path = sa.getNonConfigurationString(
   2941                         com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix, 0);
   2942                 if (path != null) {
   2943                     pa = new PathPermission(path,
   2944                             PatternMatcher.PATTERN_PREFIX, readPermission, writePermission);
   2945                 }
   2946 
   2947                 path = sa.getNonConfigurationString(
   2948                         com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern, 0);
   2949                 if (path != null) {
   2950                     pa = new PathPermission(path,
   2951                             PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
   2952                 }
   2953 
   2954                 sa.recycle();
   2955 
   2956                 if (pa != null) {
   2957                     if (outInfo.info.pathPermissions == null) {
   2958                         outInfo.info.pathPermissions = new PathPermission[1];
   2959                         outInfo.info.pathPermissions[0] = pa;
   2960                     } else {
   2961                         final int N = outInfo.info.pathPermissions.length;
   2962                         PathPermission[] newp = new PathPermission[N+1];
   2963                         System.arraycopy(outInfo.info.pathPermissions, 0, newp, 0, N);
   2964                         newp[N] = pa;
   2965                         outInfo.info.pathPermissions = newp;
   2966                     }
   2967                 } else {
   2968                     if (!RIGID_PARSER) {
   2969                         Slog.w(TAG, "No path, pathPrefix, or pathPattern for <path-permission>: "
   2970                                 + parser.getName() + " at " + mArchiveSourcePath + " "
   2971                                 + parser.getPositionDescription());
   2972                         XmlUtils.skipCurrentTag(parser);
   2973                         continue;
   2974                     }
   2975                     outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
   2976                     return false;
   2977                 }
   2978                 XmlUtils.skipCurrentTag(parser);
   2979 
   2980             } else {
   2981                 if (!RIGID_PARSER) {
   2982                     Slog.w(TAG, "Unknown element under <provider>: "
   2983                             + parser.getName() + " at " + mArchiveSourcePath + " "
   2984                             + parser.getPositionDescription());
   2985                     XmlUtils.skipCurrentTag(parser);
   2986                     continue;
   2987                 } else {
   2988                     outError[0] = "Bad element under <provider>: " + parser.getName();
   2989                     return false;
   2990                 }
   2991             }
   2992         }
   2993         return true;
   2994     }
   2995 
   2996     private Service parseService(Package owner, Resources res,
   2997             XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
   2998             throws XmlPullParserException, IOException {
   2999         TypedArray sa = res.obtainAttributes(attrs,
   3000                 com.android.internal.R.styleable.AndroidManifestService);
   3001 
   3002         if (mParseServiceArgs == null) {
   3003             mParseServiceArgs = new ParseComponentArgs(owner, outError,
   3004                     com.android.internal.R.styleable.AndroidManifestService_name,
   3005                     com.android.internal.R.styleable.AndroidManifestService_label,
   3006                     com.android.internal.R.styleable.AndroidManifestService_icon,
   3007                     com.android.internal.R.styleable.AndroidManifestService_logo,
   3008                     mSeparateProcesses,
   3009                     com.android.internal.R.styleable.AndroidManifestService_process,
   3010                     com.android.internal.R.styleable.AndroidManifestService_description,
   3011                     com.android.internal.R.styleable.AndroidManifestService_enabled);
   3012             mParseServiceArgs.tag = "<service>";
   3013         }
   3014 
   3015         mParseServiceArgs.sa = sa;
   3016         mParseServiceArgs.flags = flags;
   3017 
   3018         Service s = new Service(mParseServiceArgs, new ServiceInfo());
   3019         if (outError[0] != null) {
   3020             sa.recycle();
   3021             return null;
   3022         }
   3023 
   3024         boolean setExported = sa.hasValue(
   3025                 com.android.internal.R.styleable.AndroidManifestService_exported);
   3026         if (setExported) {
   3027             s.info.exported = sa.getBoolean(
   3028                     com.android.internal.R.styleable.AndroidManifestService_exported, false);
   3029         }
   3030 
   3031         String str = sa.getNonConfigurationString(
   3032                 com.android.internal.R.styleable.AndroidManifestService_permission, 0);
   3033         if (str == null) {
   3034             s.info.permission = owner.applicationInfo.permission;
   3035         } else {
   3036             s.info.permission = str.length() > 0 ? str.toString().intern() : null;
   3037         }
   3038 
   3039         s.info.flags = 0;
   3040         if (sa.getBoolean(
   3041                 com.android.internal.R.styleable.AndroidManifestService_stopWithTask,
   3042                 false)) {
   3043             s.info.flags |= ServiceInfo.FLAG_STOP_WITH_TASK;
   3044         }
   3045         if (sa.getBoolean(
   3046                 com.android.internal.R.styleable.AndroidManifestService_isolatedProcess,
   3047                 false)) {
   3048             s.info.flags |= ServiceInfo.FLAG_ISOLATED_PROCESS;
   3049         }
   3050         if (sa.getBoolean(
   3051                 com.android.internal.R.styleable.AndroidManifestService_singleUser,
   3052                 false)) {
   3053             s.info.flags |= ServiceInfo.FLAG_SINGLE_USER;
   3054             if (s.info.exported) {
   3055                 Slog.w(TAG, "Service exported request ignored due to singleUser: "
   3056                         + s.className + " at " + mArchiveSourcePath + " "
   3057                         + parser.getPositionDescription());
   3058                 s.info.exported = false;
   3059             }
   3060             setExported = true;
   3061         }
   3062 
   3063         sa.recycle();
   3064 
   3065         if ((owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
   3066             // A heavy-weight application can not have services in its main process
   3067             // We can do direct compare because we intern all strings.
   3068             if (s.info.processName == owner.packageName) {
   3069                 outError[0] = "Heavy-weight applications can not have services in main process";
   3070                 return null;
   3071             }
   3072         }
   3073 
   3074         int outerDepth = parser.getDepth();
   3075         int type;
   3076         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   3077                && (type != XmlPullParser.END_TAG
   3078                        || parser.getDepth() > outerDepth)) {
   3079             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   3080                 continue;
   3081             }
   3082 
   3083             if (parser.getName().equals("intent-filter")) {
   3084                 ServiceIntentInfo intent = new ServiceIntentInfo(s);
   3085                 if (!parseIntent(res, parser, attrs, true, intent, outError)) {
   3086                     return null;
   3087                 }
   3088 
   3089                 s.intents.add(intent);
   3090             } else if (parser.getName().equals("meta-data")) {
   3091                 if ((s.metaData=parseMetaData(res, parser, attrs, s.metaData,
   3092                         outError)) == null) {
   3093                     return null;
   3094                 }
   3095             } else {
   3096                 if (!RIGID_PARSER) {
   3097                     Slog.w(TAG, "Unknown element under <service>: "
   3098                             + parser.getName() + " at " + mArchiveSourcePath + " "
   3099                             + parser.getPositionDescription());
   3100                     XmlUtils.skipCurrentTag(parser);
   3101                     continue;
   3102                 } else {
   3103                     outError[0] = "Bad element under <service>: " + parser.getName();
   3104                     return null;
   3105                 }
   3106             }
   3107         }
   3108 
   3109         if (!setExported) {
   3110             s.info.exported = s.intents.size() > 0;
   3111         }
   3112 
   3113         return s;
   3114     }
   3115 
   3116     private boolean parseAllMetaData(Resources res,
   3117             XmlPullParser parser, AttributeSet attrs, String tag,
   3118             Component outInfo, String[] outError)
   3119             throws XmlPullParserException, IOException {
   3120         int outerDepth = parser.getDepth();
   3121         int type;
   3122         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
   3123                && (type != XmlPullParser.END_TAG
   3124                        || parser.getDepth() > outerDepth)) {
   3125             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   3126                 continue;
   3127             }
   3128 
   3129             if (parser.getName().equals("meta-data")) {
   3130                 if ((outInfo.metaData=parseMetaData(res, parser, attrs,
   3131                         outInfo.metaData, outError)) == null) {
   3132                     return false;
   3133                 }
   3134             } else {
   3135                 if (!RIGID_PARSER) {
   3136                     Slog.w(TAG, "Unknown element under " + tag + ": "
   3137                             + parser.getName() + " at " + mArchiveSourcePath + " "
   3138                             + parser.getPositionDescription());
   3139                     XmlUtils.skipCurrentTag(parser);
   3140                     continue;
   3141                 } else {
   3142                     outError[0] = "Bad element under " + tag + ": " + parser.getName();
   3143                     return false;
   3144                 }
   3145             }
   3146         }
   3147         return true;
   3148     }
   3149 
   3150     private Bundle parseMetaData(Resources res,
   3151             XmlPullParser parser, AttributeSet attrs,
   3152             Bundle data, String[] outError)
   3153             throws XmlPullParserException, IOException {
   3154 
   3155         TypedArray sa = res.obtainAttributes(attrs,
   3156                 com.android.internal.R.styleable.AndroidManifestMetaData);
   3157 
   3158         if (data == null) {
   3159             data = new Bundle();
   3160         }
   3161 
   3162         String name = sa.getNonConfigurationString(
   3163                 com.android.internal.R.styleable.AndroidManifestMetaData_name, 0);
   3164         if (name == null) {
   3165             outError[0] = "<meta-data> requires an android:name attribute";
   3166             sa.recycle();
   3167             return null;
   3168         }
   3169 
   3170         name = name.intern();
   3171 
   3172         TypedValue v = sa.peekValue(
   3173                 com.android.internal.R.styleable.AndroidManifestMetaData_resource);
   3174         if (v != null && v.resourceId != 0) {
   3175             //Slog.i(TAG, "Meta data ref " + name + ": " + v);
   3176             data.putInt(name, v.resourceId);
   3177         } else {
   3178             v = sa.peekValue(
   3179                     com.android.internal.R.styleable.AndroidManifestMetaData_value);
   3180             //Slog.i(TAG, "Meta data " + name + ": " + v);
   3181             if (v != null) {
   3182                 if (v.type == TypedValue.TYPE_STRING) {
   3183                     CharSequence cs = v.coerceToString();
   3184                     data.putString(name, cs != null ? cs.toString().intern() : null);
   3185                 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
   3186                     data.putBoolean(name, v.data != 0);
   3187                 } else if (v.type >= TypedValue.TYPE_FIRST_INT
   3188                         && v.type <= TypedValue.TYPE_LAST_INT) {
   3189                     data.putInt(name, v.data);
   3190                 } else if (v.type == TypedValue.TYPE_FLOAT) {
   3191                     data.putFloat(name, v.getFloat());
   3192                 } else {
   3193                     if (!RIGID_PARSER) {
   3194                         Slog.w(TAG, "<meta-data> only supports string, integer, float, color, boolean, and resource reference types: "
   3195                                 + parser.getName() + " at " + mArchiveSourcePath + " "
   3196                                 + parser.getPositionDescription());
   3197                     } else {
   3198                         outError[0] = "<meta-data> only supports string, integer, float, color, boolean, and resource reference types";
   3199                         data = null;
   3200                     }
   3201                 }
   3202             } else {
   3203                 outError[0] = "<meta-data> requires an android:value or android:resource attribute";
   3204                 data = null;
   3205             }
   3206         }
   3207 
   3208         sa.recycle();
   3209 
   3210         XmlUtils.skipCurrentTag(parser);
   3211 
   3212         return data;
   3213     }
   3214 
   3215     private static VerifierInfo parseVerifier(Resources res, XmlPullParser parser,
   3216             AttributeSet attrs, int flags, String[] outError) throws XmlPullParserException,
   3217             IOException {
   3218         final TypedArray sa = res.obtainAttributes(attrs,
   3219                 com.android.internal.R.styleable.AndroidManifestPackageVerifier);
   3220 
   3221         final String packageName = sa.getNonResourceString(
   3222                 com.android.internal.R.styleable.AndroidManifestPackageVerifier_name);
   3223 
   3224         final String encodedPublicKey = sa.getNonResourceString(
   3225                 com.android.internal.R.styleable.AndroidManifestPackageVerifier_publicKey);
   3226 
   3227         sa.recycle();
   3228 
   3229         if (packageName == null || packageName.length() == 0) {
   3230             Slog.i(TAG, "verifier package name was null; skipping");
   3231             return null;
   3232         } else if (encodedPublicKey == null) {
   3233             Slog.i(TAG, "verifier " + packageName + " public key was null; skipping");
   3234         }
   3235 
   3236         PublicKey publicKey = parsePublicKey(encodedPublicKey);
   3237         if (publicKey != null) {
   3238             return new VerifierInfo(packageName, publicKey);
   3239         }
   3240 
   3241         return null;
   3242     }
   3243 
   3244     public static final PublicKey parsePublicKey(String encodedPublicKey) {
   3245         EncodedKeySpec keySpec;
   3246         try {
   3247             final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT);
   3248             keySpec = new X509EncodedKeySpec(encoded);
   3249         } catch (IllegalArgumentException e) {
   3250             Slog.i(TAG, "Could not parse verifier public key; invalid Base64");
   3251             return null;
   3252         }
   3253 
   3254         /* First try the key as an RSA key. */
   3255         try {
   3256             final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   3257             return keyFactory.generatePublic(keySpec);
   3258         } catch (NoSuchAlgorithmException e) {
   3259             Log.wtf(TAG, "Could not parse public key because RSA isn't included in build");
   3260             return null;
   3261         } catch (InvalidKeySpecException e) {
   3262             // Not a RSA public key.
   3263         }
   3264 
   3265         /* Now try it as a DSA key. */
   3266         try {
   3267             final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
   3268             return keyFactory.generatePublic(keySpec);
   3269         } catch (NoSuchAlgorithmException e) {
   3270             Log.wtf(TAG, "Could not parse public key because DSA isn't included in build");
   3271             return null;
   3272         } catch (InvalidKeySpecException e) {
   3273             // Not a DSA public key.
   3274         }
   3275 
   3276         return null;
   3277     }
   3278 
   3279     private static final String ANDROID_RESOURCES
   3280             = "http://schemas.android.com/apk/res/android";
   3281 
   3282     private boolean parseIntent(Resources res, XmlPullParser parser, AttributeSet attrs,
   3283             boolean allowGlobs, IntentInfo outInfo, String[] outError)
   3284             throws XmlPullParserException, IOException {
   3285 
   3286         TypedArray sa = res.obtainAttributes(attrs,
   3287                 com.android.internal.R.styleable.AndroidManifestIntentFilter);
   3288 
   3289         int priority = sa.getInt(
   3290                 com.android.internal.R.styleable.AndroidManifestIntentFilter_priority, 0);
   3291         outInfo.setPriority(priority);
   3292 
   3293         TypedValue v = sa.peekValue(
   3294                 com.android.internal.R.styleable.AndroidManifestIntentFilter_label);
   3295         if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
   3296             outInfo.nonLocalizedLabel = v.coerceToString();
   3297         }
   3298 
   3299         outInfo.icon = sa.getResourceId(
   3300                 com.android.internal.R.styleable.AndroidManifestIntentFilter_icon, 0);
   3301 
   3302         outInfo.logo = sa.getResourceId(
   3303                 com.android.internal.R.styleable.AndroidManifestIntentFilter_logo, 0);
   3304 
   3305         sa.recycle();
   3306 
   3307         int outerDepth = parser.getDepth();
   3308         int type;
   3309         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
   3310                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
   3311             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
   3312                 continue;
   3313             }
   3314 
   3315             String nodeName = parser.getName();
   3316             if (nodeName.equals("action")) {
   3317                 String value = attrs.getAttributeValue(
   3318                         ANDROID_RESOURCES, "name");
   3319                 if (value == null || value == "") {
   3320                     outError[0] = "No value supplied for <android:name>";
   3321                     return false;
   3322                 }
   3323                 XmlUtils.skipCurrentTag(parser);
   3324 
   3325                 outInfo.addAction(value);
   3326             } else if (nodeName.equals("category")) {
   3327                 String value = attrs.getAttributeValue(
   3328                         ANDROID_RESOURCES, "name");
   3329                 if (value == null || value == "") {
   3330                     outError[0] = "No value supplied for <android:name>";
   3331                     return false;
   3332                 }
   3333                 XmlUtils.skipCurrentTag(parser);
   3334 
   3335                 outInfo.addCategory(value);
   3336 
   3337             } else if (nodeName.equals("data")) {
   3338                 sa = res.obtainAttributes(attrs,
   3339                         com.android.internal.R.styleable.AndroidManifestData);
   3340 
   3341                 String str = sa.getNonConfigurationString(
   3342                         com.android.internal.R.styleable.AndroidManifestData_mimeType, 0);
   3343                 if (str != null) {
   3344                     try {
   3345                         outInfo.addDataType(str);
   3346                     } catch (IntentFilter.MalformedMimeTypeException e) {
   3347                         outError[0] = e.toString();
   3348                         sa.recycle();
   3349                         return false;
   3350                     }
   3351                 }
   3352 
   3353                 str = sa.getNonConfigurationString(
   3354                         com.android.internal.R.styleable.AndroidManifestData_scheme, 0);
   3355                 if (str != null) {
   3356                     outInfo.addDataScheme(str);
   3357                 }
   3358 
   3359                 str = sa.getNonConfigurationString(
   3360                         com.android.internal.R.styleable.AndroidManifestData_ssp, 0);
   3361                 if (str != null) {
   3362                     outInfo.addDataSchemeSpecificPart(str, PatternMatcher.PATTERN_LITERAL);
   3363                 }
   3364 
   3365                 str = sa.getNonConfigurationString(
   3366                         com.android.internal.R.styleable.AndroidManifestData_sspPrefix, 0);
   3367                 if (str != null) {
   3368                     outInfo.addDataSchemeSpecificPart(str, PatternMatcher.PATTERN_PREFIX);
   3369                 }
   3370 
   3371                 str = sa.getNonConfigurationString(
   3372                         com.android.internal.R.styleable.AndroidManifestData_sspPattern, 0);
   3373                 if (str != null) {
   3374                     if (!allowGlobs) {
   3375                         outError[0] = "sspPattern not allowed here; ssp must be literal";
   3376                         return false;
   3377                     }
   3378                     outInfo.addDataSchemeSpecificPart(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
   3379                 }
   3380 
   3381                 String host = sa.getNonConfigurationString(
   3382                         com.android.internal.R.styleable.AndroidManifestData_host, 0);
   3383                 String port = sa.getNonConfigurationString(
   3384                         com.android.internal.R.styleable.AndroidManifestData_port, 0);
   3385                 if (host != null) {
   3386                     outInfo.addDataAuthority(host, port);
   3387                 }
   3388 
   3389                 str = sa.getNonConfigurationString(
   3390                         com.android.internal.R.styleable.AndroidManifestData_path, 0);
   3391                 if (str != null) {
   3392                     outInfo.addDataPath(str, PatternMatcher.PATTERN_LITERAL);
   3393                 }
   3394 
   3395                 str = sa.getNonConfigurationString(
   3396                         com.android.internal.R.styleable.AndroidManifestData_pathPrefix, 0);
   3397                 if (str != null) {
   3398                     outInfo.addDataPath(str, PatternMatcher.PATTERN_PREFIX);
   3399                 }
   3400 
   3401                 str = sa.getNonConfigurationString(
   3402                         com.android.internal.R.styleable.AndroidManifestData_pathPattern, 0);
   3403                 if (str != null) {
   3404                     if (!allowGlobs) {
   3405                         outError[0] = "pathPattern not allowed here; path must be literal";
   3406                         return false;
   3407                     }
   3408                     outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
   3409                 }
   3410 
   3411                 sa.recycle();
   3412                 XmlUtils.skipCurrentTag(parser);
   3413             } else if (!RIGID_PARSER) {
   3414                 Slog.w(TAG, "Unknown element under <intent-filter>: "
   3415                         + parser.getName() + " at " + mArchiveSourcePath + " "
   3416                         + parser.getPositionDescription());
   3417                 XmlUtils.skipCurrentTag(parser);
   3418             } else {
   3419                 outError[0] = "Bad element under <intent-filter>: " + parser.getName();
   3420                 return false;
   3421             }
   3422         }
   3423 
   3424         outInfo.hasDefault = outInfo.hasCategory(Intent.CATEGORY_DEFAULT);
   3425 
   3426         if (DEBUG_PARSER) {
   3427             final StringBuilder cats = new StringBuilder("Intent d=");
   3428             cats.append(outInfo.hasDefault);
   3429             cats.append(", cat=");
   3430 
   3431             final Iterator<String> it = outInfo.categoriesIterator();
   3432             if (it != null) {
   3433                 while (it.hasNext()) {
   3434                     cats.append(' ');
   3435                     cats.append(it.next());
   3436                 }
   3437             }
   3438             Slog.d(TAG, cats.toString());
   3439         }
   3440 
   3441         return true;
   3442     }
   3443 
   3444     public final static class Package {
   3445 
   3446         public String packageName;
   3447 
   3448         // For now we only support one application per package.
   3449         public final ApplicationInfo applicationInfo = new ApplicationInfo();
   3450 
   3451         public final ArrayList<Permission> permissions = new ArrayList<Permission>(0);
   3452         public final ArrayList<PermissionGroup> permissionGroups = new ArrayList<PermissionGroup>(0);
   3453         public final ArrayList<Activity> activities = new ArrayList<Activity>(0);
   3454         public final ArrayList<Activity> receivers = new ArrayList<Activity>(0);
   3455         public final ArrayList<Provider> providers = new ArrayList<Provider>(0);
   3456         public final ArrayList<Service> services = new ArrayList<Service>(0);
   3457         public final ArrayList<Instrumentation> instrumentation = new ArrayList<Instrumentation>(0);
   3458 
   3459         public final ArrayList<String> requestedPermissions = new ArrayList<String>();
   3460         public final ArrayList<Boolean> requestedPermissionsRequired = new ArrayList<Boolean>();
   3461 
   3462         public ArrayList<String> protectedBroadcasts;
   3463 
   3464         public ArrayList<String> libraryNames = null;
   3465         public ArrayList<String> usesLibraries = null;
   3466         public ArrayList<String> usesOptionalLibraries = null;
   3467         public String[] usesLibraryFiles = null;
   3468 
   3469         public ArrayList<ActivityIntentInfo> preferredActivityFilters = null;
   3470 
   3471         public ArrayList<String> mOriginalPackages = null;
   3472         public String mRealPackage = null;
   3473         public ArrayList<String> mAdoptPermissions = null;
   3474 
   3475         // We store the application meta-data independently to avoid multiple unwanted references
   3476         public Bundle mAppMetaData = null;
   3477 
   3478         // If this is a 3rd party app, this is the path of the zip file.
   3479         public String mPath;
   3480 
   3481         // The version code declared for this package.
   3482         public int mVersionCode;
   3483 
   3484         // The version name declared for this package.
   3485         public String mVersionName;
   3486 
   3487         // The shared user id that this package wants to use.
   3488         public String mSharedUserId;
   3489 
   3490         // The shared user label that this package wants to use.
   3491         public int mSharedUserLabel;
   3492 
   3493         // Signatures that were read from the package.
   3494         public Signature mSignatures[];
   3495 
   3496         // For use by package manager service for quick lookup of
   3497         // preferred up order.
   3498         public int mPreferredOrder = 0;
   3499 
   3500         // For use by the package manager to keep track of the path to the
   3501         // file an app came from.
   3502         public String mScanPath;
   3503 
   3504         // For use by package manager to keep track of where it has done dexopt.
   3505         public boolean mDidDexOpt;
   3506 
   3507         // // User set enabled state.
   3508         // public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
   3509         //
   3510         // // Whether the package has been stopped.
   3511         // public boolean mSetStopped = false;
   3512 
   3513         // Additional data supplied by callers.
   3514         public Object mExtras;
   3515 
   3516         // Whether an operation is currently pending on this package
   3517         public boolean mOperationPending;
   3518 
   3519         /*
   3520          *  Applications hardware preferences
   3521          */
   3522         public final ArrayList<ConfigurationInfo> configPreferences =
   3523                 new ArrayList<ConfigurationInfo>();
   3524 
   3525         /*
   3526          *  Applications requested features
   3527          */
   3528         public ArrayList<FeatureInfo> reqFeatures = null;
   3529 
   3530         public int installLocation;
   3531 
   3532         /* An app that's required for all users and cannot be uninstalled for a user */
   3533         public boolean mRequiredForAllUsers;
   3534 
   3535         /* The restricted account authenticator type that is used by this application */
   3536         public String mRestrictedAccountType;
   3537 
   3538         /* The required account type without which this application will not function */
   3539         public String mRequiredAccountType;
   3540 
   3541         /**
   3542          * Digest suitable for comparing whether this package's manifest is the
   3543          * same as another.
   3544          */
   3545         public ManifestDigest manifestDigest;
   3546 
   3547         /**
   3548          * Data used to feed the KeySetManager
   3549          */
   3550         public Set<PublicKey> mSigningKeys;
   3551         public Map<String, Set<PublicKey>> mKeySetMapping;
   3552 
   3553         public Package(String _name) {
   3554             packageName = _name;
   3555             applicationInfo.packageName = _name;
   3556             applicationInfo.uid = -1;
   3557         }
   3558 
   3559         public void setPackageName(String newName) {
   3560             packageName = newName;
   3561             applicationInfo.packageName = newName;
   3562             for (int i=permissions.size()-1; i>=0; i--) {
   3563                 permissions.get(i).setPackageName(newName);
   3564             }
   3565             for (int i=permissionGroups.size()-1; i>=0; i--) {
   3566                 permissionGroups.get(i).setPackageName(newName);
   3567             }
   3568             for (int i=activities.size()-1; i>=0; i--) {
   3569                 activities.get(i).setPackageName(newName);
   3570             }
   3571             for (int i=receivers.size()-1; i>=0; i--) {
   3572                 receivers.get(i).setPackageName(newName);
   3573             }
   3574             for (int i=providers.size()-1; i>=0; i--) {
   3575                 providers.get(i).setPackageName(newName);
   3576             }
   3577             for (int i=services.size()-1; i>=0; i--) {
   3578                 services.get(i).setPackageName(newName);
   3579             }
   3580             for (int i=instrumentation.size()-1; i>=0; i--) {
   3581                 instrumentation.get(i).setPackageName(newName);
   3582             }
   3583         }
   3584 
   3585         public boolean hasComponentClassName(String name) {
   3586             for (int i=activities.size()-1; i>=0; i--) {
   3587                 if (name.equals(activities.get(i).className)) {
   3588                     return true;
   3589                 }
   3590             }
   3591             for (int i=receivers.size()-1; i>=0; i--) {
   3592                 if (name.equals(receivers.get(i).className)) {
   3593                     return true;
   3594                 }
   3595             }
   3596             for (int i=providers.size()-1; i>=0; i--) {
   3597                 if (name.equals(providers.get(i).className)) {
   3598                     return true;
   3599                 }
   3600             }
   3601             for (int i=services.size()-1; i>=0; i--) {
   3602                 if (name.equals(services.get(i).className)) {
   3603                     return true;
   3604                 }
   3605             }
   3606             for (int i=instrumentation.size()-1; i>=0; i--) {
   3607                 if (name.equals(instrumentation.get(i).className)) {
   3608                     return true;
   3609                 }
   3610             }
   3611             return false;
   3612         }
   3613 
   3614         public String toString() {
   3615             return "Package{"
   3616                 + Integer.toHexString(System.identityHashCode(this))
   3617                 + " " + packageName + "}";
   3618         }
   3619     }
   3620 
   3621     public static class Component<II extends IntentInfo> {
   3622         public final Package owner;
   3623         public final ArrayList<II> intents;
   3624         public final String className;
   3625         public Bundle metaData;
   3626 
   3627         ComponentName componentName;
   3628         String componentShortName;
   3629 
   3630         public Component(Package _owner) {
   3631             owner = _owner;
   3632             intents = null;
   3633             className = null;
   3634         }
   3635 
   3636         public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
   3637             owner = args.owner;
   3638             intents = new ArrayList<II>(0);
   3639             String name = args.sa.getNonConfigurationString(args.nameRes, 0);
   3640             if (name == null) {
   3641                 className = null;
   3642                 args.outError[0] = args.tag + " does not specify android:name";
   3643                 return;
   3644             }
   3645 
   3646             outInfo.name
   3647                 = buildClassName(owner.applicationInfo.packageName, name, args.outError);
   3648             if (outInfo.name == null) {
   3649                 className = null;
   3650                 args.outError[0] = args.tag + " does not have valid android:name";
   3651                 return;
   3652             }
   3653 
   3654             className = outInfo.name;
   3655 
   3656             int iconVal = args.sa.getResourceId(args.iconRes, 0);
   3657             if (iconVal != 0) {
   3658                 outInfo.icon = iconVal;
   3659                 outInfo.nonLocalizedLabel = null;
   3660             }
   3661 
   3662             int logoVal = args.sa.getResourceId(args.logoRes, 0);
   3663             if (logoVal != 0) {
   3664                 outInfo.logo = logoVal;
   3665             }
   3666 
   3667             TypedValue v = args.sa.peekValue(args.labelRes);
   3668             if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
   3669                 outInfo.nonLocalizedLabel = v.coerceToString();
   3670             }
   3671 
   3672             outInfo.packageName = owner.packageName;
   3673         }
   3674 
   3675         public Component(final ParseComponentArgs args, final ComponentInfo outInfo) {
   3676             this(args, (PackageItemInfo)outInfo);
   3677             if (args.outError[0] != null) {
   3678                 return;
   3679             }
   3680 
   3681             if (args.processRes != 0) {
   3682                 CharSequence pname;
   3683                 if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
   3684                     pname = args.sa.getNonConfigurationString(args.processRes,
   3685                             Configuration.NATIVE_CONFIG_VERSION);
   3686                 } else {
   3687                     // Some older apps have been seen to use a resource reference
   3688                     // here that on older builds was ignored (with a warning).  We
   3689                     // need to continue to do this for them so they don't break.
   3690                     pname = args.sa.getNonResourceString(args.processRes);
   3691                 }
   3692                 outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
   3693                         owner.applicationInfo.processName, pname,
   3694                         args.flags, args.sepProcesses, args.outError);
   3695             }
   3696 
   3697             if (args.descriptionRes != 0) {
   3698                 outInfo.descriptionRes = args.sa.getResourceId(args.descriptionRes, 0);
   3699             }
   3700 
   3701             outInfo.enabled = args.sa.getBoolean(args.enabledRes, true);
   3702         }
   3703 
   3704         public Component(Component<II> clone) {
   3705             owner = clone.owner;
   3706             intents = clone.intents;
   3707             className = clone.className;
   3708             componentName = clone.componentName;
   3709             componentShortName = clone.componentShortName;
   3710         }
   3711 
   3712         public ComponentName getComponentName() {
   3713             if (componentName != null) {
   3714                 return componentName;
   3715             }
   3716             if (className != null) {
   3717                 componentName = new ComponentName(owner.applicationInfo.packageName,
   3718                         className);
   3719             }
   3720             return componentName;
   3721         }
   3722 
   3723         public void appendComponentShortName(StringBuilder sb) {
   3724             ComponentName.appendShortString(sb, owner.applicationInfo.packageName, className);
   3725         }
   3726 
   3727         public void printComponentShortName(PrintWriter pw) {
   3728             ComponentName.printShortString(pw, owner.applicationInfo.packageName, className);
   3729         }
   3730 
   3731         public void setPackageName(String packageName) {
   3732             componentName = null;
   3733             componentShortName = null;
   3734         }
   3735     }
   3736 
   3737     public final static class Permission extends Component<IntentInfo> {
   3738         public final PermissionInfo info;
   3739         public boolean tree;
   3740         public PermissionGroup group;
   3741 
   3742         public Permission(Package _owner) {
   3743             super(_owner);
   3744             info = new PermissionInfo();
   3745         }
   3746 
   3747         public Permission(Package _owner, PermissionInfo _info) {
   3748             super(_owner);
   3749             info = _info;
   3750         }
   3751 
   3752         public void setPackageName(String packageName) {
   3753             super.setPackageName(packageName);
   3754             info.packageName = packageName;
   3755         }
   3756 
   3757         public String toString() {
   3758             return "Permission{"
   3759                 + Integer.toHexString(System.identityHashCode(this))
   3760                 + " " + info.name + "}";
   3761         }
   3762     }
   3763 
   3764     public final static class PermissionGroup extends Component<IntentInfo> {
   3765         public final PermissionGroupInfo info;
   3766 
   3767         public PermissionGroup(Package _owner) {
   3768             super(_owner);
   3769             info = new PermissionGroupInfo();
   3770         }
   3771 
   3772         public PermissionGroup(Package _owner, PermissionGroupInfo _info) {
   3773             super(_owner);
   3774             info = _info;
   3775         }
   3776 
   3777         public void setPackageName(String packageName) {
   3778             super.setPackageName(packageName);
   3779             info.packageName = packageName;
   3780         }
   3781 
   3782         public String toString() {
   3783             return "PermissionGroup{"
   3784                 + Integer.toHexString(System.identityHashCode(this))
   3785                 + " " + info.name + "}";
   3786         }
   3787     }
   3788 
   3789     private static boolean copyNeeded(int flags, Package p,
   3790             PackageUserState state, Bundle metaData, int userId) {
   3791         if (userId != 0) {
   3792             // We always need to copy for other users, since we need
   3793             // to fix up the uid.
   3794             return true;
   3795         }
   3796         if (state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
   3797             boolean enabled = state.enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
   3798             if (p.applicationInfo.enabled != enabled) {
   3799                 return true;
   3800             }
   3801         }
   3802         if (!state.installed || state.blocked) {
   3803             return true;
   3804         }
   3805         if (state.stopped) {
   3806             return true;
   3807         }
   3808         if ((flags & PackageManager.GET_META_DATA) != 0
   3809                 && (metaData != null || p.mAppMetaData != null)) {
   3810             return true;
   3811         }
   3812         if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0
   3813                 && p.usesLibraryFiles != null) {
   3814             return true;
   3815         }
   3816         return false;
   3817     }
   3818 
   3819     public static ApplicationInfo generateApplicationInfo(Package p, int flags,
   3820             PackageUserState state) {
   3821         return generateApplicationInfo(p, flags, state, UserHandle.getCallingUserId());
   3822     }
   3823 
   3824     private static void updateApplicationInfo(ApplicationInfo ai, int flags,
   3825             PackageUserState state) {
   3826         // CompatibilityMode is global state.
   3827         if (!sCompatibilityModeEnabled) {
   3828             ai.disableCompatibilityMode();
   3829         }
   3830         if (state.installed) {
   3831             ai.flags |= ApplicationInfo.FLAG_INSTALLED;
   3832         } else {
   3833             ai.flags &= ~ApplicationInfo.FLAG_INSTALLED;
   3834         }
   3835         if (state.blocked) {
   3836             ai.flags |= ApplicationInfo.FLAG_BLOCKED;
   3837         } else {
   3838             ai.flags &= ~ApplicationInfo.FLAG_BLOCKED;
   3839         }
   3840         if (state.enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
   3841             ai.enabled = true;
   3842         } else if (state.enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
   3843             ai.enabled = (flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0;
   3844         } else if (state.enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
   3845                 || state.enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
   3846             ai.enabled = false;
   3847         }
   3848         ai.enabledSetting = state.enabled;
   3849     }
   3850 
   3851     public static ApplicationInfo generateApplicationInfo(Package p, int flags,
   3852             PackageUserState state, int userId) {
   3853         if (p == null) return null;
   3854         if (!checkUseInstalledOrBlocked(flags, state)) {
   3855             return null;
   3856         }
   3857         if (!copyNeeded(flags, p, state, null, userId)
   3858                 && ((flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) == 0
   3859                         || state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
   3860             // In this case it is safe to directly modify the internal ApplicationInfo state:
   3861             // - CompatibilityMode is global state, so will be the same for every call.
   3862             // - We only come in to here if the app should reported as installed; this is the
   3863             // default state, and we will do a copy otherwise.
   3864             // - The enable state will always be reported the same for the application across
   3865             // calls; the only exception is for the UNTIL_USED mode, and in that case we will
   3866             // be doing a copy.
   3867             updateApplicationInfo(p.applicationInfo, flags, state);
   3868             return p.applicationInfo;
   3869         }
   3870 
   3871         // Make shallow copy so we can store the metadata/libraries safely
   3872         ApplicationInfo ai = new ApplicationInfo(p.applicationInfo);
   3873         if (userId != 0) {
   3874             ai.uid = UserHandle.getUid(userId, ai.uid);
   3875             ai.dataDir = PackageManager.getDataDirForUser(userId, ai.packageName);
   3876         }
   3877         if ((flags & PackageManager.GET_META_DATA) != 0) {
   3878             ai.metaData = p.mAppMetaData;
   3879         }
   3880         if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0) {
   3881             ai.sharedLibraryFiles = p.usesLibraryFiles;
   3882         }
   3883         if (state.stopped) {
   3884             ai.flags |= ApplicationInfo.FLAG_STOPPED;
   3885         } else {
   3886             ai.flags &= ~ApplicationInfo.FLAG_STOPPED;
   3887         }
   3888         updateApplicationInfo(ai, flags, state);
   3889         return ai;
   3890     }
   3891 
   3892     public static final PermissionInfo generatePermissionInfo(
   3893             Permission p, int flags) {
   3894         if (p == null) return null;
   3895         if ((flags&PackageManager.GET_META_DATA) == 0) {
   3896             return p.info;
   3897         }
   3898         PermissionInfo pi = new PermissionInfo(p.info);
   3899         pi.metaData = p.metaData;
   3900         return pi;
   3901     }
   3902 
   3903     public static final PermissionGroupInfo generatePermissionGroupInfo(
   3904             PermissionGroup pg, int flags) {
   3905         if (pg == null) return null;
   3906         if ((flags&PackageManager.GET_META_DATA) == 0) {
   3907             return pg.info;
   3908         }
   3909         PermissionGroupInfo pgi = new PermissionGroupInfo(pg.info);
   3910         pgi.metaData = pg.metaData;
   3911         return pgi;
   3912     }
   3913 
   3914     public final static class Activity extends Component<ActivityIntentInfo> {
   3915         public final ActivityInfo info;
   3916 
   3917         public Activity(final ParseComponentArgs args, final ActivityInfo _info) {
   3918             super(args, _info);
   3919             info = _info;
   3920             info.applicationInfo = args.owner.applicationInfo;
   3921         }
   3922 
   3923         public void setPackageName(String packageName) {
   3924             super.setPackageName(packageName);
   3925             info.packageName = packageName;
   3926         }
   3927 
   3928         public String toString() {
   3929             StringBuilder sb = new StringBuilder(128);
   3930             sb.append("Activity{");
   3931             sb.append(Integer.toHexString(System.identityHashCode(this)));
   3932             sb.append(' ');
   3933             appendComponentShortName(sb);
   3934             sb.append('}');
   3935             return sb.toString();
   3936         }
   3937     }
   3938 
   3939     public static final ActivityInfo generateActivityInfo(Activity a, int flags,
   3940             PackageUserState state, int userId) {
   3941         if (a == null) return null;
   3942         if (!checkUseInstalledOrBlocked(flags, state)) {
   3943             return null;
   3944         }
   3945         if (!copyNeeded(flags, a.owner, state, a.metaData, userId)) {
   3946             return a.info;
   3947         }
   3948         // Make shallow copies so we can store the metadata safely
   3949         ActivityInfo ai = new ActivityInfo(a.info);
   3950         ai.metaData = a.metaData;
   3951         ai.applicationInfo = generateApplicationInfo(a.owner, flags, state, userId);
   3952         return ai;
   3953     }
   3954 
   3955     public final static class Service extends Component<ServiceIntentInfo> {
   3956         public final ServiceInfo info;
   3957 
   3958         public Service(final ParseComponentArgs args, final ServiceInfo _info) {
   3959             super(args, _info);
   3960             info = _info;
   3961             info.applicationInfo = args.owner.applicationInfo;
   3962         }
   3963 
   3964         public void setPackageName(String packageName) {
   3965             super.setPackageName(packageName);
   3966             info.packageName = packageName;
   3967         }
   3968 
   3969         public String toString() {
   3970             StringBuilder sb = new StringBuilder(128);
   3971             sb.append("Service{");
   3972             sb.append(Integer.toHexString(System.identityHashCode(this)));
   3973             sb.append(' ');
   3974             appendComponentShortName(sb);
   3975             sb.append('}');
   3976             return sb.toString();
   3977         }
   3978     }
   3979 
   3980     public static final ServiceInfo generateServiceInfo(Service s, int flags,
   3981             PackageUserState state, int userId) {
   3982         if (s == null) return null;
   3983         if (!checkUseInstalledOrBlocked(flags, state)) {
   3984             return null;
   3985         }
   3986         if (!copyNeeded(flags, s.owner, state, s.metaData, userId)) {
   3987             return s.info;
   3988         }
   3989         // Make shallow copies so we can store the metadata safely
   3990         ServiceInfo si = new ServiceInfo(s.info);
   3991         si.metaData = s.metaData;
   3992         si.applicationInfo = generateApplicationInfo(s.owner, flags, state, userId);
   3993         return si;
   3994     }
   3995 
   3996     public final static class Provider extends Component<ProviderIntentInfo> {
   3997         public final ProviderInfo info;
   3998         public boolean syncable;
   3999 
   4000         public Provider(final ParseComponentArgs args, final ProviderInfo _info) {
   4001             super(args, _info);
   4002             info = _info;
   4003             info.applicationInfo = args.owner.applicationInfo;
   4004             syncable = false;
   4005         }
   4006 
   4007         public Provider(Provider existingProvider) {
   4008             super(existingProvider);
   4009             this.info = existingProvider.info;
   4010             this.syncable = existingProvider.syncable;
   4011         }
   4012 
   4013         public void setPackageName(String packageName) {
   4014             super.setPackageName(packageName);
   4015             info.packageName = packageName;
   4016         }
   4017 
   4018         public String toString() {
   4019             StringBuilder sb = new StringBuilder(128);
   4020             sb.append("Provider{");
   4021             sb.append(Integer.toHexString(System.identityHashCode(this)));
   4022             sb.append(' ');
   4023             appendComponentShortName(sb);
   4024             sb.append('}');
   4025             return sb.toString();
   4026         }
   4027     }
   4028 
   4029     public static final ProviderInfo generateProviderInfo(Provider p, int flags,
   4030             PackageUserState state, int userId) {
   4031         if (p == null) return null;
   4032         if (!checkUseInstalledOrBlocked(flags, state)) {
   4033             return null;
   4034         }
   4035         if (!copyNeeded(flags, p.owner, state, p.metaData, userId)
   4036                 && ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) != 0
   4037                         || p.info.uriPermissionPatterns == null)) {
   4038             return p.info;
   4039         }
   4040         // Make shallow copies so we can store the metadata safely
   4041         ProviderInfo pi = new ProviderInfo(p.info);
   4042         pi.metaData = p.metaData;
   4043         if ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) == 0) {
   4044             pi.uriPermissionPatterns = null;
   4045         }
   4046         pi.applicationInfo = generateApplicationInfo(p.owner, flags, state, userId);
   4047         return pi;
   4048     }
   4049 
   4050     public final static class Instrumentation extends Component {
   4051         public final InstrumentationInfo info;
   4052 
   4053         public Instrumentation(final ParsePackageItemArgs args, final InstrumentationInfo _info) {
   4054             super(args, _info);
   4055             info = _info;
   4056         }
   4057 
   4058         public void setPackageName(String packageName) {
   4059             super.setPackageName(packageName);
   4060             info.packageName = packageName;
   4061         }
   4062 
   4063         public String toString() {
   4064             StringBuilder sb = new StringBuilder(128);
   4065             sb.append("Instrumentation{");
   4066             sb.append(Integer.toHexString(System.identityHashCode(this)));
   4067             sb.append(' ');
   4068             appendComponentShortName(sb);
   4069             sb.append('}');
   4070             return sb.toString();
   4071         }
   4072     }
   4073 
   4074     public static final InstrumentationInfo generateInstrumentationInfo(
   4075             Instrumentation i, int flags) {
   4076         if (i == null) return null;
   4077         if ((flags&PackageManager.GET_META_DATA) == 0) {
   4078             return i.info;
   4079         }
   4080         InstrumentationInfo ii = new InstrumentationInfo(i.info);
   4081         ii.metaData = i.metaData;
   4082         return ii;
   4083     }
   4084 
   4085     public static class IntentInfo extends IntentFilter {
   4086         public boolean hasDefault;
   4087         public int labelRes;
   4088         public CharSequence nonLocalizedLabel;
   4089         public int icon;
   4090         public int logo;
   4091         public int preferred;
   4092     }
   4093 
   4094     public final static class ActivityIntentInfo extends IntentInfo {
   4095         public final Activity activity;
   4096 
   4097         public ActivityIntentInfo(Activity _activity) {
   4098             activity = _activity;
   4099         }
   4100 
   4101         public String toString() {
   4102             StringBuilder sb = new StringBuilder(128);
   4103             sb.append("ActivityIntentInfo{");
   4104             sb.append(Integer.toHexString(System.identityHashCode(this)));
   4105             sb.append(' ');
   4106             activity.appendComponentShortName(sb);
   4107             sb.append('}');
   4108             return sb.toString();
   4109         }
   4110     }
   4111 
   4112     public final static class ServiceIntentInfo extends IntentInfo {
   4113         public final Service service;
   4114 
   4115         public ServiceIntentInfo(Service _service) {
   4116             service = _service;
   4117         }
   4118 
   4119         public String toString() {
   4120             StringBuilder sb = new StringBuilder(128);
   4121             sb.append("ServiceIntentInfo{");
   4122             sb.append(Integer.toHexString(System.identityHashCode(this)));
   4123             sb.append(' ');
   4124             service.appendComponentShortName(sb);
   4125             sb.append('}');
   4126             return sb.toString();
   4127         }
   4128     }
   4129 
   4130     public static final class ProviderIntentInfo extends IntentInfo {
   4131         public final Provider provider;
   4132 
   4133         public ProviderIntentInfo(Provider provider) {
   4134             this.provider = provider;
   4135         }
   4136 
   4137         public String toString() {
   4138             StringBuilder sb = new StringBuilder(128);
   4139             sb.append("ProviderIntentInfo{");
   4140             sb.append(Integer.toHexString(System.identityHashCode(this)));
   4141             sb.append(' ');
   4142             provider.appendComponentShortName(sb);
   4143             sb.append('}');
   4144             return sb.toString();
   4145         }
   4146     }
   4147 
   4148     /**
   4149      * @hide
   4150      */
   4151     public static void setCompatibilityModeEnabled(boolean compatibilityModeEnabled) {
   4152         sCompatibilityModeEnabled = compatibilityModeEnabled;
   4153     }
   4154 }
   4155