PackageParser.java revision 6069beb2dfed6da837bf7faa3db3f6119edc017a
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.getNonConfigurationString(
759                com.android.internal.R.styleable.AndroidManifest_versionName, 0);
760        if (pkg.mVersionName != null) {
761            pkg.mVersionName = pkg.mVersionName.intern();
762        }
763        String str = sa.getNonConfigurationString(
764                com.android.internal.R.styleable.AndroidManifest_sharedUserId, 0);
765        if (str != null && str.length() > 0) {
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                // Note: don't allow this value to be a reference to a resource
832                // that may change.
833                String name = sa.getNonResourceString(
834                        com.android.internal.R.styleable.AndroidManifestUsesPermission_name);
835
836                sa.recycle();
837
838                if (name != null && !pkg.requestedPermissions.contains(name)) {
839                    pkg.requestedPermissions.add(name.intern());
840                }
841
842                XmlUtils.skipCurrentTag(parser);
843
844            } else if (tagName.equals("uses-configuration")) {
845                ConfigurationInfo cPref = new ConfigurationInfo();
846                sa = res.obtainAttributes(attrs,
847                        com.android.internal.R.styleable.AndroidManifestUsesConfiguration);
848                cPref.reqTouchScreen = sa.getInt(
849                        com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqTouchScreen,
850                        Configuration.TOUCHSCREEN_UNDEFINED);
851                cPref.reqKeyboardType = sa.getInt(
852                        com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqKeyboardType,
853                        Configuration.KEYBOARD_UNDEFINED);
854                if (sa.getBoolean(
855                        com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqHardKeyboard,
856                        false)) {
857                    cPref.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
858                }
859                cPref.reqNavigation = sa.getInt(
860                        com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqNavigation,
861                        Configuration.NAVIGATION_UNDEFINED);
862                if (sa.getBoolean(
863                        com.android.internal.R.styleable.AndroidManifestUsesConfiguration_reqFiveWayNav,
864                        false)) {
865                    cPref.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
866                }
867                sa.recycle();
868                pkg.configPreferences.add(cPref);
869
870                XmlUtils.skipCurrentTag(parser);
871
872            } else if (tagName.equals("uses-feature")) {
873                FeatureInfo fi = new FeatureInfo();
874                sa = res.obtainAttributes(attrs,
875                        com.android.internal.R.styleable.AndroidManifestUsesFeature);
876                // Note: don't allow this value to be a reference to a resource
877                // that may change.
878                fi.name = sa.getNonResourceString(
879                        com.android.internal.R.styleable.AndroidManifestUsesFeature_name);
880                if (fi.name == null) {
881                    fi.reqGlEsVersion = sa.getInt(
882                            com.android.internal.R.styleable.AndroidManifestUsesFeature_glEsVersion,
883                            FeatureInfo.GL_ES_VERSION_UNDEFINED);
884                }
885                if (sa.getBoolean(
886                        com.android.internal.R.styleable.AndroidManifestUsesFeature_required,
887                        true)) {
888                    fi.flags |= FeatureInfo.FLAG_REQUIRED;
889                }
890                sa.recycle();
891                if (pkg.reqFeatures == null) {
892                    pkg.reqFeatures = new ArrayList<FeatureInfo>();
893                }
894                pkg.reqFeatures.add(fi);
895
896                if (fi.name == null) {
897                    ConfigurationInfo cPref = new ConfigurationInfo();
898                    cPref.reqGlEsVersion = fi.reqGlEsVersion;
899                    pkg.configPreferences.add(cPref);
900                }
901
902                XmlUtils.skipCurrentTag(parser);
903
904            } else if (tagName.equals("uses-sdk")) {
905                if (SDK_VERSION > 0) {
906                    sa = res.obtainAttributes(attrs,
907                            com.android.internal.R.styleable.AndroidManifestUsesSdk);
908
909                    int minVers = 0;
910                    String minCode = null;
911                    int targetVers = 0;
912                    String targetCode = null;
913
914                    TypedValue val = sa.peekValue(
915                            com.android.internal.R.styleable.AndroidManifestUsesSdk_minSdkVersion);
916                    if (val != null) {
917                        if (val.type == TypedValue.TYPE_STRING && val.string != null) {
918                            targetCode = minCode = val.string.toString();
919                        } else {
920                            // If it's not a string, it's an integer.
921                            targetVers = minVers = val.data;
922                        }
923                    }
924
925                    val = sa.peekValue(
926                            com.android.internal.R.styleable.AndroidManifestUsesSdk_targetSdkVersion);
927                    if (val != null) {
928                        if (val.type == TypedValue.TYPE_STRING && val.string != null) {
929                            targetCode = minCode = val.string.toString();
930                        } else {
931                            // If it's not a string, it's an integer.
932                            targetVers = val.data;
933                        }
934                    }
935
936                    sa.recycle();
937
938                    if (minCode != null) {
939                        if (!minCode.equals(SDK_CODENAME)) {
940                            if (SDK_CODENAME != null) {
941                                outError[0] = "Requires development platform " + minCode
942                                        + " (current platform is " + SDK_CODENAME + ")";
943                            } else {
944                                outError[0] = "Requires development platform " + minCode
945                                        + " but this is a release platform.";
946                            }
947                            mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
948                            return null;
949                        }
950                    } else if (minVers > SDK_VERSION) {
951                        outError[0] = "Requires newer sdk version #" + minVers
952                                + " (current version is #" + SDK_VERSION + ")";
953                        mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
954                        return null;
955                    }
956
957                    if (targetCode != null) {
958                        if (!targetCode.equals(SDK_CODENAME)) {
959                            if (SDK_CODENAME != null) {
960                                outError[0] = "Requires development platform " + targetCode
961                                        + " (current platform is " + SDK_CODENAME + ")";
962                            } else {
963                                outError[0] = "Requires development platform " + targetCode
964                                        + " but this is a release platform.";
965                            }
966                            mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
967                            return null;
968                        }
969                        // If the code matches, it definitely targets this SDK.
970                        pkg.applicationInfo.targetSdkVersion
971                                = android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
972                    } else {
973                        pkg.applicationInfo.targetSdkVersion = targetVers;
974                    }
975                }
976
977                XmlUtils.skipCurrentTag(parser);
978
979            } else if (tagName.equals("supports-screens")) {
980                sa = res.obtainAttributes(attrs,
981                        com.android.internal.R.styleable.AndroidManifestSupportsScreens);
982
983                // This is a trick to get a boolean and still able to detect
984                // if a value was actually set.
985                supportsSmallScreens = sa.getInteger(
986                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_smallScreens,
987                        supportsSmallScreens);
988                supportsNormalScreens = sa.getInteger(
989                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_normalScreens,
990                        supportsNormalScreens);
991                supportsLargeScreens = sa.getInteger(
992                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_largeScreens,
993                        supportsLargeScreens);
994                resizeable = sa.getInteger(
995                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_resizeable,
996                        supportsLargeScreens);
997                anyDensity = sa.getInteger(
998                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_anyDensity,
999                        anyDensity);
1000
1001                sa.recycle();
1002
1003                XmlUtils.skipCurrentTag(parser);
1004
1005            } else if (tagName.equals("protected-broadcast")) {
1006                sa = res.obtainAttributes(attrs,
1007                        com.android.internal.R.styleable.AndroidManifestProtectedBroadcast);
1008
1009                // Note: don't allow this value to be a reference to a resource
1010                // that may change.
1011                String name = sa.getNonResourceString(
1012                        com.android.internal.R.styleable.AndroidManifestProtectedBroadcast_name);
1013
1014                sa.recycle();
1015
1016                if (name != null && (flags&PARSE_IS_SYSTEM) != 0) {
1017                    if (pkg.protectedBroadcasts == null) {
1018                        pkg.protectedBroadcasts = new ArrayList<String>();
1019                    }
1020                    if (!pkg.protectedBroadcasts.contains(name)) {
1021                        pkg.protectedBroadcasts.add(name.intern());
1022                    }
1023                }
1024
1025                XmlUtils.skipCurrentTag(parser);
1026
1027            } else if (tagName.equals("instrumentation")) {
1028                if (parseInstrumentation(pkg, res, parser, attrs, outError) == null) {
1029                    return null;
1030                }
1031
1032            } else if (tagName.equals("original-package")) {
1033                sa = res.obtainAttributes(attrs,
1034                        com.android.internal.R.styleable.AndroidManifestOriginalPackage);
1035
1036                String orig =sa.getNonConfigurationString(
1037                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
1038                if (!pkg.packageName.equals(orig)) {
1039                    if (pkg.mOriginalPackages == null) {
1040                        pkg.mOriginalPackages = new ArrayList<String>();
1041                        pkg.mRealPackage = pkg.packageName;
1042                    }
1043                    pkg.mOriginalPackages.add(orig);
1044                }
1045
1046                sa.recycle();
1047
1048                XmlUtils.skipCurrentTag(parser);
1049
1050            } else if (tagName.equals("adopt-permissions")) {
1051                sa = res.obtainAttributes(attrs,
1052                        com.android.internal.R.styleable.AndroidManifestOriginalPackage);
1053
1054                String name = sa.getNonConfigurationString(
1055                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
1056
1057                sa.recycle();
1058
1059                if (name != null) {
1060                    if (pkg.mAdoptPermissions == null) {
1061                        pkg.mAdoptPermissions = new ArrayList<String>();
1062                    }
1063                    pkg.mAdoptPermissions.add(name);
1064                }
1065
1066                XmlUtils.skipCurrentTag(parser);
1067
1068            } else if (tagName.equals("eat-comment")) {
1069                // Just skip this tag
1070                XmlUtils.skipCurrentTag(parser);
1071                continue;
1072
1073            } else if (RIGID_PARSER) {
1074                outError[0] = "Bad element under <manifest>: "
1075                    + parser.getName();
1076                mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1077                return null;
1078
1079            } else {
1080                Log.w(TAG, "Unknown element under <manifest>: " + parser.getName()
1081                        + " at " + mArchiveSourcePath + " "
1082                        + parser.getPositionDescription());
1083                XmlUtils.skipCurrentTag(parser);
1084                continue;
1085            }
1086        }
1087
1088        if (!foundApp && pkg.instrumentation.size() == 0) {
1089            outError[0] = "<manifest> does not contain an <application> or <instrumentation>";
1090            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_EMPTY;
1091        }
1092
1093        final int NP = PackageParser.NEW_PERMISSIONS.length;
1094        StringBuilder implicitPerms = null;
1095        for (int ip=0; ip<NP; ip++) {
1096            final PackageParser.NewPermissionInfo npi
1097                    = PackageParser.NEW_PERMISSIONS[ip];
1098            if (pkg.applicationInfo.targetSdkVersion >= npi.sdkVersion) {
1099                break;
1100            }
1101            if (!pkg.requestedPermissions.contains(npi.name)) {
1102                if (implicitPerms == null) {
1103                    implicitPerms = new StringBuilder(128);
1104                    implicitPerms.append(pkg.packageName);
1105                    implicitPerms.append(": compat added ");
1106                } else {
1107                    implicitPerms.append(' ');
1108                }
1109                implicitPerms.append(npi.name);
1110                pkg.requestedPermissions.add(npi.name);
1111            }
1112        }
1113        if (implicitPerms != null) {
1114            Log.i(TAG, implicitPerms.toString());
1115        }
1116
1117        if (supportsSmallScreens < 0 || (supportsSmallScreens > 0
1118                && pkg.applicationInfo.targetSdkVersion
1119                        >= android.os.Build.VERSION_CODES.DONUT)) {
1120            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS;
1121        }
1122        if (supportsNormalScreens != 0) {
1123            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS;
1124        }
1125        if (supportsLargeScreens < 0 || (supportsLargeScreens > 0
1126                && pkg.applicationInfo.targetSdkVersion
1127                        >= android.os.Build.VERSION_CODES.DONUT)) {
1128            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS;
1129        }
1130        if (resizeable < 0 || (resizeable > 0
1131                && pkg.applicationInfo.targetSdkVersion
1132                        >= android.os.Build.VERSION_CODES.DONUT)) {
1133            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS;
1134        }
1135        if (anyDensity < 0 || (anyDensity > 0
1136                && pkg.applicationInfo.targetSdkVersion
1137                        >= android.os.Build.VERSION_CODES.DONUT)) {
1138            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES;
1139        }
1140
1141        return pkg;
1142    }
1143
1144    private static String buildClassName(String pkg, CharSequence clsSeq,
1145            String[] outError) {
1146        if (clsSeq == null || clsSeq.length() <= 0) {
1147            outError[0] = "Empty class name in package " + pkg;
1148            return null;
1149        }
1150        String cls = clsSeq.toString();
1151        char c = cls.charAt(0);
1152        if (c == '.') {
1153            return (pkg + cls).intern();
1154        }
1155        if (cls.indexOf('.') < 0) {
1156            StringBuilder b = new StringBuilder(pkg);
1157            b.append('.');
1158            b.append(cls);
1159            return b.toString().intern();
1160        }
1161        if (c >= 'a' && c <= 'z') {
1162            return cls.intern();
1163        }
1164        outError[0] = "Bad class name " + cls + " in package " + pkg;
1165        return null;
1166    }
1167
1168    private static String buildCompoundName(String pkg,
1169            CharSequence procSeq, String type, String[] outError) {
1170        String proc = procSeq.toString();
1171        char c = proc.charAt(0);
1172        if (pkg != null && c == ':') {
1173            if (proc.length() < 2) {
1174                outError[0] = "Bad " + type + " name " + proc + " in package " + pkg
1175                        + ": must be at least two characters";
1176                return null;
1177            }
1178            String subName = proc.substring(1);
1179            String nameError = validateName(subName, false);
1180            if (nameError != null) {
1181                outError[0] = "Invalid " + type + " name " + proc + " in package "
1182                        + pkg + ": " + nameError;
1183                return null;
1184            }
1185            return (pkg + proc).intern();
1186        }
1187        String nameError = validateName(proc, true);
1188        if (nameError != null && !"system".equals(proc)) {
1189            outError[0] = "Invalid " + type + " name " + proc + " in package "
1190                    + pkg + ": " + nameError;
1191            return null;
1192        }
1193        return proc.intern();
1194    }
1195
1196    private static String buildProcessName(String pkg, String defProc,
1197            CharSequence procSeq, int flags, String[] separateProcesses,
1198            String[] outError) {
1199        if ((flags&PARSE_IGNORE_PROCESSES) != 0 && !"system".equals(procSeq)) {
1200            return defProc != null ? defProc : pkg;
1201        }
1202        if (separateProcesses != null) {
1203            for (int i=separateProcesses.length-1; i>=0; i--) {
1204                String sp = separateProcesses[i];
1205                if (sp.equals(pkg) || sp.equals(defProc) || sp.equals(procSeq)) {
1206                    return pkg;
1207                }
1208            }
1209        }
1210        if (procSeq == null || procSeq.length() <= 0) {
1211            return defProc;
1212        }
1213        return buildCompoundName(pkg, procSeq, "package", outError);
1214    }
1215
1216    private static String buildTaskAffinityName(String pkg, String defProc,
1217            CharSequence procSeq, String[] outError) {
1218        if (procSeq == null) {
1219            return defProc;
1220        }
1221        if (procSeq.length() <= 0) {
1222            return null;
1223        }
1224        return buildCompoundName(pkg, procSeq, "taskAffinity", outError);
1225    }
1226
1227    private PermissionGroup parsePermissionGroup(Package owner, Resources res,
1228            XmlPullParser parser, AttributeSet attrs, String[] outError)
1229        throws XmlPullParserException, IOException {
1230        PermissionGroup perm = new PermissionGroup(owner);
1231
1232        TypedArray sa = res.obtainAttributes(attrs,
1233                com.android.internal.R.styleable.AndroidManifestPermissionGroup);
1234
1235        if (!parsePackageItemInfo(owner, perm.info, outError,
1236                "<permission-group>", sa,
1237                com.android.internal.R.styleable.AndroidManifestPermissionGroup_name,
1238                com.android.internal.R.styleable.AndroidManifestPermissionGroup_label,
1239                com.android.internal.R.styleable.AndroidManifestPermissionGroup_icon)) {
1240            sa.recycle();
1241            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1242            return null;
1243        }
1244
1245        perm.info.descriptionRes = sa.getResourceId(
1246                com.android.internal.R.styleable.AndroidManifestPermissionGroup_description,
1247                0);
1248
1249        sa.recycle();
1250
1251        if (!parseAllMetaData(res, parser, attrs, "<permission-group>", perm,
1252                outError)) {
1253            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1254            return null;
1255        }
1256
1257        owner.permissionGroups.add(perm);
1258
1259        return perm;
1260    }
1261
1262    private Permission parsePermission(Package owner, Resources res,
1263            XmlPullParser parser, AttributeSet attrs, String[] outError)
1264        throws XmlPullParserException, IOException {
1265        Permission perm = new Permission(owner);
1266
1267        TypedArray sa = res.obtainAttributes(attrs,
1268                com.android.internal.R.styleable.AndroidManifestPermission);
1269
1270        if (!parsePackageItemInfo(owner, perm.info, outError,
1271                "<permission>", sa,
1272                com.android.internal.R.styleable.AndroidManifestPermission_name,
1273                com.android.internal.R.styleable.AndroidManifestPermission_label,
1274                com.android.internal.R.styleable.AndroidManifestPermission_icon)) {
1275            sa.recycle();
1276            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1277            return null;
1278        }
1279
1280        // Note: don't allow this value to be a reference to a resource
1281        // that may change.
1282        perm.info.group = sa.getNonResourceString(
1283                com.android.internal.R.styleable.AndroidManifestPermission_permissionGroup);
1284        if (perm.info.group != null) {
1285            perm.info.group = perm.info.group.intern();
1286        }
1287
1288        perm.info.descriptionRes = sa.getResourceId(
1289                com.android.internal.R.styleable.AndroidManifestPermission_description,
1290                0);
1291
1292        perm.info.protectionLevel = sa.getInt(
1293                com.android.internal.R.styleable.AndroidManifestPermission_protectionLevel,
1294                PermissionInfo.PROTECTION_NORMAL);
1295
1296        sa.recycle();
1297
1298        if (perm.info.protectionLevel == -1) {
1299            outError[0] = "<permission> does not specify protectionLevel";
1300            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1301            return null;
1302        }
1303
1304        if (!parseAllMetaData(res, parser, attrs, "<permission>", perm,
1305                outError)) {
1306            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1307            return null;
1308        }
1309
1310        owner.permissions.add(perm);
1311
1312        return perm;
1313    }
1314
1315    private Permission parsePermissionTree(Package owner, Resources res,
1316            XmlPullParser parser, AttributeSet attrs, String[] outError)
1317        throws XmlPullParserException, IOException {
1318        Permission perm = new Permission(owner);
1319
1320        TypedArray sa = res.obtainAttributes(attrs,
1321                com.android.internal.R.styleable.AndroidManifestPermissionTree);
1322
1323        if (!parsePackageItemInfo(owner, perm.info, outError,
1324                "<permission-tree>", sa,
1325                com.android.internal.R.styleable.AndroidManifestPermissionTree_name,
1326                com.android.internal.R.styleable.AndroidManifestPermissionTree_label,
1327                com.android.internal.R.styleable.AndroidManifestPermissionTree_icon)) {
1328            sa.recycle();
1329            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1330            return null;
1331        }
1332
1333        sa.recycle();
1334
1335        int index = perm.info.name.indexOf('.');
1336        if (index > 0) {
1337            index = perm.info.name.indexOf('.', index+1);
1338        }
1339        if (index < 0) {
1340            outError[0] = "<permission-tree> name has less than three segments: "
1341                + perm.info.name;
1342            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1343            return null;
1344        }
1345
1346        perm.info.descriptionRes = 0;
1347        perm.info.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
1348        perm.tree = true;
1349
1350        if (!parseAllMetaData(res, parser, attrs, "<permission-tree>", perm,
1351                outError)) {
1352            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1353            return null;
1354        }
1355
1356        owner.permissions.add(perm);
1357
1358        return perm;
1359    }
1360
1361    private Instrumentation parseInstrumentation(Package owner, Resources res,
1362            XmlPullParser parser, AttributeSet attrs, String[] outError)
1363        throws XmlPullParserException, IOException {
1364        TypedArray sa = res.obtainAttributes(attrs,
1365                com.android.internal.R.styleable.AndroidManifestInstrumentation);
1366
1367        if (mParseInstrumentationArgs == null) {
1368            mParseInstrumentationArgs = new ParsePackageItemArgs(owner, outError,
1369                    com.android.internal.R.styleable.AndroidManifestInstrumentation_name,
1370                    com.android.internal.R.styleable.AndroidManifestInstrumentation_label,
1371                    com.android.internal.R.styleable.AndroidManifestInstrumentation_icon);
1372            mParseInstrumentationArgs.tag = "<instrumentation>";
1373        }
1374
1375        mParseInstrumentationArgs.sa = sa;
1376
1377        Instrumentation a = new Instrumentation(mParseInstrumentationArgs,
1378                new InstrumentationInfo());
1379        if (outError[0] != null) {
1380            sa.recycle();
1381            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1382            return null;
1383        }
1384
1385        String str;
1386        // Note: don't allow this value to be a reference to a resource
1387        // that may change.
1388        str = sa.getNonResourceString(
1389                com.android.internal.R.styleable.AndroidManifestInstrumentation_targetPackage);
1390        a.info.targetPackage = str != null ? str.intern() : null;
1391
1392        a.info.handleProfiling = sa.getBoolean(
1393                com.android.internal.R.styleable.AndroidManifestInstrumentation_handleProfiling,
1394                false);
1395
1396        a.info.functionalTest = sa.getBoolean(
1397                com.android.internal.R.styleable.AndroidManifestInstrumentation_functionalTest,
1398                false);
1399
1400        sa.recycle();
1401
1402        if (a.info.targetPackage == null) {
1403            outError[0] = "<instrumentation> does not specify targetPackage";
1404            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1405            return null;
1406        }
1407
1408        if (!parseAllMetaData(res, parser, attrs, "<instrumentation>", a,
1409                outError)) {
1410            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1411            return null;
1412        }
1413
1414        owner.instrumentation.add(a);
1415
1416        return a;
1417    }
1418
1419    private boolean parseApplication(Package owner, Resources res,
1420            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
1421        throws XmlPullParserException, IOException {
1422        final ApplicationInfo ai = owner.applicationInfo;
1423        final String pkgName = owner.applicationInfo.packageName;
1424
1425        TypedArray sa = res.obtainAttributes(attrs,
1426                com.android.internal.R.styleable.AndroidManifestApplication);
1427
1428        String name = sa.getNonConfigurationString(
1429                com.android.internal.R.styleable.AndroidManifestApplication_name, 0);
1430        if (name != null) {
1431            ai.className = buildClassName(pkgName, name, outError);
1432            if (ai.className == null) {
1433                sa.recycle();
1434                mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1435                return false;
1436            }
1437        }
1438
1439        String manageSpaceActivity = sa.getNonConfigurationString(
1440                com.android.internal.R.styleable.AndroidManifestApplication_manageSpaceActivity, 0);
1441        if (manageSpaceActivity != null) {
1442            ai.manageSpaceActivityName = buildClassName(pkgName, manageSpaceActivity,
1443                    outError);
1444        }
1445
1446        boolean allowBackup = sa.getBoolean(
1447                com.android.internal.R.styleable.AndroidManifestApplication_allowBackup, true);
1448        if (allowBackup) {
1449            ai.flags |= ApplicationInfo.FLAG_ALLOW_BACKUP;
1450
1451            // backupAgent, killAfterRestore, restoreNeedsApplication, and restoreAnyVersion
1452            // are only relevant if backup is possible for the given application.
1453            String backupAgent = sa.getNonConfigurationString(
1454                    com.android.internal.R.styleable.AndroidManifestApplication_backupAgent, 0);
1455            if (backupAgent != null) {
1456                ai.backupAgentName = buildClassName(pkgName, backupAgent, outError);
1457                if (false) {
1458                    Log.v(TAG, "android:backupAgent = " + ai.backupAgentName
1459                            + " from " + pkgName + "+" + backupAgent);
1460                }
1461
1462                if (sa.getBoolean(
1463                        com.android.internal.R.styleable.AndroidManifestApplication_killAfterRestore,
1464                        true)) {
1465                    ai.flags |= ApplicationInfo.FLAG_KILL_AFTER_RESTORE;
1466                }
1467                if (sa.getBoolean(
1468                        com.android.internal.R.styleable.AndroidManifestApplication_restoreNeedsApplication,
1469                        false)) {
1470                    ai.flags |= ApplicationInfo.FLAG_RESTORE_NEEDS_APPLICATION;
1471                }
1472                if (sa.getBoolean(
1473                        com.android.internal.R.styleable.AndroidManifestApplication_restoreAnyVersion,
1474                        false)) {
1475                    ai.flags |= ApplicationInfo.FLAG_RESTORE_ANY_VERSION;
1476                }
1477            }
1478        }
1479
1480        TypedValue v = sa.peekValue(
1481                com.android.internal.R.styleable.AndroidManifestApplication_label);
1482        if (v != null && (ai.labelRes=v.resourceId) == 0) {
1483            ai.nonLocalizedLabel = v.coerceToString();
1484        }
1485
1486        ai.icon = sa.getResourceId(
1487                com.android.internal.R.styleable.AndroidManifestApplication_icon, 0);
1488        ai.theme = sa.getResourceId(
1489                com.android.internal.R.styleable.AndroidManifestApplication_theme, 0);
1490        ai.descriptionRes = sa.getResourceId(
1491                com.android.internal.R.styleable.AndroidManifestApplication_description, 0);
1492
1493        if ((flags&PARSE_IS_SYSTEM) != 0) {
1494            if (sa.getBoolean(
1495                    com.android.internal.R.styleable.AndroidManifestApplication_persistent,
1496                    false)) {
1497                ai.flags |= ApplicationInfo.FLAG_PERSISTENT;
1498            }
1499        }
1500
1501        if ((flags & PARSE_FORWARD_LOCK) != 0) {
1502            ai.flags |= ApplicationInfo.FLAG_FORWARD_LOCK;
1503        }
1504
1505        if ((flags & PARSE_ON_SDCARD) != 0) {
1506            ai.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
1507        }
1508
1509        if (sa.getBoolean(
1510                com.android.internal.R.styleable.AndroidManifestApplication_debuggable,
1511                false)) {
1512            ai.flags |= ApplicationInfo.FLAG_DEBUGGABLE;
1513        }
1514
1515        if (sa.getBoolean(
1516                com.android.internal.R.styleable.AndroidManifestApplication_safeMode,
1517                false)) {
1518            ai.flags |= ApplicationInfo.FLAG_VM_SAFE_MODE;
1519        }
1520
1521        if (sa.getBoolean(
1522                com.android.internal.R.styleable.AndroidManifestApplication_hasCode,
1523                true)) {
1524            ai.flags |= ApplicationInfo.FLAG_HAS_CODE;
1525        }
1526
1527        if (sa.getBoolean(
1528                com.android.internal.R.styleable.AndroidManifestApplication_allowTaskReparenting,
1529                false)) {
1530            ai.flags |= ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING;
1531        }
1532
1533        if (sa.getBoolean(
1534                com.android.internal.R.styleable.AndroidManifestApplication_allowClearUserData,
1535                true)) {
1536            ai.flags |= ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA;
1537        }
1538
1539        if (sa.getBoolean(
1540                com.android.internal.R.styleable.AndroidManifestApplication_testOnly,
1541                false)) {
1542            ai.flags |= ApplicationInfo.FLAG_TEST_ONLY;
1543        }
1544
1545        if (sa.getBoolean(
1546                com.android.internal.R.styleable.AndroidManifestApplication_neverEncrypt,
1547                false)) {
1548            ai.flags |= ApplicationInfo.FLAG_NEVER_ENCRYPT;
1549        }
1550
1551        String str;
1552        str = sa.getNonConfigurationString(
1553                com.android.internal.R.styleable.AndroidManifestApplication_permission, 0);
1554        ai.permission = (str != null && str.length() > 0) ? str.intern() : null;
1555
1556        str = sa.getNonConfigurationString(
1557                com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity, 0);
1558        ai.taskAffinity = buildTaskAffinityName(ai.packageName, ai.packageName,
1559                str, outError);
1560
1561        if (outError[0] == null) {
1562            ai.processName = buildProcessName(ai.packageName, null, sa.getNonConfigurationString(
1563                    com.android.internal.R.styleable.AndroidManifestApplication_process, 0),
1564                    flags, mSeparateProcesses, outError);
1565
1566            ai.enabled = sa.getBoolean(
1567                    com.android.internal.R.styleable.AndroidManifestApplication_enabled, true);
1568        }
1569
1570        sa.recycle();
1571
1572        if (outError[0] != null) {
1573            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1574            return false;
1575        }
1576
1577        final int innerDepth = parser.getDepth();
1578
1579        int type;
1580        while ((type=parser.next()) != parser.END_DOCUMENT
1581               && (type != parser.END_TAG || parser.getDepth() > innerDepth)) {
1582            if (type == parser.END_TAG || type == parser.TEXT) {
1583                continue;
1584            }
1585
1586            String tagName = parser.getName();
1587            if (tagName.equals("activity")) {
1588                Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false);
1589                if (a == null) {
1590                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1591                    return false;
1592                }
1593
1594                owner.activities.add(a);
1595
1596            } else if (tagName.equals("receiver")) {
1597                Activity a = parseActivity(owner, res, parser, attrs, flags, outError, true);
1598                if (a == null) {
1599                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1600                    return false;
1601                }
1602
1603                owner.receivers.add(a);
1604
1605            } else if (tagName.equals("service")) {
1606                Service s = parseService(owner, res, parser, attrs, flags, outError);
1607                if (s == null) {
1608                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1609                    return false;
1610                }
1611
1612                owner.services.add(s);
1613
1614            } else if (tagName.equals("provider")) {
1615                Provider p = parseProvider(owner, res, parser, attrs, flags, outError);
1616                if (p == null) {
1617                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1618                    return false;
1619                }
1620
1621                owner.providers.add(p);
1622
1623            } else if (tagName.equals("activity-alias")) {
1624                Activity a = parseActivityAlias(owner, res, parser, attrs, flags, outError);
1625                if (a == null) {
1626                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1627                    return false;
1628                }
1629
1630                owner.activities.add(a);
1631
1632            } else if (parser.getName().equals("meta-data")) {
1633                // note: application meta-data is stored off to the side, so it can
1634                // remain null in the primary copy (we like to avoid extra copies because
1635                // it can be large)
1636                if ((owner.mAppMetaData = parseMetaData(res, parser, attrs, owner.mAppMetaData,
1637                        outError)) == null) {
1638                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1639                    return false;
1640                }
1641
1642            } else if (tagName.equals("uses-library")) {
1643                sa = res.obtainAttributes(attrs,
1644                        com.android.internal.R.styleable.AndroidManifestUsesLibrary);
1645
1646                // Note: don't allow this value to be a reference to a resource
1647                // that may change.
1648                String lname = sa.getNonResourceString(
1649                        com.android.internal.R.styleable.AndroidManifestUsesLibrary_name);
1650                boolean req = sa.getBoolean(
1651                        com.android.internal.R.styleable.AndroidManifestUsesLibrary_required,
1652                        true);
1653
1654                sa.recycle();
1655
1656                if (lname != null) {
1657                    if (req) {
1658                        if (owner.usesLibraries == null) {
1659                            owner.usesLibraries = new ArrayList<String>();
1660                        }
1661                        if (!owner.usesLibraries.contains(lname)) {
1662                            owner.usesLibraries.add(lname.intern());
1663                        }
1664                    } else {
1665                        if (owner.usesOptionalLibraries == null) {
1666                            owner.usesOptionalLibraries = new ArrayList<String>();
1667                        }
1668                        if (!owner.usesOptionalLibraries.contains(lname)) {
1669                            owner.usesOptionalLibraries.add(lname.intern());
1670                        }
1671                    }
1672                }
1673
1674                XmlUtils.skipCurrentTag(parser);
1675
1676            } else {
1677                if (!RIGID_PARSER) {
1678                    Log.w(TAG, "Unknown element under <application>: " + tagName
1679                            + " at " + mArchiveSourcePath + " "
1680                            + parser.getPositionDescription());
1681                    XmlUtils.skipCurrentTag(parser);
1682                    continue;
1683                } else {
1684                    outError[0] = "Bad element under <application>: " + tagName;
1685                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1686                    return false;
1687                }
1688            }
1689        }
1690
1691        return true;
1692    }
1693
1694    private boolean parsePackageItemInfo(Package owner, PackageItemInfo outInfo,
1695            String[] outError, String tag, TypedArray sa,
1696            int nameRes, int labelRes, int iconRes) {
1697        String name = sa.getNonConfigurationString(nameRes, 0);
1698        if (name == null) {
1699            outError[0] = tag + " does not specify android:name";
1700            return false;
1701        }
1702
1703        outInfo.name
1704            = buildClassName(owner.applicationInfo.packageName, name, outError);
1705        if (outInfo.name == null) {
1706            return false;
1707        }
1708
1709        int iconVal = sa.getResourceId(iconRes, 0);
1710        if (iconVal != 0) {
1711            outInfo.icon = iconVal;
1712            outInfo.nonLocalizedLabel = null;
1713        }
1714
1715        TypedValue v = sa.peekValue(labelRes);
1716        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
1717            outInfo.nonLocalizedLabel = v.coerceToString();
1718        }
1719
1720        outInfo.packageName = owner.packageName;
1721
1722        return true;
1723    }
1724
1725    private Activity parseActivity(Package owner, Resources res,
1726            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError,
1727            boolean receiver) throws XmlPullParserException, IOException {
1728        TypedArray sa = res.obtainAttributes(attrs,
1729                com.android.internal.R.styleable.AndroidManifestActivity);
1730
1731        if (mParseActivityArgs == null) {
1732            mParseActivityArgs = new ParseComponentArgs(owner, outError,
1733                    com.android.internal.R.styleable.AndroidManifestActivity_name,
1734                    com.android.internal.R.styleable.AndroidManifestActivity_label,
1735                    com.android.internal.R.styleable.AndroidManifestActivity_icon,
1736                    mSeparateProcesses,
1737                    com.android.internal.R.styleable.AndroidManifestActivity_process,
1738                    com.android.internal.R.styleable.AndroidManifestActivity_description,
1739                    com.android.internal.R.styleable.AndroidManifestActivity_enabled);
1740        }
1741
1742        mParseActivityArgs.tag = receiver ? "<receiver>" : "<activity>";
1743        mParseActivityArgs.sa = sa;
1744        mParseActivityArgs.flags = flags;
1745
1746        Activity a = new Activity(mParseActivityArgs, new ActivityInfo());
1747        if (outError[0] != null) {
1748            sa.recycle();
1749            return null;
1750        }
1751
1752        final boolean setExported = sa.hasValue(
1753                com.android.internal.R.styleable.AndroidManifestActivity_exported);
1754        if (setExported) {
1755            a.info.exported = sa.getBoolean(
1756                    com.android.internal.R.styleable.AndroidManifestActivity_exported, false);
1757        }
1758
1759        a.info.theme = sa.getResourceId(
1760                com.android.internal.R.styleable.AndroidManifestActivity_theme, 0);
1761
1762        String str;
1763        str = sa.getNonConfigurationString(
1764                com.android.internal.R.styleable.AndroidManifestActivity_permission, 0);
1765        if (str == null) {
1766            a.info.permission = owner.applicationInfo.permission;
1767        } else {
1768            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
1769        }
1770
1771        str = sa.getNonConfigurationString(
1772                com.android.internal.R.styleable.AndroidManifestActivity_taskAffinity, 0);
1773        a.info.taskAffinity = buildTaskAffinityName(owner.applicationInfo.packageName,
1774                owner.applicationInfo.taskAffinity, str, outError);
1775
1776        a.info.flags = 0;
1777        if (sa.getBoolean(
1778                com.android.internal.R.styleable.AndroidManifestActivity_multiprocess,
1779                false)) {
1780            a.info.flags |= ActivityInfo.FLAG_MULTIPROCESS;
1781        }
1782
1783        if (sa.getBoolean(
1784                com.android.internal.R.styleable.AndroidManifestActivity_finishOnTaskLaunch,
1785                false)) {
1786            a.info.flags |= ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH;
1787        }
1788
1789        if (sa.getBoolean(
1790                com.android.internal.R.styleable.AndroidManifestActivity_clearTaskOnLaunch,
1791                false)) {
1792            a.info.flags |= ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH;
1793        }
1794
1795        if (sa.getBoolean(
1796                com.android.internal.R.styleable.AndroidManifestActivity_noHistory,
1797                false)) {
1798            a.info.flags |= ActivityInfo.FLAG_NO_HISTORY;
1799        }
1800
1801        if (sa.getBoolean(
1802                com.android.internal.R.styleable.AndroidManifestActivity_alwaysRetainTaskState,
1803                false)) {
1804            a.info.flags |= ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE;
1805        }
1806
1807        if (sa.getBoolean(
1808                com.android.internal.R.styleable.AndroidManifestActivity_stateNotNeeded,
1809                false)) {
1810            a.info.flags |= ActivityInfo.FLAG_STATE_NOT_NEEDED;
1811        }
1812
1813        if (sa.getBoolean(
1814                com.android.internal.R.styleable.AndroidManifestActivity_excludeFromRecents,
1815                false)) {
1816            a.info.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1817        }
1818
1819        if (sa.getBoolean(
1820                com.android.internal.R.styleable.AndroidManifestActivity_allowTaskReparenting,
1821                (owner.applicationInfo.flags&ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING) != 0)) {
1822            a.info.flags |= ActivityInfo.FLAG_ALLOW_TASK_REPARENTING;
1823        }
1824
1825        if (sa.getBoolean(
1826                com.android.internal.R.styleable.AndroidManifestActivity_finishOnCloseSystemDialogs,
1827                false)) {
1828            a.info.flags |= ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
1829        }
1830
1831        if (!receiver) {
1832            a.info.launchMode = sa.getInt(
1833                    com.android.internal.R.styleable.AndroidManifestActivity_launchMode,
1834                    ActivityInfo.LAUNCH_MULTIPLE);
1835            a.info.screenOrientation = sa.getInt(
1836                    com.android.internal.R.styleable.AndroidManifestActivity_screenOrientation,
1837                    ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1838            a.info.configChanges = sa.getInt(
1839                    com.android.internal.R.styleable.AndroidManifestActivity_configChanges,
1840                    0);
1841            a.info.softInputMode = sa.getInt(
1842                    com.android.internal.R.styleable.AndroidManifestActivity_windowSoftInputMode,
1843                    0);
1844        } else {
1845            a.info.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1846            a.info.configChanges = 0;
1847        }
1848
1849        sa.recycle();
1850
1851        if (outError[0] != null) {
1852            return null;
1853        }
1854
1855        int outerDepth = parser.getDepth();
1856        int type;
1857        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1858               && (type != XmlPullParser.END_TAG
1859                       || parser.getDepth() > outerDepth)) {
1860            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1861                continue;
1862            }
1863
1864            if (parser.getName().equals("intent-filter")) {
1865                ActivityIntentInfo intent = new ActivityIntentInfo(a);
1866                if (!parseIntent(res, parser, attrs, flags, intent, outError, !receiver)) {
1867                    return null;
1868                }
1869                if (intent.countActions() == 0) {
1870                    Log.w(TAG, "No actions in intent filter at "
1871                            + mArchiveSourcePath + " "
1872                            + parser.getPositionDescription());
1873                } else {
1874                    a.intents.add(intent);
1875                }
1876            } else if (parser.getName().equals("meta-data")) {
1877                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
1878                        outError)) == null) {
1879                    return null;
1880                }
1881            } else {
1882                if (!RIGID_PARSER) {
1883                    Log.w(TAG, "Problem in package " + mArchiveSourcePath + ":");
1884                    if (receiver) {
1885                        Log.w(TAG, "Unknown element under <receiver>: " + parser.getName()
1886                                + " at " + mArchiveSourcePath + " "
1887                                + parser.getPositionDescription());
1888                    } else {
1889                        Log.w(TAG, "Unknown element under <activity>: " + parser.getName()
1890                                + " at " + mArchiveSourcePath + " "
1891                                + parser.getPositionDescription());
1892                    }
1893                    XmlUtils.skipCurrentTag(parser);
1894                    continue;
1895                }
1896                if (receiver) {
1897                    outError[0] = "Bad element under <receiver>: " + parser.getName();
1898                } else {
1899                    outError[0] = "Bad element under <activity>: " + parser.getName();
1900                }
1901                return null;
1902            }
1903        }
1904
1905        if (!setExported) {
1906            a.info.exported = a.intents.size() > 0;
1907        }
1908
1909        return a;
1910    }
1911
1912    private Activity parseActivityAlias(Package owner, Resources res,
1913            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
1914            throws XmlPullParserException, IOException {
1915        TypedArray sa = res.obtainAttributes(attrs,
1916                com.android.internal.R.styleable.AndroidManifestActivityAlias);
1917
1918        String targetActivity = sa.getNonConfigurationString(
1919                com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity, 0);
1920        if (targetActivity == null) {
1921            outError[0] = "<activity-alias> does not specify android:targetActivity";
1922            sa.recycle();
1923            return null;
1924        }
1925
1926        targetActivity = buildClassName(owner.applicationInfo.packageName,
1927                targetActivity, outError);
1928        if (targetActivity == null) {
1929            sa.recycle();
1930            return null;
1931        }
1932
1933        if (mParseActivityAliasArgs == null) {
1934            mParseActivityAliasArgs = new ParseComponentArgs(owner, outError,
1935                    com.android.internal.R.styleable.AndroidManifestActivityAlias_name,
1936                    com.android.internal.R.styleable.AndroidManifestActivityAlias_label,
1937                    com.android.internal.R.styleable.AndroidManifestActivityAlias_icon,
1938                    mSeparateProcesses,
1939                    0,
1940                    com.android.internal.R.styleable.AndroidManifestActivityAlias_description,
1941                    com.android.internal.R.styleable.AndroidManifestActivityAlias_enabled);
1942            mParseActivityAliasArgs.tag = "<activity-alias>";
1943        }
1944
1945        mParseActivityAliasArgs.sa = sa;
1946        mParseActivityAliasArgs.flags = flags;
1947
1948        Activity target = null;
1949
1950        final int NA = owner.activities.size();
1951        for (int i=0; i<NA; i++) {
1952            Activity t = owner.activities.get(i);
1953            if (targetActivity.equals(t.info.name)) {
1954                target = t;
1955                break;
1956            }
1957        }
1958
1959        if (target == null) {
1960            outError[0] = "<activity-alias> target activity " + targetActivity
1961                    + " not found in manifest";
1962            sa.recycle();
1963            return null;
1964        }
1965
1966        ActivityInfo info = new ActivityInfo();
1967        info.targetActivity = targetActivity;
1968        info.configChanges = target.info.configChanges;
1969        info.flags = target.info.flags;
1970        info.icon = target.info.icon;
1971        info.labelRes = target.info.labelRes;
1972        info.nonLocalizedLabel = target.info.nonLocalizedLabel;
1973        info.launchMode = target.info.launchMode;
1974        info.processName = target.info.processName;
1975        if (info.descriptionRes == 0) {
1976            info.descriptionRes = target.info.descriptionRes;
1977        }
1978        info.screenOrientation = target.info.screenOrientation;
1979        info.taskAffinity = target.info.taskAffinity;
1980        info.theme = target.info.theme;
1981
1982        Activity a = new Activity(mParseActivityAliasArgs, info);
1983        if (outError[0] != null) {
1984            sa.recycle();
1985            return null;
1986        }
1987
1988        final boolean setExported = sa.hasValue(
1989                com.android.internal.R.styleable.AndroidManifestActivityAlias_exported);
1990        if (setExported) {
1991            a.info.exported = sa.getBoolean(
1992                    com.android.internal.R.styleable.AndroidManifestActivityAlias_exported, false);
1993        }
1994
1995        String str;
1996        str = sa.getNonConfigurationString(
1997                com.android.internal.R.styleable.AndroidManifestActivityAlias_permission, 0);
1998        if (str != null) {
1999            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
2000        }
2001
2002        sa.recycle();
2003
2004        if (outError[0] != null) {
2005            return null;
2006        }
2007
2008        int outerDepth = parser.getDepth();
2009        int type;
2010        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2011               && (type != XmlPullParser.END_TAG
2012                       || parser.getDepth() > outerDepth)) {
2013            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2014                continue;
2015            }
2016
2017            if (parser.getName().equals("intent-filter")) {
2018                ActivityIntentInfo intent = new ActivityIntentInfo(a);
2019                if (!parseIntent(res, parser, attrs, flags, intent, outError, true)) {
2020                    return null;
2021                }
2022                if (intent.countActions() == 0) {
2023                    Log.w(TAG, "No actions in intent filter at "
2024                            + mArchiveSourcePath + " "
2025                            + parser.getPositionDescription());
2026                } else {
2027                    a.intents.add(intent);
2028                }
2029            } else if (parser.getName().equals("meta-data")) {
2030                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
2031                        outError)) == null) {
2032                    return null;
2033                }
2034            } else {
2035                if (!RIGID_PARSER) {
2036                    Log.w(TAG, "Unknown element under <activity-alias>: " + parser.getName()
2037                            + " at " + mArchiveSourcePath + " "
2038                            + parser.getPositionDescription());
2039                    XmlUtils.skipCurrentTag(parser);
2040                    continue;
2041                }
2042                outError[0] = "Bad element under <activity-alias>: " + parser.getName();
2043                return null;
2044            }
2045        }
2046
2047        if (!setExported) {
2048            a.info.exported = a.intents.size() > 0;
2049        }
2050
2051        return a;
2052    }
2053
2054    private Provider parseProvider(Package owner, Resources res,
2055            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2056            throws XmlPullParserException, IOException {
2057        TypedArray sa = res.obtainAttributes(attrs,
2058                com.android.internal.R.styleable.AndroidManifestProvider);
2059
2060        if (mParseProviderArgs == null) {
2061            mParseProviderArgs = new ParseComponentArgs(owner, outError,
2062                    com.android.internal.R.styleable.AndroidManifestProvider_name,
2063                    com.android.internal.R.styleable.AndroidManifestProvider_label,
2064                    com.android.internal.R.styleable.AndroidManifestProvider_icon,
2065                    mSeparateProcesses,
2066                    com.android.internal.R.styleable.AndroidManifestProvider_process,
2067                    com.android.internal.R.styleable.AndroidManifestProvider_description,
2068                    com.android.internal.R.styleable.AndroidManifestProvider_enabled);
2069            mParseProviderArgs.tag = "<provider>";
2070        }
2071
2072        mParseProviderArgs.sa = sa;
2073        mParseProviderArgs.flags = flags;
2074
2075        Provider p = new Provider(mParseProviderArgs, new ProviderInfo());
2076        if (outError[0] != null) {
2077            sa.recycle();
2078            return null;
2079        }
2080
2081        p.info.exported = sa.getBoolean(
2082                com.android.internal.R.styleable.AndroidManifestProvider_exported, true);
2083
2084        String cpname = sa.getNonConfigurationString(
2085                com.android.internal.R.styleable.AndroidManifestProvider_authorities, 0);
2086
2087        p.info.isSyncable = sa.getBoolean(
2088                com.android.internal.R.styleable.AndroidManifestProvider_syncable,
2089                false);
2090
2091        String permission = sa.getNonConfigurationString(
2092                com.android.internal.R.styleable.AndroidManifestProvider_permission, 0);
2093        String str = sa.getNonConfigurationString(
2094                com.android.internal.R.styleable.AndroidManifestProvider_readPermission, 0);
2095        if (str == null) {
2096            str = permission;
2097        }
2098        if (str == null) {
2099            p.info.readPermission = owner.applicationInfo.permission;
2100        } else {
2101            p.info.readPermission =
2102                str.length() > 0 ? str.toString().intern() : null;
2103        }
2104        str = sa.getNonConfigurationString(
2105                com.android.internal.R.styleable.AndroidManifestProvider_writePermission, 0);
2106        if (str == null) {
2107            str = permission;
2108        }
2109        if (str == null) {
2110            p.info.writePermission = owner.applicationInfo.permission;
2111        } else {
2112            p.info.writePermission =
2113                str.length() > 0 ? str.toString().intern() : null;
2114        }
2115
2116        p.info.grantUriPermissions = sa.getBoolean(
2117                com.android.internal.R.styleable.AndroidManifestProvider_grantUriPermissions,
2118                false);
2119
2120        p.info.multiprocess = sa.getBoolean(
2121                com.android.internal.R.styleable.AndroidManifestProvider_multiprocess,
2122                false);
2123
2124        p.info.initOrder = sa.getInt(
2125                com.android.internal.R.styleable.AndroidManifestProvider_initOrder,
2126                0);
2127
2128        sa.recycle();
2129
2130        if (cpname == null) {
2131            outError[0] = "<provider> does not incude authorities attribute";
2132            return null;
2133        }
2134        p.info.authority = cpname.intern();
2135
2136        if (!parseProviderTags(res, parser, attrs, p, outError)) {
2137            return null;
2138        }
2139
2140        return p;
2141    }
2142
2143    private boolean parseProviderTags(Resources res,
2144            XmlPullParser parser, AttributeSet attrs,
2145            Provider outInfo, String[] outError)
2146            throws XmlPullParserException, IOException {
2147        int outerDepth = parser.getDepth();
2148        int type;
2149        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2150               && (type != XmlPullParser.END_TAG
2151                       || parser.getDepth() > outerDepth)) {
2152            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2153                continue;
2154            }
2155
2156            if (parser.getName().equals("meta-data")) {
2157                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2158                        outInfo.metaData, outError)) == null) {
2159                    return false;
2160                }
2161
2162            } else if (parser.getName().equals("grant-uri-permission")) {
2163                TypedArray sa = res.obtainAttributes(attrs,
2164                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission);
2165
2166                PatternMatcher pa = null;
2167
2168                String str = sa.getNonConfigurationString(
2169                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path, 0);
2170                if (str != null) {
2171                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_LITERAL);
2172                }
2173
2174                str = sa.getNonConfigurationString(
2175                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix, 0);
2176                if (str != null) {
2177                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_PREFIX);
2178                }
2179
2180                str = sa.getNonConfigurationString(
2181                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern, 0);
2182                if (str != null) {
2183                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2184                }
2185
2186                sa.recycle();
2187
2188                if (pa != null) {
2189                    if (outInfo.info.uriPermissionPatterns == null) {
2190                        outInfo.info.uriPermissionPatterns = new PatternMatcher[1];
2191                        outInfo.info.uriPermissionPatterns[0] = pa;
2192                    } else {
2193                        final int N = outInfo.info.uriPermissionPatterns.length;
2194                        PatternMatcher[] newp = new PatternMatcher[N+1];
2195                        System.arraycopy(outInfo.info.uriPermissionPatterns, 0, newp, 0, N);
2196                        newp[N] = pa;
2197                        outInfo.info.uriPermissionPatterns = newp;
2198                    }
2199                    outInfo.info.grantUriPermissions = true;
2200                } else {
2201                    if (!RIGID_PARSER) {
2202                        Log.w(TAG, "Unknown element under <path-permission>: "
2203                                + parser.getName() + " at " + mArchiveSourcePath + " "
2204                                + parser.getPositionDescription());
2205                        XmlUtils.skipCurrentTag(parser);
2206                        continue;
2207                    }
2208                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2209                    return false;
2210                }
2211                XmlUtils.skipCurrentTag(parser);
2212
2213            } else if (parser.getName().equals("path-permission")) {
2214                TypedArray sa = res.obtainAttributes(attrs,
2215                        com.android.internal.R.styleable.AndroidManifestPathPermission);
2216
2217                PathPermission pa = null;
2218
2219                String permission = sa.getNonConfigurationString(
2220                        com.android.internal.R.styleable.AndroidManifestPathPermission_permission, 0);
2221                String readPermission = sa.getNonConfigurationString(
2222                        com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission, 0);
2223                if (readPermission == null) {
2224                    readPermission = permission;
2225                }
2226                String writePermission = sa.getNonConfigurationString(
2227                        com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission, 0);
2228                if (writePermission == null) {
2229                    writePermission = permission;
2230                }
2231
2232                boolean havePerm = false;
2233                if (readPermission != null) {
2234                    readPermission = readPermission.intern();
2235                    havePerm = true;
2236                }
2237                if (writePermission != null) {
2238                    writePermission = writePermission.intern();
2239                    havePerm = true;
2240                }
2241
2242                if (!havePerm) {
2243                    if (!RIGID_PARSER) {
2244                        Log.w(TAG, "No readPermission or writePermssion for <path-permission>: "
2245                                + parser.getName() + " at " + mArchiveSourcePath + " "
2246                                + parser.getPositionDescription());
2247                        XmlUtils.skipCurrentTag(parser);
2248                        continue;
2249                    }
2250                    outError[0] = "No readPermission or writePermssion for <path-permission>";
2251                    return false;
2252                }
2253
2254                String path = sa.getNonConfigurationString(
2255                        com.android.internal.R.styleable.AndroidManifestPathPermission_path, 0);
2256                if (path != null) {
2257                    pa = new PathPermission(path,
2258                            PatternMatcher.PATTERN_LITERAL, readPermission, writePermission);
2259                }
2260
2261                path = sa.getNonConfigurationString(
2262                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix, 0);
2263                if (path != null) {
2264                    pa = new PathPermission(path,
2265                            PatternMatcher.PATTERN_PREFIX, readPermission, writePermission);
2266                }
2267
2268                path = sa.getNonConfigurationString(
2269                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern, 0);
2270                if (path != null) {
2271                    pa = new PathPermission(path,
2272                            PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
2273                }
2274
2275                sa.recycle();
2276
2277                if (pa != null) {
2278                    if (outInfo.info.pathPermissions == null) {
2279                        outInfo.info.pathPermissions = new PathPermission[1];
2280                        outInfo.info.pathPermissions[0] = pa;
2281                    } else {
2282                        final int N = outInfo.info.pathPermissions.length;
2283                        PathPermission[] newp = new PathPermission[N+1];
2284                        System.arraycopy(outInfo.info.pathPermissions, 0, newp, 0, N);
2285                        newp[N] = pa;
2286                        outInfo.info.pathPermissions = newp;
2287                    }
2288                } else {
2289                    if (!RIGID_PARSER) {
2290                        Log.w(TAG, "No path, pathPrefix, or pathPattern for <path-permission>: "
2291                                + parser.getName() + " at " + mArchiveSourcePath + " "
2292                                + parser.getPositionDescription());
2293                        XmlUtils.skipCurrentTag(parser);
2294                        continue;
2295                    }
2296                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2297                    return false;
2298                }
2299                XmlUtils.skipCurrentTag(parser);
2300
2301            } else {
2302                if (!RIGID_PARSER) {
2303                    Log.w(TAG, "Unknown element under <provider>: "
2304                            + parser.getName() + " at " + mArchiveSourcePath + " "
2305                            + parser.getPositionDescription());
2306                    XmlUtils.skipCurrentTag(parser);
2307                    continue;
2308                }
2309                outError[0] = "Bad element under <provider>: "
2310                    + parser.getName();
2311                return false;
2312            }
2313        }
2314        return true;
2315    }
2316
2317    private Service parseService(Package owner, Resources res,
2318            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2319            throws XmlPullParserException, IOException {
2320        TypedArray sa = res.obtainAttributes(attrs,
2321                com.android.internal.R.styleable.AndroidManifestService);
2322
2323        if (mParseServiceArgs == null) {
2324            mParseServiceArgs = new ParseComponentArgs(owner, outError,
2325                    com.android.internal.R.styleable.AndroidManifestService_name,
2326                    com.android.internal.R.styleable.AndroidManifestService_label,
2327                    com.android.internal.R.styleable.AndroidManifestService_icon,
2328                    mSeparateProcesses,
2329                    com.android.internal.R.styleable.AndroidManifestService_process,
2330                    com.android.internal.R.styleable.AndroidManifestService_description,
2331                    com.android.internal.R.styleable.AndroidManifestService_enabled);
2332            mParseServiceArgs.tag = "<service>";
2333        }
2334
2335        mParseServiceArgs.sa = sa;
2336        mParseServiceArgs.flags = flags;
2337
2338        Service s = new Service(mParseServiceArgs, new ServiceInfo());
2339        if (outError[0] != null) {
2340            sa.recycle();
2341            return null;
2342        }
2343
2344        final boolean setExported = sa.hasValue(
2345                com.android.internal.R.styleable.AndroidManifestService_exported);
2346        if (setExported) {
2347            s.info.exported = sa.getBoolean(
2348                    com.android.internal.R.styleable.AndroidManifestService_exported, false);
2349        }
2350
2351        String str = sa.getNonConfigurationString(
2352                com.android.internal.R.styleable.AndroidManifestService_permission, 0);
2353        if (str == null) {
2354            s.info.permission = owner.applicationInfo.permission;
2355        } else {
2356            s.info.permission = str.length() > 0 ? str.toString().intern() : null;
2357        }
2358
2359        sa.recycle();
2360
2361        int outerDepth = parser.getDepth();
2362        int type;
2363        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2364               && (type != XmlPullParser.END_TAG
2365                       || parser.getDepth() > outerDepth)) {
2366            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2367                continue;
2368            }
2369
2370            if (parser.getName().equals("intent-filter")) {
2371                ServiceIntentInfo intent = new ServiceIntentInfo(s);
2372                if (!parseIntent(res, parser, attrs, flags, intent, outError, false)) {
2373                    return null;
2374                }
2375
2376                s.intents.add(intent);
2377            } else if (parser.getName().equals("meta-data")) {
2378                if ((s.metaData=parseMetaData(res, parser, attrs, s.metaData,
2379                        outError)) == null) {
2380                    return null;
2381                }
2382            } else {
2383                if (!RIGID_PARSER) {
2384                    Log.w(TAG, "Unknown element under <service>: "
2385                            + parser.getName() + " at " + mArchiveSourcePath + " "
2386                            + parser.getPositionDescription());
2387                    XmlUtils.skipCurrentTag(parser);
2388                    continue;
2389                }
2390                outError[0] = "Bad element under <service>: "
2391                    + parser.getName();
2392                return null;
2393            }
2394        }
2395
2396        if (!setExported) {
2397            s.info.exported = s.intents.size() > 0;
2398        }
2399
2400        return s;
2401    }
2402
2403    private boolean parseAllMetaData(Resources res,
2404            XmlPullParser parser, AttributeSet attrs, String tag,
2405            Component outInfo, String[] outError)
2406            throws XmlPullParserException, IOException {
2407        int outerDepth = parser.getDepth();
2408        int type;
2409        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2410               && (type != XmlPullParser.END_TAG
2411                       || parser.getDepth() > outerDepth)) {
2412            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2413                continue;
2414            }
2415
2416            if (parser.getName().equals("meta-data")) {
2417                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2418                        outInfo.metaData, outError)) == null) {
2419                    return false;
2420                }
2421            } else {
2422                if (!RIGID_PARSER) {
2423                    Log.w(TAG, "Unknown element under " + tag + ": "
2424                            + parser.getName() + " at " + mArchiveSourcePath + " "
2425                            + parser.getPositionDescription());
2426                    XmlUtils.skipCurrentTag(parser);
2427                    continue;
2428                }
2429                outError[0] = "Bad element under " + tag + ": "
2430                    + parser.getName();
2431                return false;
2432            }
2433        }
2434        return true;
2435    }
2436
2437    private Bundle parseMetaData(Resources res,
2438            XmlPullParser parser, AttributeSet attrs,
2439            Bundle data, String[] outError)
2440            throws XmlPullParserException, IOException {
2441
2442        TypedArray sa = res.obtainAttributes(attrs,
2443                com.android.internal.R.styleable.AndroidManifestMetaData);
2444
2445        if (data == null) {
2446            data = new Bundle();
2447        }
2448
2449        String name = sa.getNonConfigurationString(
2450                com.android.internal.R.styleable.AndroidManifestMetaData_name, 0);
2451        if (name == null) {
2452            outError[0] = "<meta-data> requires an android:name attribute";
2453            sa.recycle();
2454            return null;
2455        }
2456
2457        name = name.intern();
2458
2459        TypedValue v = sa.peekValue(
2460                com.android.internal.R.styleable.AndroidManifestMetaData_resource);
2461        if (v != null && v.resourceId != 0) {
2462            //Log.i(TAG, "Meta data ref " + name + ": " + v);
2463            data.putInt(name, v.resourceId);
2464        } else {
2465            v = sa.peekValue(
2466                    com.android.internal.R.styleable.AndroidManifestMetaData_value);
2467            //Log.i(TAG, "Meta data " + name + ": " + v);
2468            if (v != null) {
2469                if (v.type == TypedValue.TYPE_STRING) {
2470                    CharSequence cs = v.coerceToString();
2471                    data.putString(name, cs != null ? cs.toString().intern() : null);
2472                } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2473                    data.putBoolean(name, v.data != 0);
2474                } else if (v.type >= TypedValue.TYPE_FIRST_INT
2475                        && v.type <= TypedValue.TYPE_LAST_INT) {
2476                    data.putInt(name, v.data);
2477                } else if (v.type == TypedValue.TYPE_FLOAT) {
2478                    data.putFloat(name, v.getFloat());
2479                } else {
2480                    if (!RIGID_PARSER) {
2481                        Log.w(TAG, "<meta-data> only supports string, integer, float, color, boolean, and resource reference types: "
2482                                + parser.getName() + " at " + mArchiveSourcePath + " "
2483                                + parser.getPositionDescription());
2484                    } else {
2485                        outError[0] = "<meta-data> only supports string, integer, float, color, boolean, and resource reference types";
2486                        data = null;
2487                    }
2488                }
2489            } else {
2490                outError[0] = "<meta-data> requires an android:value or android:resource attribute";
2491                data = null;
2492            }
2493        }
2494
2495        sa.recycle();
2496
2497        XmlUtils.skipCurrentTag(parser);
2498
2499        return data;
2500    }
2501
2502    private static final String ANDROID_RESOURCES
2503            = "http://schemas.android.com/apk/res/android";
2504
2505    private boolean parseIntent(Resources res,
2506            XmlPullParser parser, AttributeSet attrs, int flags,
2507            IntentInfo outInfo, String[] outError, boolean isActivity)
2508            throws XmlPullParserException, IOException {
2509
2510        TypedArray sa = res.obtainAttributes(attrs,
2511                com.android.internal.R.styleable.AndroidManifestIntentFilter);
2512
2513        int priority = sa.getInt(
2514                com.android.internal.R.styleable.AndroidManifestIntentFilter_priority, 0);
2515        if (priority > 0 && isActivity && (flags&PARSE_IS_SYSTEM) == 0) {
2516            Log.w(TAG, "Activity with priority > 0, forcing to 0 at "
2517                    + mArchiveSourcePath + " "
2518                    + parser.getPositionDescription());
2519            priority = 0;
2520        }
2521        outInfo.setPriority(priority);
2522
2523        TypedValue v = sa.peekValue(
2524                com.android.internal.R.styleable.AndroidManifestIntentFilter_label);
2525        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2526            outInfo.nonLocalizedLabel = v.coerceToString();
2527        }
2528
2529        outInfo.icon = sa.getResourceId(
2530                com.android.internal.R.styleable.AndroidManifestIntentFilter_icon, 0);
2531
2532        sa.recycle();
2533
2534        int outerDepth = parser.getDepth();
2535        int type;
2536        while ((type=parser.next()) != parser.END_DOCUMENT
2537               && (type != parser.END_TAG || parser.getDepth() > outerDepth)) {
2538            if (type == parser.END_TAG || type == parser.TEXT) {
2539                continue;
2540            }
2541
2542            String nodeName = parser.getName();
2543            if (nodeName.equals("action")) {
2544                String value = attrs.getAttributeValue(
2545                        ANDROID_RESOURCES, "name");
2546                if (value == null || value == "") {
2547                    outError[0] = "No value supplied for <android:name>";
2548                    return false;
2549                }
2550                XmlUtils.skipCurrentTag(parser);
2551
2552                outInfo.addAction(value);
2553            } else if (nodeName.equals("category")) {
2554                String value = attrs.getAttributeValue(
2555                        ANDROID_RESOURCES, "name");
2556                if (value == null || value == "") {
2557                    outError[0] = "No value supplied for <android:name>";
2558                    return false;
2559                }
2560                XmlUtils.skipCurrentTag(parser);
2561
2562                outInfo.addCategory(value);
2563
2564            } else if (nodeName.equals("data")) {
2565                sa = res.obtainAttributes(attrs,
2566                        com.android.internal.R.styleable.AndroidManifestData);
2567
2568                String str = sa.getNonConfigurationString(
2569                        com.android.internal.R.styleable.AndroidManifestData_mimeType, 0);
2570                if (str != null) {
2571                    try {
2572                        outInfo.addDataType(str);
2573                    } catch (IntentFilter.MalformedMimeTypeException e) {
2574                        outError[0] = e.toString();
2575                        sa.recycle();
2576                        return false;
2577                    }
2578                }
2579
2580                str = sa.getNonConfigurationString(
2581                        com.android.internal.R.styleable.AndroidManifestData_scheme, 0);
2582                if (str != null) {
2583                    outInfo.addDataScheme(str);
2584                }
2585
2586                String host = sa.getNonConfigurationString(
2587                        com.android.internal.R.styleable.AndroidManifestData_host, 0);
2588                String port = sa.getNonConfigurationString(
2589                        com.android.internal.R.styleable.AndroidManifestData_port, 0);
2590                if (host != null) {
2591                    outInfo.addDataAuthority(host, port);
2592                }
2593
2594                str = sa.getNonConfigurationString(
2595                        com.android.internal.R.styleable.AndroidManifestData_path, 0);
2596                if (str != null) {
2597                    outInfo.addDataPath(str, PatternMatcher.PATTERN_LITERAL);
2598                }
2599
2600                str = sa.getNonConfigurationString(
2601                        com.android.internal.R.styleable.AndroidManifestData_pathPrefix, 0);
2602                if (str != null) {
2603                    outInfo.addDataPath(str, PatternMatcher.PATTERN_PREFIX);
2604                }
2605
2606                str = sa.getNonConfigurationString(
2607                        com.android.internal.R.styleable.AndroidManifestData_pathPattern, 0);
2608                if (str != null) {
2609                    outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2610                }
2611
2612                sa.recycle();
2613                XmlUtils.skipCurrentTag(parser);
2614            } else if (!RIGID_PARSER) {
2615                Log.w(TAG, "Unknown element under <intent-filter>: "
2616                        + parser.getName() + " at " + mArchiveSourcePath + " "
2617                        + parser.getPositionDescription());
2618                XmlUtils.skipCurrentTag(parser);
2619            } else {
2620                outError[0] = "Bad element under <intent-filter>: " + parser.getName();
2621                return false;
2622            }
2623        }
2624
2625        outInfo.hasDefault = outInfo.hasCategory(Intent.CATEGORY_DEFAULT);
2626        if (false) {
2627            String cats = "";
2628            Iterator<String> it = outInfo.categoriesIterator();
2629            while (it != null && it.hasNext()) {
2630                cats += " " + it.next();
2631            }
2632            System.out.println("Intent d=" +
2633                    outInfo.hasDefault + ", cat=" + cats);
2634        }
2635
2636        return true;
2637    }
2638
2639    public final static class Package {
2640        public String packageName;
2641
2642        // For now we only support one application per package.
2643        public final ApplicationInfo applicationInfo = new ApplicationInfo();
2644
2645        public final ArrayList<Permission> permissions = new ArrayList<Permission>(0);
2646        public final ArrayList<PermissionGroup> permissionGroups = new ArrayList<PermissionGroup>(0);
2647        public final ArrayList<Activity> activities = new ArrayList<Activity>(0);
2648        public final ArrayList<Activity> receivers = new ArrayList<Activity>(0);
2649        public final ArrayList<Provider> providers = new ArrayList<Provider>(0);
2650        public final ArrayList<Service> services = new ArrayList<Service>(0);
2651        public final ArrayList<Instrumentation> instrumentation = new ArrayList<Instrumentation>(0);
2652
2653        public final ArrayList<String> requestedPermissions = new ArrayList<String>();
2654
2655        public ArrayList<String> protectedBroadcasts;
2656
2657        public ArrayList<String> usesLibraries = null;
2658        public ArrayList<String> usesOptionalLibraries = null;
2659        public String[] usesLibraryFiles = null;
2660
2661        public ArrayList<String> mOriginalPackages = null;
2662        public String mRealPackage = null;
2663        public ArrayList<String> mAdoptPermissions = null;
2664
2665        // We store the application meta-data independently to avoid multiple unwanted references
2666        public Bundle mAppMetaData = null;
2667
2668        // If this is a 3rd party app, this is the path of the zip file.
2669        public String mPath;
2670
2671        // The version code declared for this package.
2672        public int mVersionCode;
2673
2674        // The version name declared for this package.
2675        public String mVersionName;
2676
2677        // The shared user id that this package wants to use.
2678        public String mSharedUserId;
2679
2680        // The shared user label that this package wants to use.
2681        public int mSharedUserLabel;
2682
2683        // Signatures that were read from the package.
2684        public Signature mSignatures[];
2685
2686        // For use by package manager service for quick lookup of
2687        // preferred up order.
2688        public int mPreferredOrder = 0;
2689
2690        // For use by the package manager to keep track of the path to the
2691        // file an app came from.
2692        public String mScanPath;
2693
2694        // For use by package manager to keep track of where it has done dexopt.
2695        public boolean mDidDexOpt;
2696
2697        // Additional data supplied by callers.
2698        public Object mExtras;
2699
2700        /*
2701         *  Applications hardware preferences
2702         */
2703        public final ArrayList<ConfigurationInfo> configPreferences =
2704                new ArrayList<ConfigurationInfo>();
2705
2706        /*
2707         *  Applications requested features
2708         */
2709        public ArrayList<FeatureInfo> reqFeatures = null;
2710
2711        public int installLocation;
2712
2713        public Package(String _name) {
2714            packageName = _name;
2715            applicationInfo.packageName = _name;
2716            applicationInfo.uid = -1;
2717        }
2718
2719        public void setPackageName(String newName) {
2720            packageName = newName;
2721            applicationInfo.packageName = newName;
2722            for (int i=permissions.size()-1; i>=0; i--) {
2723                permissions.get(i).setPackageName(newName);
2724            }
2725            for (int i=permissionGroups.size()-1; i>=0; i--) {
2726                permissionGroups.get(i).setPackageName(newName);
2727            }
2728            for (int i=activities.size()-1; i>=0; i--) {
2729                activities.get(i).setPackageName(newName);
2730            }
2731            for (int i=receivers.size()-1; i>=0; i--) {
2732                receivers.get(i).setPackageName(newName);
2733            }
2734            for (int i=providers.size()-1; i>=0; i--) {
2735                providers.get(i).setPackageName(newName);
2736            }
2737            for (int i=services.size()-1; i>=0; i--) {
2738                services.get(i).setPackageName(newName);
2739            }
2740            for (int i=instrumentation.size()-1; i>=0; i--) {
2741                instrumentation.get(i).setPackageName(newName);
2742            }
2743        }
2744
2745        public String toString() {
2746            return "Package{"
2747                + Integer.toHexString(System.identityHashCode(this))
2748                + " " + packageName + "}";
2749        }
2750    }
2751
2752    public static class Component<II extends IntentInfo> {
2753        public final Package owner;
2754        public final ArrayList<II> intents;
2755        public final String className;
2756        public Bundle metaData;
2757
2758        ComponentName componentName;
2759        String componentShortName;
2760
2761        public Component(Package _owner) {
2762            owner = _owner;
2763            intents = null;
2764            className = null;
2765        }
2766
2767        public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
2768            owner = args.owner;
2769            intents = new ArrayList<II>(0);
2770            String name = args.sa.getNonConfigurationString(args.nameRes, 0);
2771            if (name == null) {
2772                className = null;
2773                args.outError[0] = args.tag + " does not specify android:name";
2774                return;
2775            }
2776
2777            outInfo.name
2778                = buildClassName(owner.applicationInfo.packageName, name, args.outError);
2779            if (outInfo.name == null) {
2780                className = null;
2781                args.outError[0] = args.tag + " does not have valid android:name";
2782                return;
2783            }
2784
2785            className = outInfo.name;
2786
2787            int iconVal = args.sa.getResourceId(args.iconRes, 0);
2788            if (iconVal != 0) {
2789                outInfo.icon = iconVal;
2790                outInfo.nonLocalizedLabel = null;
2791            }
2792
2793            TypedValue v = args.sa.peekValue(args.labelRes);
2794            if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2795                outInfo.nonLocalizedLabel = v.coerceToString();
2796            }
2797
2798            outInfo.packageName = owner.packageName;
2799        }
2800
2801        public Component(final ParseComponentArgs args, final ComponentInfo outInfo) {
2802            this(args, (PackageItemInfo)outInfo);
2803            if (args.outError[0] != null) {
2804                return;
2805            }
2806
2807            if (args.processRes != 0) {
2808                outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
2809                        owner.applicationInfo.processName,
2810                        args.sa.getNonConfigurationString(args.processRes, 0),
2811                        args.flags, args.sepProcesses, args.outError);
2812            }
2813
2814            if (args.descriptionRes != 0) {
2815                outInfo.descriptionRes = args.sa.getResourceId(args.descriptionRes, 0);
2816            }
2817
2818            outInfo.enabled = args.sa.getBoolean(args.enabledRes, true);
2819        }
2820
2821        public Component(Component<II> clone) {
2822            owner = clone.owner;
2823            intents = clone.intents;
2824            className = clone.className;
2825            componentName = clone.componentName;
2826            componentShortName = clone.componentShortName;
2827        }
2828
2829        public ComponentName getComponentName() {
2830            if (componentName != null) {
2831                return componentName;
2832            }
2833            if (className != null) {
2834                componentName = new ComponentName(owner.applicationInfo.packageName,
2835                        className);
2836            }
2837            return componentName;
2838        }
2839
2840        public String getComponentShortName() {
2841            if (componentShortName != null) {
2842                return componentShortName;
2843            }
2844            ComponentName component = getComponentName();
2845            if (component != null) {
2846                componentShortName = component.flattenToShortString();
2847            }
2848            return componentShortName;
2849        }
2850
2851        public void setPackageName(String packageName) {
2852            componentName = null;
2853            componentShortName = null;
2854        }
2855    }
2856
2857    public final static class Permission extends Component<IntentInfo> {
2858        public final PermissionInfo info;
2859        public boolean tree;
2860        public PermissionGroup group;
2861
2862        public Permission(Package _owner) {
2863            super(_owner);
2864            info = new PermissionInfo();
2865        }
2866
2867        public Permission(Package _owner, PermissionInfo _info) {
2868            super(_owner);
2869            info = _info;
2870        }
2871
2872        public void setPackageName(String packageName) {
2873            super.setPackageName(packageName);
2874            info.packageName = packageName;
2875        }
2876
2877        public String toString() {
2878            return "Permission{"
2879                + Integer.toHexString(System.identityHashCode(this))
2880                + " " + info.name + "}";
2881        }
2882    }
2883
2884    public final static class PermissionGroup extends Component<IntentInfo> {
2885        public final PermissionGroupInfo info;
2886
2887        public PermissionGroup(Package _owner) {
2888            super(_owner);
2889            info = new PermissionGroupInfo();
2890        }
2891
2892        public PermissionGroup(Package _owner, PermissionGroupInfo _info) {
2893            super(_owner);
2894            info = _info;
2895        }
2896
2897        public void setPackageName(String packageName) {
2898            super.setPackageName(packageName);
2899            info.packageName = packageName;
2900        }
2901
2902        public String toString() {
2903            return "PermissionGroup{"
2904                + Integer.toHexString(System.identityHashCode(this))
2905                + " " + info.name + "}";
2906        }
2907    }
2908
2909    private static boolean copyNeeded(int flags, Package p, Bundle metaData) {
2910        if ((flags & PackageManager.GET_META_DATA) != 0
2911                && (metaData != null || p.mAppMetaData != null)) {
2912            return true;
2913        }
2914        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0
2915                && p.usesLibraryFiles != null) {
2916            return true;
2917        }
2918        return false;
2919    }
2920
2921    public static ApplicationInfo generateApplicationInfo(Package p, int flags) {
2922        if (p == null) return null;
2923        if (!copyNeeded(flags, p, null)) {
2924            // CompatibilityMode is global state. It's safe to modify the instance
2925            // of the package.
2926            if (!sCompatibilityModeEnabled) {
2927                p.applicationInfo.disableCompatibilityMode();
2928            }
2929            return p.applicationInfo;
2930        }
2931
2932        // Make shallow copy so we can store the metadata/libraries safely
2933        ApplicationInfo ai = new ApplicationInfo(p.applicationInfo);
2934        if ((flags & PackageManager.GET_META_DATA) != 0) {
2935            ai.metaData = p.mAppMetaData;
2936        }
2937        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0) {
2938            ai.sharedLibraryFiles = p.usesLibraryFiles;
2939        }
2940        if (!sCompatibilityModeEnabled) {
2941            ai.disableCompatibilityMode();
2942        }
2943        return ai;
2944    }
2945
2946    public static final PermissionInfo generatePermissionInfo(
2947            Permission p, int flags) {
2948        if (p == null) return null;
2949        if ((flags&PackageManager.GET_META_DATA) == 0) {
2950            return p.info;
2951        }
2952        PermissionInfo pi = new PermissionInfo(p.info);
2953        pi.metaData = p.metaData;
2954        return pi;
2955    }
2956
2957    public static final PermissionGroupInfo generatePermissionGroupInfo(
2958            PermissionGroup pg, int flags) {
2959        if (pg == null) return null;
2960        if ((flags&PackageManager.GET_META_DATA) == 0) {
2961            return pg.info;
2962        }
2963        PermissionGroupInfo pgi = new PermissionGroupInfo(pg.info);
2964        pgi.metaData = pg.metaData;
2965        return pgi;
2966    }
2967
2968    public final static class Activity extends Component<ActivityIntentInfo> {
2969        public final ActivityInfo info;
2970
2971        public Activity(final ParseComponentArgs args, final ActivityInfo _info) {
2972            super(args, _info);
2973            info = _info;
2974            info.applicationInfo = args.owner.applicationInfo;
2975        }
2976
2977        public void setPackageName(String packageName) {
2978            super.setPackageName(packageName);
2979            info.packageName = packageName;
2980        }
2981
2982        public String toString() {
2983            return "Activity{"
2984                + Integer.toHexString(System.identityHashCode(this))
2985                + " " + getComponentShortName() + "}";
2986        }
2987    }
2988
2989    public static final ActivityInfo generateActivityInfo(Activity a,
2990            int flags) {
2991        if (a == null) return null;
2992        if (!copyNeeded(flags, a.owner, a.metaData)) {
2993            return a.info;
2994        }
2995        // Make shallow copies so we can store the metadata safely
2996        ActivityInfo ai = new ActivityInfo(a.info);
2997        ai.metaData = a.metaData;
2998        ai.applicationInfo = generateApplicationInfo(a.owner, flags);
2999        return ai;
3000    }
3001
3002    public final static class Service extends Component<ServiceIntentInfo> {
3003        public final ServiceInfo info;
3004
3005        public Service(final ParseComponentArgs args, final ServiceInfo _info) {
3006            super(args, _info);
3007            info = _info;
3008            info.applicationInfo = args.owner.applicationInfo;
3009        }
3010
3011        public void setPackageName(String packageName) {
3012            super.setPackageName(packageName);
3013            info.packageName = packageName;
3014        }
3015
3016        public String toString() {
3017            return "Service{"
3018                + Integer.toHexString(System.identityHashCode(this))
3019                + " " + getComponentShortName() + "}";
3020        }
3021    }
3022
3023    public static final ServiceInfo generateServiceInfo(Service s, int flags) {
3024        if (s == null) return null;
3025        if (!copyNeeded(flags, s.owner, s.metaData)) {
3026            return s.info;
3027        }
3028        // Make shallow copies so we can store the metadata safely
3029        ServiceInfo si = new ServiceInfo(s.info);
3030        si.metaData = s.metaData;
3031        si.applicationInfo = generateApplicationInfo(s.owner, flags);
3032        return si;
3033    }
3034
3035    public final static class Provider extends Component {
3036        public final ProviderInfo info;
3037        public boolean syncable;
3038
3039        public Provider(final ParseComponentArgs args, final ProviderInfo _info) {
3040            super(args, _info);
3041            info = _info;
3042            info.applicationInfo = args.owner.applicationInfo;
3043            syncable = false;
3044        }
3045
3046        public Provider(Provider existingProvider) {
3047            super(existingProvider);
3048            this.info = existingProvider.info;
3049            this.syncable = existingProvider.syncable;
3050        }
3051
3052        public void setPackageName(String packageName) {
3053            super.setPackageName(packageName);
3054            info.packageName = packageName;
3055        }
3056
3057        public String toString() {
3058            return "Provider{"
3059                + Integer.toHexString(System.identityHashCode(this))
3060                + " " + info.name + "}";
3061        }
3062    }
3063
3064    public static final ProviderInfo generateProviderInfo(Provider p,
3065            int flags) {
3066        if (p == null) return null;
3067        if (!copyNeeded(flags, p.owner, p.metaData)
3068                && ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) != 0
3069                        || p.info.uriPermissionPatterns == null)) {
3070            return p.info;
3071        }
3072        // Make shallow copies so we can store the metadata safely
3073        ProviderInfo pi = new ProviderInfo(p.info);
3074        pi.metaData = p.metaData;
3075        if ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) == 0) {
3076            pi.uriPermissionPatterns = null;
3077        }
3078        pi.applicationInfo = generateApplicationInfo(p.owner, flags);
3079        return pi;
3080    }
3081
3082    public final static class Instrumentation extends Component {
3083        public final InstrumentationInfo info;
3084
3085        public Instrumentation(final ParsePackageItemArgs args, final InstrumentationInfo _info) {
3086            super(args, _info);
3087            info = _info;
3088        }
3089
3090        public void setPackageName(String packageName) {
3091            super.setPackageName(packageName);
3092            info.packageName = packageName;
3093        }
3094
3095        public String toString() {
3096            return "Instrumentation{"
3097                + Integer.toHexString(System.identityHashCode(this))
3098                + " " + getComponentShortName() + "}";
3099        }
3100    }
3101
3102    public static final InstrumentationInfo generateInstrumentationInfo(
3103            Instrumentation i, int flags) {
3104        if (i == null) return null;
3105        if ((flags&PackageManager.GET_META_DATA) == 0) {
3106            return i.info;
3107        }
3108        InstrumentationInfo ii = new InstrumentationInfo(i.info);
3109        ii.metaData = i.metaData;
3110        return ii;
3111    }
3112
3113    public static class IntentInfo extends IntentFilter {
3114        public boolean hasDefault;
3115        public int labelRes;
3116        public CharSequence nonLocalizedLabel;
3117        public int icon;
3118    }
3119
3120    public final static class ActivityIntentInfo extends IntentInfo {
3121        public final Activity activity;
3122
3123        public ActivityIntentInfo(Activity _activity) {
3124            activity = _activity;
3125        }
3126
3127        public String toString() {
3128            return "ActivityIntentInfo{"
3129                + Integer.toHexString(System.identityHashCode(this))
3130                + " " + activity.info.name + "}";
3131        }
3132    }
3133
3134    public final static class ServiceIntentInfo extends IntentInfo {
3135        public final Service service;
3136
3137        public ServiceIntentInfo(Service _service) {
3138            service = _service;
3139        }
3140
3141        public String toString() {
3142            return "ServiceIntentInfo{"
3143                + Integer.toHexString(System.identityHashCode(this))
3144                + " " + service.info.name + "}";
3145        }
3146    }
3147
3148    /**
3149     * @hide
3150     */
3151    public static void setCompatibilityModeEnabled(boolean compatibilityModeEnabled) {
3152        sCompatibilityModeEnabled = compatibilityModeEnabled;
3153    }
3154}
3155