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