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