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