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