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