PackageParser.java revision dc71b9e4d67327065a992924a021cad4bc100fa2
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 if (tagName.equals("uses-package")) {
1734                // Dependencies for app installers; we don't currently try to
1735                // enforce this.
1736                XmlUtils.skipCurrentTag(parser);
1737
1738            } else {
1739                if (!RIGID_PARSER) {
1740                    Log.w(TAG, "Unknown element under <application>: " + tagName
1741                            + " at " + mArchiveSourcePath + " "
1742                            + parser.getPositionDescription());
1743                    XmlUtils.skipCurrentTag(parser);
1744                    continue;
1745                } else {
1746                    outError[0] = "Bad element under <application>: " + tagName;
1747                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1748                    return false;
1749                }
1750            }
1751        }
1752
1753        return true;
1754    }
1755
1756    private boolean parsePackageItemInfo(Package owner, PackageItemInfo outInfo,
1757            String[] outError, String tag, TypedArray sa,
1758            int nameRes, int labelRes, int iconRes, int logoRes) {
1759        String name = sa.getNonConfigurationString(nameRes, 0);
1760        if (name == null) {
1761            outError[0] = tag + " does not specify android:name";
1762            return false;
1763        }
1764
1765        outInfo.name
1766            = buildClassName(owner.applicationInfo.packageName, name, outError);
1767        if (outInfo.name == null) {
1768            return false;
1769        }
1770
1771        int iconVal = sa.getResourceId(iconRes, 0);
1772        if (iconVal != 0) {
1773            outInfo.icon = iconVal;
1774            outInfo.nonLocalizedLabel = null;
1775        }
1776
1777        int logoVal = sa.getResourceId(logoRes, 0);
1778        if (logoVal != 0) {
1779            outInfo.logo = logoVal;
1780        }
1781
1782        TypedValue v = sa.peekValue(labelRes);
1783        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
1784            outInfo.nonLocalizedLabel = v.coerceToString();
1785        }
1786
1787        outInfo.packageName = owner.packageName;
1788
1789        return true;
1790    }
1791
1792    private Activity parseActivity(Package owner, Resources res,
1793            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError,
1794            boolean receiver, boolean hardwareAccelerated)
1795            throws XmlPullParserException, IOException {
1796        TypedArray sa = res.obtainAttributes(attrs,
1797                com.android.internal.R.styleable.AndroidManifestActivity);
1798
1799        if (mParseActivityArgs == null) {
1800            mParseActivityArgs = new ParseComponentArgs(owner, outError,
1801                    com.android.internal.R.styleable.AndroidManifestActivity_name,
1802                    com.android.internal.R.styleable.AndroidManifestActivity_label,
1803                    com.android.internal.R.styleable.AndroidManifestActivity_icon,
1804                    com.android.internal.R.styleable.AndroidManifestActivity_logo,
1805                    mSeparateProcesses,
1806                    com.android.internal.R.styleable.AndroidManifestActivity_process,
1807                    com.android.internal.R.styleable.AndroidManifestActivity_description,
1808                    com.android.internal.R.styleable.AndroidManifestActivity_enabled);
1809        }
1810
1811        mParseActivityArgs.tag = receiver ? "<receiver>" : "<activity>";
1812        mParseActivityArgs.sa = sa;
1813        mParseActivityArgs.flags = flags;
1814
1815        Activity a = new Activity(mParseActivityArgs, new ActivityInfo());
1816        if (outError[0] != null) {
1817            sa.recycle();
1818            return null;
1819        }
1820
1821        final boolean setExported = sa.hasValue(
1822                com.android.internal.R.styleable.AndroidManifestActivity_exported);
1823        if (setExported) {
1824            a.info.exported = sa.getBoolean(
1825                    com.android.internal.R.styleable.AndroidManifestActivity_exported, false);
1826        }
1827
1828        a.info.theme = sa.getResourceId(
1829                com.android.internal.R.styleable.AndroidManifestActivity_theme, 0);
1830
1831        String str;
1832        str = sa.getNonConfigurationString(
1833                com.android.internal.R.styleable.AndroidManifestActivity_permission, 0);
1834        if (str == null) {
1835            a.info.permission = owner.applicationInfo.permission;
1836        } else {
1837            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
1838        }
1839
1840        str = sa.getNonConfigurationString(
1841                com.android.internal.R.styleable.AndroidManifestActivity_taskAffinity, 0);
1842        a.info.taskAffinity = buildTaskAffinityName(owner.applicationInfo.packageName,
1843                owner.applicationInfo.taskAffinity, str, outError);
1844
1845        a.info.flags = 0;
1846        if (sa.getBoolean(
1847                com.android.internal.R.styleable.AndroidManifestActivity_multiprocess,
1848                false)) {
1849            a.info.flags |= ActivityInfo.FLAG_MULTIPROCESS;
1850        }
1851
1852        if (sa.getBoolean(
1853                com.android.internal.R.styleable.AndroidManifestActivity_finishOnTaskLaunch,
1854                false)) {
1855            a.info.flags |= ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH;
1856        }
1857
1858        if (sa.getBoolean(
1859                com.android.internal.R.styleable.AndroidManifestActivity_clearTaskOnLaunch,
1860                false)) {
1861            a.info.flags |= ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH;
1862        }
1863
1864        if (sa.getBoolean(
1865                com.android.internal.R.styleable.AndroidManifestActivity_noHistory,
1866                false)) {
1867            a.info.flags |= ActivityInfo.FLAG_NO_HISTORY;
1868        }
1869
1870        if (sa.getBoolean(
1871                com.android.internal.R.styleable.AndroidManifestActivity_alwaysRetainTaskState,
1872                false)) {
1873            a.info.flags |= ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE;
1874        }
1875
1876        if (sa.getBoolean(
1877                com.android.internal.R.styleable.AndroidManifestActivity_stateNotNeeded,
1878                false)) {
1879            a.info.flags |= ActivityInfo.FLAG_STATE_NOT_NEEDED;
1880        }
1881
1882        if (sa.getBoolean(
1883                com.android.internal.R.styleable.AndroidManifestActivity_excludeFromRecents,
1884                false)) {
1885            a.info.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1886        }
1887
1888        if (sa.getBoolean(
1889                com.android.internal.R.styleable.AndroidManifestActivity_allowTaskReparenting,
1890                (owner.applicationInfo.flags&ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING) != 0)) {
1891            a.info.flags |= ActivityInfo.FLAG_ALLOW_TASK_REPARENTING;
1892        }
1893
1894        if (sa.getBoolean(
1895                com.android.internal.R.styleable.AndroidManifestActivity_finishOnCloseSystemDialogs,
1896                false)) {
1897            a.info.flags |= ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
1898        }
1899
1900        if (sa.getBoolean(
1901                com.android.internal.R.styleable.AndroidManifestActivity_immersive,
1902                false)) {
1903            a.info.flags |= ActivityInfo.FLAG_IMMERSIVE;
1904        }
1905
1906        if (!receiver) {
1907            if (sa.getBoolean(
1908                    com.android.internal.R.styleable.AndroidManifestActivity_hardwareAccelerated,
1909                    hardwareAccelerated)) {
1910                a.info.flags |= ActivityInfo.FLAG_HARDWARE_ACCELERATED;
1911            }
1912
1913            a.info.launchMode = sa.getInt(
1914                    com.android.internal.R.styleable.AndroidManifestActivity_launchMode,
1915                    ActivityInfo.LAUNCH_MULTIPLE);
1916            a.info.screenOrientation = sa.getInt(
1917                    com.android.internal.R.styleable.AndroidManifestActivity_screenOrientation,
1918                    ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1919            a.info.configChanges = sa.getInt(
1920                    com.android.internal.R.styleable.AndroidManifestActivity_configChanges,
1921                    0);
1922            a.info.softInputMode = sa.getInt(
1923                    com.android.internal.R.styleable.AndroidManifestActivity_windowSoftInputMode,
1924                    0);
1925        } else {
1926            a.info.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1927            a.info.configChanges = 0;
1928        }
1929
1930        sa.recycle();
1931
1932        if (receiver && (owner.applicationInfo.flags&ApplicationInfo.CANT_SAVE_STATE) != 0) {
1933            // A heavy-weight application can not have receives in its main process
1934            // We can do direct compare because we intern all strings.
1935            if (a.info.processName == owner.packageName) {
1936                outError[0] = "Heavy-weight applications can not have receivers in main process";
1937            }
1938        }
1939
1940        if (outError[0] != null) {
1941            return null;
1942        }
1943
1944        int outerDepth = parser.getDepth();
1945        int type;
1946        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1947               && (type != XmlPullParser.END_TAG
1948                       || parser.getDepth() > outerDepth)) {
1949            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1950                continue;
1951            }
1952
1953            if (parser.getName().equals("intent-filter")) {
1954                ActivityIntentInfo intent = new ActivityIntentInfo(a);
1955                if (!parseIntent(res, parser, attrs, flags, intent, outError, !receiver)) {
1956                    return null;
1957                }
1958                if (intent.countActions() == 0) {
1959                    Log.w(TAG, "No actions in intent filter at "
1960                            + mArchiveSourcePath + " "
1961                            + parser.getPositionDescription());
1962                } else {
1963                    a.intents.add(intent);
1964                }
1965            } else if (parser.getName().equals("meta-data")) {
1966                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
1967                        outError)) == null) {
1968                    return null;
1969                }
1970            } else {
1971                if (!RIGID_PARSER) {
1972                    Log.w(TAG, "Problem in package " + mArchiveSourcePath + ":");
1973                    if (receiver) {
1974                        Log.w(TAG, "Unknown element under <receiver>: " + parser.getName()
1975                                + " at " + mArchiveSourcePath + " "
1976                                + parser.getPositionDescription());
1977                    } else {
1978                        Log.w(TAG, "Unknown element under <activity>: " + parser.getName()
1979                                + " at " + mArchiveSourcePath + " "
1980                                + parser.getPositionDescription());
1981                    }
1982                    XmlUtils.skipCurrentTag(parser);
1983                    continue;
1984                }
1985                if (receiver) {
1986                    outError[0] = "Bad element under <receiver>: " + parser.getName();
1987                } else {
1988                    outError[0] = "Bad element under <activity>: " + parser.getName();
1989                }
1990                return null;
1991            }
1992        }
1993
1994        if (!setExported) {
1995            a.info.exported = a.intents.size() > 0;
1996        }
1997
1998        return a;
1999    }
2000
2001    private Activity parseActivityAlias(Package owner, Resources res,
2002            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2003            throws XmlPullParserException, IOException {
2004        TypedArray sa = res.obtainAttributes(attrs,
2005                com.android.internal.R.styleable.AndroidManifestActivityAlias);
2006
2007        String targetActivity = sa.getNonConfigurationString(
2008                com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity, 0);
2009        if (targetActivity == null) {
2010            outError[0] = "<activity-alias> does not specify android:targetActivity";
2011            sa.recycle();
2012            return null;
2013        }
2014
2015        targetActivity = buildClassName(owner.applicationInfo.packageName,
2016                targetActivity, outError);
2017        if (targetActivity == null) {
2018            sa.recycle();
2019            return null;
2020        }
2021
2022        if (mParseActivityAliasArgs == null) {
2023            mParseActivityAliasArgs = new ParseComponentArgs(owner, outError,
2024                    com.android.internal.R.styleable.AndroidManifestActivityAlias_name,
2025                    com.android.internal.R.styleable.AndroidManifestActivityAlias_label,
2026                    com.android.internal.R.styleable.AndroidManifestActivityAlias_icon,
2027                    com.android.internal.R.styleable.AndroidManifestActivityAlias_logo,
2028                    mSeparateProcesses,
2029                    0,
2030                    com.android.internal.R.styleable.AndroidManifestActivityAlias_description,
2031                    com.android.internal.R.styleable.AndroidManifestActivityAlias_enabled);
2032            mParseActivityAliasArgs.tag = "<activity-alias>";
2033        }
2034
2035        mParseActivityAliasArgs.sa = sa;
2036        mParseActivityAliasArgs.flags = flags;
2037
2038        Activity target = null;
2039
2040        final int NA = owner.activities.size();
2041        for (int i=0; i<NA; i++) {
2042            Activity t = owner.activities.get(i);
2043            if (targetActivity.equals(t.info.name)) {
2044                target = t;
2045                break;
2046            }
2047        }
2048
2049        if (target == null) {
2050            outError[0] = "<activity-alias> target activity " + targetActivity
2051                    + " not found in manifest";
2052            sa.recycle();
2053            return null;
2054        }
2055
2056        ActivityInfo info = new ActivityInfo();
2057        info.targetActivity = targetActivity;
2058        info.configChanges = target.info.configChanges;
2059        info.flags = target.info.flags;
2060        info.icon = target.info.icon;
2061        info.logo = target.info.logo;
2062        info.labelRes = target.info.labelRes;
2063        info.nonLocalizedLabel = target.info.nonLocalizedLabel;
2064        info.launchMode = target.info.launchMode;
2065        info.processName = target.info.processName;
2066        if (info.descriptionRes == 0) {
2067            info.descriptionRes = target.info.descriptionRes;
2068        }
2069        info.screenOrientation = target.info.screenOrientation;
2070        info.taskAffinity = target.info.taskAffinity;
2071        info.theme = target.info.theme;
2072
2073        Activity a = new Activity(mParseActivityAliasArgs, info);
2074        if (outError[0] != null) {
2075            sa.recycle();
2076            return null;
2077        }
2078
2079        final boolean setExported = sa.hasValue(
2080                com.android.internal.R.styleable.AndroidManifestActivityAlias_exported);
2081        if (setExported) {
2082            a.info.exported = sa.getBoolean(
2083                    com.android.internal.R.styleable.AndroidManifestActivityAlias_exported, false);
2084        }
2085
2086        String str;
2087        str = sa.getNonConfigurationString(
2088                com.android.internal.R.styleable.AndroidManifestActivityAlias_permission, 0);
2089        if (str != null) {
2090            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
2091        }
2092
2093        sa.recycle();
2094
2095        if (outError[0] != null) {
2096            return null;
2097        }
2098
2099        int outerDepth = parser.getDepth();
2100        int type;
2101        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2102               && (type != XmlPullParser.END_TAG
2103                       || parser.getDepth() > outerDepth)) {
2104            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2105                continue;
2106            }
2107
2108            if (parser.getName().equals("intent-filter")) {
2109                ActivityIntentInfo intent = new ActivityIntentInfo(a);
2110                if (!parseIntent(res, parser, attrs, flags, intent, outError, true)) {
2111                    return null;
2112                }
2113                if (intent.countActions() == 0) {
2114                    Log.w(TAG, "No actions in intent filter at "
2115                            + mArchiveSourcePath + " "
2116                            + parser.getPositionDescription());
2117                } else {
2118                    a.intents.add(intent);
2119                }
2120            } else if (parser.getName().equals("meta-data")) {
2121                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
2122                        outError)) == null) {
2123                    return null;
2124                }
2125            } else {
2126                if (!RIGID_PARSER) {
2127                    Log.w(TAG, "Unknown element under <activity-alias>: " + parser.getName()
2128                            + " at " + mArchiveSourcePath + " "
2129                            + parser.getPositionDescription());
2130                    XmlUtils.skipCurrentTag(parser);
2131                    continue;
2132                }
2133                outError[0] = "Bad element under <activity-alias>: " + parser.getName();
2134                return null;
2135            }
2136        }
2137
2138        if (!setExported) {
2139            a.info.exported = a.intents.size() > 0;
2140        }
2141
2142        return a;
2143    }
2144
2145    private Provider parseProvider(Package owner, Resources res,
2146            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2147            throws XmlPullParserException, IOException {
2148        TypedArray sa = res.obtainAttributes(attrs,
2149                com.android.internal.R.styleable.AndroidManifestProvider);
2150
2151        if (mParseProviderArgs == null) {
2152            mParseProviderArgs = new ParseComponentArgs(owner, outError,
2153                    com.android.internal.R.styleable.AndroidManifestProvider_name,
2154                    com.android.internal.R.styleable.AndroidManifestProvider_label,
2155                    com.android.internal.R.styleable.AndroidManifestProvider_icon,
2156                    com.android.internal.R.styleable.AndroidManifestProvider_logo,
2157                    mSeparateProcesses,
2158                    com.android.internal.R.styleable.AndroidManifestProvider_process,
2159                    com.android.internal.R.styleable.AndroidManifestProvider_description,
2160                    com.android.internal.R.styleable.AndroidManifestProvider_enabled);
2161            mParseProviderArgs.tag = "<provider>";
2162        }
2163
2164        mParseProviderArgs.sa = sa;
2165        mParseProviderArgs.flags = flags;
2166
2167        Provider p = new Provider(mParseProviderArgs, new ProviderInfo());
2168        if (outError[0] != null) {
2169            sa.recycle();
2170            return null;
2171        }
2172
2173        p.info.exported = sa.getBoolean(
2174                com.android.internal.R.styleable.AndroidManifestProvider_exported, true);
2175
2176        String cpname = sa.getNonConfigurationString(
2177                com.android.internal.R.styleable.AndroidManifestProvider_authorities, 0);
2178
2179        p.info.isSyncable = sa.getBoolean(
2180                com.android.internal.R.styleable.AndroidManifestProvider_syncable,
2181                false);
2182
2183        String permission = sa.getNonConfigurationString(
2184                com.android.internal.R.styleable.AndroidManifestProvider_permission, 0);
2185        String str = sa.getNonConfigurationString(
2186                com.android.internal.R.styleable.AndroidManifestProvider_readPermission, 0);
2187        if (str == null) {
2188            str = permission;
2189        }
2190        if (str == null) {
2191            p.info.readPermission = owner.applicationInfo.permission;
2192        } else {
2193            p.info.readPermission =
2194                str.length() > 0 ? str.toString().intern() : null;
2195        }
2196        str = sa.getNonConfigurationString(
2197                com.android.internal.R.styleable.AndroidManifestProvider_writePermission, 0);
2198        if (str == null) {
2199            str = permission;
2200        }
2201        if (str == null) {
2202            p.info.writePermission = owner.applicationInfo.permission;
2203        } else {
2204            p.info.writePermission =
2205                str.length() > 0 ? str.toString().intern() : null;
2206        }
2207
2208        p.info.grantUriPermissions = sa.getBoolean(
2209                com.android.internal.R.styleable.AndroidManifestProvider_grantUriPermissions,
2210                false);
2211
2212        p.info.multiprocess = sa.getBoolean(
2213                com.android.internal.R.styleable.AndroidManifestProvider_multiprocess,
2214                false);
2215
2216        p.info.initOrder = sa.getInt(
2217                com.android.internal.R.styleable.AndroidManifestProvider_initOrder,
2218                0);
2219
2220        sa.recycle();
2221
2222        if ((owner.applicationInfo.flags&ApplicationInfo.CANT_SAVE_STATE) != 0) {
2223            // A heavy-weight application can not have providers in its main process
2224            // We can do direct compare because we intern all strings.
2225            if (p.info.processName == owner.packageName) {
2226                outError[0] = "Heavy-weight applications can not have providers in main process";
2227                return null;
2228            }
2229        }
2230
2231        if (cpname == null) {
2232            outError[0] = "<provider> does not incude authorities attribute";
2233            return null;
2234        }
2235        p.info.authority = cpname.intern();
2236
2237        if (!parseProviderTags(res, parser, attrs, p, outError)) {
2238            return null;
2239        }
2240
2241        return p;
2242    }
2243
2244    private boolean parseProviderTags(Resources res,
2245            XmlPullParser parser, AttributeSet attrs,
2246            Provider outInfo, String[] outError)
2247            throws XmlPullParserException, IOException {
2248        int outerDepth = parser.getDepth();
2249        int type;
2250        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2251               && (type != XmlPullParser.END_TAG
2252                       || parser.getDepth() > outerDepth)) {
2253            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2254                continue;
2255            }
2256
2257            if (parser.getName().equals("meta-data")) {
2258                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2259                        outInfo.metaData, outError)) == null) {
2260                    return false;
2261                }
2262
2263            } else if (parser.getName().equals("grant-uri-permission")) {
2264                TypedArray sa = res.obtainAttributes(attrs,
2265                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission);
2266
2267                PatternMatcher pa = null;
2268
2269                String str = sa.getNonConfigurationString(
2270                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path, 0);
2271                if (str != null) {
2272                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_LITERAL);
2273                }
2274
2275                str = sa.getNonConfigurationString(
2276                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix, 0);
2277                if (str != null) {
2278                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_PREFIX);
2279                }
2280
2281                str = sa.getNonConfigurationString(
2282                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern, 0);
2283                if (str != null) {
2284                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2285                }
2286
2287                sa.recycle();
2288
2289                if (pa != null) {
2290                    if (outInfo.info.uriPermissionPatterns == null) {
2291                        outInfo.info.uriPermissionPatterns = new PatternMatcher[1];
2292                        outInfo.info.uriPermissionPatterns[0] = pa;
2293                    } else {
2294                        final int N = outInfo.info.uriPermissionPatterns.length;
2295                        PatternMatcher[] newp = new PatternMatcher[N+1];
2296                        System.arraycopy(outInfo.info.uriPermissionPatterns, 0, newp, 0, N);
2297                        newp[N] = pa;
2298                        outInfo.info.uriPermissionPatterns = newp;
2299                    }
2300                    outInfo.info.grantUriPermissions = true;
2301                } else {
2302                    if (!RIGID_PARSER) {
2303                        Log.w(TAG, "Unknown element under <path-permission>: "
2304                                + parser.getName() + " at " + mArchiveSourcePath + " "
2305                                + parser.getPositionDescription());
2306                        XmlUtils.skipCurrentTag(parser);
2307                        continue;
2308                    }
2309                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2310                    return false;
2311                }
2312                XmlUtils.skipCurrentTag(parser);
2313
2314            } else if (parser.getName().equals("path-permission")) {
2315                TypedArray sa = res.obtainAttributes(attrs,
2316                        com.android.internal.R.styleable.AndroidManifestPathPermission);
2317
2318                PathPermission pa = null;
2319
2320                String permission = sa.getNonConfigurationString(
2321                        com.android.internal.R.styleable.AndroidManifestPathPermission_permission, 0);
2322                String readPermission = sa.getNonConfigurationString(
2323                        com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission, 0);
2324                if (readPermission == null) {
2325                    readPermission = permission;
2326                }
2327                String writePermission = sa.getNonConfigurationString(
2328                        com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission, 0);
2329                if (writePermission == null) {
2330                    writePermission = permission;
2331                }
2332
2333                boolean havePerm = false;
2334                if (readPermission != null) {
2335                    readPermission = readPermission.intern();
2336                    havePerm = true;
2337                }
2338                if (writePermission != null) {
2339                    writePermission = writePermission.intern();
2340                    havePerm = true;
2341                }
2342
2343                if (!havePerm) {
2344                    if (!RIGID_PARSER) {
2345                        Log.w(TAG, "No readPermission or writePermssion for <path-permission>: "
2346                                + parser.getName() + " at " + mArchiveSourcePath + " "
2347                                + parser.getPositionDescription());
2348                        XmlUtils.skipCurrentTag(parser);
2349                        continue;
2350                    }
2351                    outError[0] = "No readPermission or writePermssion for <path-permission>";
2352                    return false;
2353                }
2354
2355                String path = sa.getNonConfigurationString(
2356                        com.android.internal.R.styleable.AndroidManifestPathPermission_path, 0);
2357                if (path != null) {
2358                    pa = new PathPermission(path,
2359                            PatternMatcher.PATTERN_LITERAL, readPermission, writePermission);
2360                }
2361
2362                path = sa.getNonConfigurationString(
2363                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix, 0);
2364                if (path != null) {
2365                    pa = new PathPermission(path,
2366                            PatternMatcher.PATTERN_PREFIX, readPermission, writePermission);
2367                }
2368
2369                path = sa.getNonConfigurationString(
2370                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern, 0);
2371                if (path != null) {
2372                    pa = new PathPermission(path,
2373                            PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
2374                }
2375
2376                sa.recycle();
2377
2378                if (pa != null) {
2379                    if (outInfo.info.pathPermissions == null) {
2380                        outInfo.info.pathPermissions = new PathPermission[1];
2381                        outInfo.info.pathPermissions[0] = pa;
2382                    } else {
2383                        final int N = outInfo.info.pathPermissions.length;
2384                        PathPermission[] newp = new PathPermission[N+1];
2385                        System.arraycopy(outInfo.info.pathPermissions, 0, newp, 0, N);
2386                        newp[N] = pa;
2387                        outInfo.info.pathPermissions = newp;
2388                    }
2389                } else {
2390                    if (!RIGID_PARSER) {
2391                        Log.w(TAG, "No path, pathPrefix, or pathPattern for <path-permission>: "
2392                                + parser.getName() + " at " + mArchiveSourcePath + " "
2393                                + parser.getPositionDescription());
2394                        XmlUtils.skipCurrentTag(parser);
2395                        continue;
2396                    }
2397                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2398                    return false;
2399                }
2400                XmlUtils.skipCurrentTag(parser);
2401
2402            } else {
2403                if (!RIGID_PARSER) {
2404                    Log.w(TAG, "Unknown element under <provider>: "
2405                            + parser.getName() + " at " + mArchiveSourcePath + " "
2406                            + parser.getPositionDescription());
2407                    XmlUtils.skipCurrentTag(parser);
2408                    continue;
2409                }
2410                outError[0] = "Bad element under <provider>: "
2411                    + parser.getName();
2412                return false;
2413            }
2414        }
2415        return true;
2416    }
2417
2418    private Service parseService(Package owner, Resources res,
2419            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2420            throws XmlPullParserException, IOException {
2421        TypedArray sa = res.obtainAttributes(attrs,
2422                com.android.internal.R.styleable.AndroidManifestService);
2423
2424        if (mParseServiceArgs == null) {
2425            mParseServiceArgs = new ParseComponentArgs(owner, outError,
2426                    com.android.internal.R.styleable.AndroidManifestService_name,
2427                    com.android.internal.R.styleable.AndroidManifestService_label,
2428                    com.android.internal.R.styleable.AndroidManifestService_icon,
2429                    com.android.internal.R.styleable.AndroidManifestService_logo,
2430                    mSeparateProcesses,
2431                    com.android.internal.R.styleable.AndroidManifestService_process,
2432                    com.android.internal.R.styleable.AndroidManifestService_description,
2433                    com.android.internal.R.styleable.AndroidManifestService_enabled);
2434            mParseServiceArgs.tag = "<service>";
2435        }
2436
2437        mParseServiceArgs.sa = sa;
2438        mParseServiceArgs.flags = flags;
2439
2440        Service s = new Service(mParseServiceArgs, new ServiceInfo());
2441        if (outError[0] != null) {
2442            sa.recycle();
2443            return null;
2444        }
2445
2446        final boolean setExported = sa.hasValue(
2447                com.android.internal.R.styleable.AndroidManifestService_exported);
2448        if (setExported) {
2449            s.info.exported = sa.getBoolean(
2450                    com.android.internal.R.styleable.AndroidManifestService_exported, false);
2451        }
2452
2453        String str = sa.getNonConfigurationString(
2454                com.android.internal.R.styleable.AndroidManifestService_permission, 0);
2455        if (str == null) {
2456            s.info.permission = owner.applicationInfo.permission;
2457        } else {
2458            s.info.permission = str.length() > 0 ? str.toString().intern() : null;
2459        }
2460
2461        sa.recycle();
2462
2463        if ((owner.applicationInfo.flags&ApplicationInfo.CANT_SAVE_STATE) != 0) {
2464            // A heavy-weight application can not have services in its main process
2465            // We can do direct compare because we intern all strings.
2466            if (s.info.processName == owner.packageName) {
2467                outError[0] = "Heavy-weight applications can not have services in main process";
2468                return null;
2469            }
2470        }
2471
2472        int outerDepth = parser.getDepth();
2473        int type;
2474        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2475               && (type != XmlPullParser.END_TAG
2476                       || parser.getDepth() > outerDepth)) {
2477            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2478                continue;
2479            }
2480
2481            if (parser.getName().equals("intent-filter")) {
2482                ServiceIntentInfo intent = new ServiceIntentInfo(s);
2483                if (!parseIntent(res, parser, attrs, flags, intent, outError, false)) {
2484                    return null;
2485                }
2486
2487                s.intents.add(intent);
2488            } else if (parser.getName().equals("meta-data")) {
2489                if ((s.metaData=parseMetaData(res, parser, attrs, s.metaData,
2490                        outError)) == null) {
2491                    return null;
2492                }
2493            } else {
2494                if (!RIGID_PARSER) {
2495                    Log.w(TAG, "Unknown element under <service>: "
2496                            + parser.getName() + " at " + mArchiveSourcePath + " "
2497                            + parser.getPositionDescription());
2498                    XmlUtils.skipCurrentTag(parser);
2499                    continue;
2500                }
2501                outError[0] = "Bad element under <service>: "
2502                    + parser.getName();
2503                return null;
2504            }
2505        }
2506
2507        if (!setExported) {
2508            s.info.exported = s.intents.size() > 0;
2509        }
2510
2511        return s;
2512    }
2513
2514    private boolean parseAllMetaData(Resources res,
2515            XmlPullParser parser, AttributeSet attrs, String tag,
2516            Component outInfo, String[] outError)
2517            throws XmlPullParserException, IOException {
2518        int outerDepth = parser.getDepth();
2519        int type;
2520        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2521               && (type != XmlPullParser.END_TAG
2522                       || parser.getDepth() > outerDepth)) {
2523            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2524                continue;
2525            }
2526
2527            if (parser.getName().equals("meta-data")) {
2528                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2529                        outInfo.metaData, outError)) == null) {
2530                    return false;
2531                }
2532            } else {
2533                if (!RIGID_PARSER) {
2534                    Log.w(TAG, "Unknown element under " + tag + ": "
2535                            + parser.getName() + " at " + mArchiveSourcePath + " "
2536                            + parser.getPositionDescription());
2537                    XmlUtils.skipCurrentTag(parser);
2538                    continue;
2539                }
2540                outError[0] = "Bad element under " + tag + ": "
2541                    + parser.getName();
2542                return false;
2543            }
2544        }
2545        return true;
2546    }
2547
2548    private Bundle parseMetaData(Resources res,
2549            XmlPullParser parser, AttributeSet attrs,
2550            Bundle data, String[] outError)
2551            throws XmlPullParserException, IOException {
2552
2553        TypedArray sa = res.obtainAttributes(attrs,
2554                com.android.internal.R.styleable.AndroidManifestMetaData);
2555
2556        if (data == null) {
2557            data = new Bundle();
2558        }
2559
2560        String name = sa.getNonConfigurationString(
2561                com.android.internal.R.styleable.AndroidManifestMetaData_name, 0);
2562        if (name == null) {
2563            outError[0] = "<meta-data> requires an android:name attribute";
2564            sa.recycle();
2565            return null;
2566        }
2567
2568        name = name.intern();
2569
2570        TypedValue v = sa.peekValue(
2571                com.android.internal.R.styleable.AndroidManifestMetaData_resource);
2572        if (v != null && v.resourceId != 0) {
2573            //Log.i(TAG, "Meta data ref " + name + ": " + v);
2574            data.putInt(name, v.resourceId);
2575        } else {
2576            v = sa.peekValue(
2577                    com.android.internal.R.styleable.AndroidManifestMetaData_value);
2578            //Log.i(TAG, "Meta data " + name + ": " + v);
2579            if (v != null) {
2580                if (v.type == TypedValue.TYPE_STRING) {
2581                    CharSequence cs = v.coerceToString();
2582                    data.putString(name, cs != null ? cs.toString().intern() : null);
2583                } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2584                    data.putBoolean(name, v.data != 0);
2585                } else if (v.type >= TypedValue.TYPE_FIRST_INT
2586                        && v.type <= TypedValue.TYPE_LAST_INT) {
2587                    data.putInt(name, v.data);
2588                } else if (v.type == TypedValue.TYPE_FLOAT) {
2589                    data.putFloat(name, v.getFloat());
2590                } else {
2591                    if (!RIGID_PARSER) {
2592                        Log.w(TAG, "<meta-data> only supports string, integer, float, color, boolean, and resource reference types: "
2593                                + parser.getName() + " at " + mArchiveSourcePath + " "
2594                                + parser.getPositionDescription());
2595                    } else {
2596                        outError[0] = "<meta-data> only supports string, integer, float, color, boolean, and resource reference types";
2597                        data = null;
2598                    }
2599                }
2600            } else {
2601                outError[0] = "<meta-data> requires an android:value or android:resource attribute";
2602                data = null;
2603            }
2604        }
2605
2606        sa.recycle();
2607
2608        XmlUtils.skipCurrentTag(parser);
2609
2610        return data;
2611    }
2612
2613    private static final String ANDROID_RESOURCES
2614            = "http://schemas.android.com/apk/res/android";
2615
2616    private boolean parseIntent(Resources res,
2617            XmlPullParser parser, AttributeSet attrs, int flags,
2618            IntentInfo outInfo, String[] outError, boolean isActivity)
2619            throws XmlPullParserException, IOException {
2620
2621        TypedArray sa = res.obtainAttributes(attrs,
2622                com.android.internal.R.styleable.AndroidManifestIntentFilter);
2623
2624        int priority = sa.getInt(
2625                com.android.internal.R.styleable.AndroidManifestIntentFilter_priority, 0);
2626        if (priority > 0 && isActivity && (flags&PARSE_IS_SYSTEM) == 0) {
2627            Log.w(TAG, "Activity with priority > 0, forcing to 0 at "
2628                    + mArchiveSourcePath + " "
2629                    + parser.getPositionDescription());
2630            priority = 0;
2631        }
2632        outInfo.setPriority(priority);
2633
2634        TypedValue v = sa.peekValue(
2635                com.android.internal.R.styleable.AndroidManifestIntentFilter_label);
2636        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2637            outInfo.nonLocalizedLabel = v.coerceToString();
2638        }
2639
2640        outInfo.icon = sa.getResourceId(
2641                com.android.internal.R.styleable.AndroidManifestIntentFilter_icon, 0);
2642
2643        outInfo.logo = sa.getResourceId(
2644                com.android.internal.R.styleable.AndroidManifestIntentFilter_logo, 0);
2645
2646        sa.recycle();
2647
2648        int outerDepth = parser.getDepth();
2649        int type;
2650        while ((type=parser.next()) != parser.END_DOCUMENT
2651               && (type != parser.END_TAG || parser.getDepth() > outerDepth)) {
2652            if (type == parser.END_TAG || type == parser.TEXT) {
2653                continue;
2654            }
2655
2656            String nodeName = parser.getName();
2657            if (nodeName.equals("action")) {
2658                String value = attrs.getAttributeValue(
2659                        ANDROID_RESOURCES, "name");
2660                if (value == null || value == "") {
2661                    outError[0] = "No value supplied for <android:name>";
2662                    return false;
2663                }
2664                XmlUtils.skipCurrentTag(parser);
2665
2666                outInfo.addAction(value);
2667            } else if (nodeName.equals("category")) {
2668                String value = attrs.getAttributeValue(
2669                        ANDROID_RESOURCES, "name");
2670                if (value == null || value == "") {
2671                    outError[0] = "No value supplied for <android:name>";
2672                    return false;
2673                }
2674                XmlUtils.skipCurrentTag(parser);
2675
2676                outInfo.addCategory(value);
2677
2678            } else if (nodeName.equals("data")) {
2679                sa = res.obtainAttributes(attrs,
2680                        com.android.internal.R.styleable.AndroidManifestData);
2681
2682                String str = sa.getNonConfigurationString(
2683                        com.android.internal.R.styleable.AndroidManifestData_mimeType, 0);
2684                if (str != null) {
2685                    try {
2686                        outInfo.addDataType(str);
2687                    } catch (IntentFilter.MalformedMimeTypeException e) {
2688                        outError[0] = e.toString();
2689                        sa.recycle();
2690                        return false;
2691                    }
2692                }
2693
2694                str = sa.getNonConfigurationString(
2695                        com.android.internal.R.styleable.AndroidManifestData_scheme, 0);
2696                if (str != null) {
2697                    outInfo.addDataScheme(str);
2698                }
2699
2700                String host = sa.getNonConfigurationString(
2701                        com.android.internal.R.styleable.AndroidManifestData_host, 0);
2702                String port = sa.getNonConfigurationString(
2703                        com.android.internal.R.styleable.AndroidManifestData_port, 0);
2704                if (host != null) {
2705                    outInfo.addDataAuthority(host, port);
2706                }
2707
2708                str = sa.getNonConfigurationString(
2709                        com.android.internal.R.styleable.AndroidManifestData_path, 0);
2710                if (str != null) {
2711                    outInfo.addDataPath(str, PatternMatcher.PATTERN_LITERAL);
2712                }
2713
2714                str = sa.getNonConfigurationString(
2715                        com.android.internal.R.styleable.AndroidManifestData_pathPrefix, 0);
2716                if (str != null) {
2717                    outInfo.addDataPath(str, PatternMatcher.PATTERN_PREFIX);
2718                }
2719
2720                str = sa.getNonConfigurationString(
2721                        com.android.internal.R.styleable.AndroidManifestData_pathPattern, 0);
2722                if (str != null) {
2723                    outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2724                }
2725
2726                sa.recycle();
2727                XmlUtils.skipCurrentTag(parser);
2728            } else if (!RIGID_PARSER) {
2729                Log.w(TAG, "Unknown element under <intent-filter>: "
2730                        + parser.getName() + " at " + mArchiveSourcePath + " "
2731                        + parser.getPositionDescription());
2732                XmlUtils.skipCurrentTag(parser);
2733            } else {
2734                outError[0] = "Bad element under <intent-filter>: " + parser.getName();
2735                return false;
2736            }
2737        }
2738
2739        outInfo.hasDefault = outInfo.hasCategory(Intent.CATEGORY_DEFAULT);
2740        if (false) {
2741            String cats = "";
2742            Iterator<String> it = outInfo.categoriesIterator();
2743            while (it != null && it.hasNext()) {
2744                cats += " " + it.next();
2745            }
2746            System.out.println("Intent d=" +
2747                    outInfo.hasDefault + ", cat=" + cats);
2748        }
2749
2750        return true;
2751    }
2752
2753    public final static class Package {
2754        public String packageName;
2755
2756        // For now we only support one application per package.
2757        public final ApplicationInfo applicationInfo = new ApplicationInfo();
2758
2759        public final ArrayList<Permission> permissions = new ArrayList<Permission>(0);
2760        public final ArrayList<PermissionGroup> permissionGroups = new ArrayList<PermissionGroup>(0);
2761        public final ArrayList<Activity> activities = new ArrayList<Activity>(0);
2762        public final ArrayList<Activity> receivers = new ArrayList<Activity>(0);
2763        public final ArrayList<Provider> providers = new ArrayList<Provider>(0);
2764        public final ArrayList<Service> services = new ArrayList<Service>(0);
2765        public final ArrayList<Instrumentation> instrumentation = new ArrayList<Instrumentation>(0);
2766
2767        public final ArrayList<String> requestedPermissions = new ArrayList<String>();
2768
2769        public ArrayList<String> protectedBroadcasts;
2770
2771        public ArrayList<String> usesLibraries = null;
2772        public ArrayList<String> usesOptionalLibraries = null;
2773        public String[] usesLibraryFiles = null;
2774
2775        public ArrayList<String> mOriginalPackages = null;
2776        public String mRealPackage = null;
2777        public ArrayList<String> mAdoptPermissions = null;
2778
2779        // We store the application meta-data independently to avoid multiple unwanted references
2780        public Bundle mAppMetaData = null;
2781
2782        // If this is a 3rd party app, this is the path of the zip file.
2783        public String mPath;
2784
2785        // The version code declared for this package.
2786        public int mVersionCode;
2787
2788        // The version name declared for this package.
2789        public String mVersionName;
2790
2791        // The shared user id that this package wants to use.
2792        public String mSharedUserId;
2793
2794        // The shared user label that this package wants to use.
2795        public int mSharedUserLabel;
2796
2797        // Signatures that were read from the package.
2798        public Signature mSignatures[];
2799
2800        // For use by package manager service for quick lookup of
2801        // preferred up order.
2802        public int mPreferredOrder = 0;
2803
2804        // For use by the package manager to keep track of the path to the
2805        // file an app came from.
2806        public String mScanPath;
2807
2808        // For use by package manager to keep track of where it has done dexopt.
2809        public boolean mDidDexOpt;
2810
2811        // User set enabled state.
2812        public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2813
2814        // Additional data supplied by callers.
2815        public Object mExtras;
2816
2817        // Whether an operation is currently pending on this package
2818        public boolean mOperationPending;
2819
2820        /*
2821         *  Applications hardware preferences
2822         */
2823        public final ArrayList<ConfigurationInfo> configPreferences =
2824                new ArrayList<ConfigurationInfo>();
2825
2826        /*
2827         *  Applications requested features
2828         */
2829        public ArrayList<FeatureInfo> reqFeatures = null;
2830
2831        public int installLocation;
2832
2833        public Package(String _name) {
2834            packageName = _name;
2835            applicationInfo.packageName = _name;
2836            applicationInfo.uid = -1;
2837        }
2838
2839        public void setPackageName(String newName) {
2840            packageName = newName;
2841            applicationInfo.packageName = newName;
2842            for (int i=permissions.size()-1; i>=0; i--) {
2843                permissions.get(i).setPackageName(newName);
2844            }
2845            for (int i=permissionGroups.size()-1; i>=0; i--) {
2846                permissionGroups.get(i).setPackageName(newName);
2847            }
2848            for (int i=activities.size()-1; i>=0; i--) {
2849                activities.get(i).setPackageName(newName);
2850            }
2851            for (int i=receivers.size()-1; i>=0; i--) {
2852                receivers.get(i).setPackageName(newName);
2853            }
2854            for (int i=providers.size()-1; i>=0; i--) {
2855                providers.get(i).setPackageName(newName);
2856            }
2857            for (int i=services.size()-1; i>=0; i--) {
2858                services.get(i).setPackageName(newName);
2859            }
2860            for (int i=instrumentation.size()-1; i>=0; i--) {
2861                instrumentation.get(i).setPackageName(newName);
2862            }
2863        }
2864
2865        public String toString() {
2866            return "Package{"
2867                + Integer.toHexString(System.identityHashCode(this))
2868                + " " + packageName + "}";
2869        }
2870    }
2871
2872    public static class Component<II extends IntentInfo> {
2873        public final Package owner;
2874        public final ArrayList<II> intents;
2875        public final String className;
2876        public Bundle metaData;
2877
2878        ComponentName componentName;
2879        String componentShortName;
2880
2881        public Component(Package _owner) {
2882            owner = _owner;
2883            intents = null;
2884            className = null;
2885        }
2886
2887        public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
2888            owner = args.owner;
2889            intents = new ArrayList<II>(0);
2890            String name = args.sa.getNonConfigurationString(args.nameRes, 0);
2891            if (name == null) {
2892                className = null;
2893                args.outError[0] = args.tag + " does not specify android:name";
2894                return;
2895            }
2896
2897            outInfo.name
2898                = buildClassName(owner.applicationInfo.packageName, name, args.outError);
2899            if (outInfo.name == null) {
2900                className = null;
2901                args.outError[0] = args.tag + " does not have valid android:name";
2902                return;
2903            }
2904
2905            className = outInfo.name;
2906
2907            int iconVal = args.sa.getResourceId(args.iconRes, 0);
2908            if (iconVal != 0) {
2909                outInfo.icon = iconVal;
2910                outInfo.nonLocalizedLabel = null;
2911            }
2912
2913            int logoVal = args.sa.getResourceId(args.logoRes, 0);
2914            if (logoVal != 0) {
2915                outInfo.logo = logoVal;
2916            }
2917
2918            TypedValue v = args.sa.peekValue(args.labelRes);
2919            if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2920                outInfo.nonLocalizedLabel = v.coerceToString();
2921            }
2922
2923            outInfo.packageName = owner.packageName;
2924        }
2925
2926        public Component(final ParseComponentArgs args, final ComponentInfo outInfo) {
2927            this(args, (PackageItemInfo)outInfo);
2928            if (args.outError[0] != null) {
2929                return;
2930            }
2931
2932            if (args.processRes != 0) {
2933                CharSequence pname;
2934                if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2935                    pname = args.sa.getNonConfigurationString(args.processRes, 0);
2936                } else {
2937                    // Some older apps have been seen to use a resource reference
2938                    // here that on older builds was ignored (with a warning).  We
2939                    // need to continue to do this for them so they don't break.
2940                    pname = args.sa.getNonResourceString(args.processRes);
2941                }
2942                outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
2943                        owner.applicationInfo.processName, pname,
2944                        args.flags, args.sepProcesses, args.outError);
2945            }
2946
2947            if (args.descriptionRes != 0) {
2948                outInfo.descriptionRes = args.sa.getResourceId(args.descriptionRes, 0);
2949            }
2950
2951            outInfo.enabled = args.sa.getBoolean(args.enabledRes, true);
2952        }
2953
2954        public Component(Component<II> clone) {
2955            owner = clone.owner;
2956            intents = clone.intents;
2957            className = clone.className;
2958            componentName = clone.componentName;
2959            componentShortName = clone.componentShortName;
2960        }
2961
2962        public ComponentName getComponentName() {
2963            if (componentName != null) {
2964                return componentName;
2965            }
2966            if (className != null) {
2967                componentName = new ComponentName(owner.applicationInfo.packageName,
2968                        className);
2969            }
2970            return componentName;
2971        }
2972
2973        public String getComponentShortName() {
2974            if (componentShortName != null) {
2975                return componentShortName;
2976            }
2977            ComponentName component = getComponentName();
2978            if (component != null) {
2979                componentShortName = component.flattenToShortString();
2980            }
2981            return componentShortName;
2982        }
2983
2984        public void setPackageName(String packageName) {
2985            componentName = null;
2986            componentShortName = null;
2987        }
2988    }
2989
2990    public final static class Permission extends Component<IntentInfo> {
2991        public final PermissionInfo info;
2992        public boolean tree;
2993        public PermissionGroup group;
2994
2995        public Permission(Package _owner) {
2996            super(_owner);
2997            info = new PermissionInfo();
2998        }
2999
3000        public Permission(Package _owner, PermissionInfo _info) {
3001            super(_owner);
3002            info = _info;
3003        }
3004
3005        public void setPackageName(String packageName) {
3006            super.setPackageName(packageName);
3007            info.packageName = packageName;
3008        }
3009
3010        public String toString() {
3011            return "Permission{"
3012                + Integer.toHexString(System.identityHashCode(this))
3013                + " " + info.name + "}";
3014        }
3015    }
3016
3017    public final static class PermissionGroup extends Component<IntentInfo> {
3018        public final PermissionGroupInfo info;
3019
3020        public PermissionGroup(Package _owner) {
3021            super(_owner);
3022            info = new PermissionGroupInfo();
3023        }
3024
3025        public PermissionGroup(Package _owner, PermissionGroupInfo _info) {
3026            super(_owner);
3027            info = _info;
3028        }
3029
3030        public void setPackageName(String packageName) {
3031            super.setPackageName(packageName);
3032            info.packageName = packageName;
3033        }
3034
3035        public String toString() {
3036            return "PermissionGroup{"
3037                + Integer.toHexString(System.identityHashCode(this))
3038                + " " + info.name + "}";
3039        }
3040    }
3041
3042    private static boolean copyNeeded(int flags, Package p, Bundle metaData) {
3043        if (p.mSetEnabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
3044            boolean enabled = p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
3045            if (p.applicationInfo.enabled != enabled) {
3046                return true;
3047            }
3048        }
3049        if ((flags & PackageManager.GET_META_DATA) != 0
3050                && (metaData != null || p.mAppMetaData != null)) {
3051            return true;
3052        }
3053        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0
3054                && p.usesLibraryFiles != null) {
3055            return true;
3056        }
3057        return false;
3058    }
3059
3060    public static ApplicationInfo generateApplicationInfo(Package p, int flags) {
3061        if (p == null) return null;
3062        if (!copyNeeded(flags, p, null)) {
3063            // CompatibilityMode is global state. It's safe to modify the instance
3064            // of the package.
3065            if (!sCompatibilityModeEnabled) {
3066                p.applicationInfo.disableCompatibilityMode();
3067            }
3068            return p.applicationInfo;
3069        }
3070
3071        // Make shallow copy so we can store the metadata/libraries safely
3072        ApplicationInfo ai = new ApplicationInfo(p.applicationInfo);
3073        if ((flags & PackageManager.GET_META_DATA) != 0) {
3074            ai.metaData = p.mAppMetaData;
3075        }
3076        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0) {
3077            ai.sharedLibraryFiles = p.usesLibraryFiles;
3078        }
3079        if (!sCompatibilityModeEnabled) {
3080            ai.disableCompatibilityMode();
3081        }
3082        ai.enabled = p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
3083        return ai;
3084    }
3085
3086    public static final PermissionInfo generatePermissionInfo(
3087            Permission p, int flags) {
3088        if (p == null) return null;
3089        if ((flags&PackageManager.GET_META_DATA) == 0) {
3090            return p.info;
3091        }
3092        PermissionInfo pi = new PermissionInfo(p.info);
3093        pi.metaData = p.metaData;
3094        return pi;
3095    }
3096
3097    public static final PermissionGroupInfo generatePermissionGroupInfo(
3098            PermissionGroup pg, int flags) {
3099        if (pg == null) return null;
3100        if ((flags&PackageManager.GET_META_DATA) == 0) {
3101            return pg.info;
3102        }
3103        PermissionGroupInfo pgi = new PermissionGroupInfo(pg.info);
3104        pgi.metaData = pg.metaData;
3105        return pgi;
3106    }
3107
3108    public final static class Activity extends Component<ActivityIntentInfo> {
3109        public final ActivityInfo info;
3110
3111        public Activity(final ParseComponentArgs args, final ActivityInfo _info) {
3112            super(args, _info);
3113            info = _info;
3114            info.applicationInfo = args.owner.applicationInfo;
3115        }
3116
3117        public void setPackageName(String packageName) {
3118            super.setPackageName(packageName);
3119            info.packageName = packageName;
3120        }
3121
3122        public String toString() {
3123            return "Activity{"
3124                + Integer.toHexString(System.identityHashCode(this))
3125                + " " + getComponentShortName() + "}";
3126        }
3127    }
3128
3129    public static final ActivityInfo generateActivityInfo(Activity a,
3130            int flags) {
3131        if (a == null) return null;
3132        if (!copyNeeded(flags, a.owner, a.metaData)) {
3133            return a.info;
3134        }
3135        // Make shallow copies so we can store the metadata safely
3136        ActivityInfo ai = new ActivityInfo(a.info);
3137        ai.metaData = a.metaData;
3138        ai.applicationInfo = generateApplicationInfo(a.owner, flags);
3139        return ai;
3140    }
3141
3142    public final static class Service extends Component<ServiceIntentInfo> {
3143        public final ServiceInfo info;
3144
3145        public Service(final ParseComponentArgs args, final ServiceInfo _info) {
3146            super(args, _info);
3147            info = _info;
3148            info.applicationInfo = args.owner.applicationInfo;
3149        }
3150
3151        public void setPackageName(String packageName) {
3152            super.setPackageName(packageName);
3153            info.packageName = packageName;
3154        }
3155
3156        public String toString() {
3157            return "Service{"
3158                + Integer.toHexString(System.identityHashCode(this))
3159                + " " + getComponentShortName() + "}";
3160        }
3161    }
3162
3163    public static final ServiceInfo generateServiceInfo(Service s, int flags) {
3164        if (s == null) return null;
3165        if (!copyNeeded(flags, s.owner, s.metaData)) {
3166            return s.info;
3167        }
3168        // Make shallow copies so we can store the metadata safely
3169        ServiceInfo si = new ServiceInfo(s.info);
3170        si.metaData = s.metaData;
3171        si.applicationInfo = generateApplicationInfo(s.owner, flags);
3172        return si;
3173    }
3174
3175    public final static class Provider extends Component {
3176        public final ProviderInfo info;
3177        public boolean syncable;
3178
3179        public Provider(final ParseComponentArgs args, final ProviderInfo _info) {
3180            super(args, _info);
3181            info = _info;
3182            info.applicationInfo = args.owner.applicationInfo;
3183            syncable = false;
3184        }
3185
3186        public Provider(Provider existingProvider) {
3187            super(existingProvider);
3188            this.info = existingProvider.info;
3189            this.syncable = existingProvider.syncable;
3190        }
3191
3192        public void setPackageName(String packageName) {
3193            super.setPackageName(packageName);
3194            info.packageName = packageName;
3195        }
3196
3197        public String toString() {
3198            return "Provider{"
3199                + Integer.toHexString(System.identityHashCode(this))
3200                + " " + info.name + "}";
3201        }
3202    }
3203
3204    public static final ProviderInfo generateProviderInfo(Provider p,
3205            int flags) {
3206        if (p == null) return null;
3207        if (!copyNeeded(flags, p.owner, p.metaData)
3208                && ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) != 0
3209                        || p.info.uriPermissionPatterns == null)) {
3210            return p.info;
3211        }
3212        // Make shallow copies so we can store the metadata safely
3213        ProviderInfo pi = new ProviderInfo(p.info);
3214        pi.metaData = p.metaData;
3215        if ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) == 0) {
3216            pi.uriPermissionPatterns = null;
3217        }
3218        pi.applicationInfo = generateApplicationInfo(p.owner, flags);
3219        return pi;
3220    }
3221
3222    public final static class Instrumentation extends Component {
3223        public final InstrumentationInfo info;
3224
3225        public Instrumentation(final ParsePackageItemArgs args, final InstrumentationInfo _info) {
3226            super(args, _info);
3227            info = _info;
3228        }
3229
3230        public void setPackageName(String packageName) {
3231            super.setPackageName(packageName);
3232            info.packageName = packageName;
3233        }
3234
3235        public String toString() {
3236            return "Instrumentation{"
3237                + Integer.toHexString(System.identityHashCode(this))
3238                + " " + getComponentShortName() + "}";
3239        }
3240    }
3241
3242    public static final InstrumentationInfo generateInstrumentationInfo(
3243            Instrumentation i, int flags) {
3244        if (i == null) return null;
3245        if ((flags&PackageManager.GET_META_DATA) == 0) {
3246            return i.info;
3247        }
3248        InstrumentationInfo ii = new InstrumentationInfo(i.info);
3249        ii.metaData = i.metaData;
3250        return ii;
3251    }
3252
3253    public static class IntentInfo extends IntentFilter {
3254        public boolean hasDefault;
3255        public int labelRes;
3256        public CharSequence nonLocalizedLabel;
3257        public int icon;
3258        public int logo;
3259    }
3260
3261    public final static class ActivityIntentInfo extends IntentInfo {
3262        public final Activity activity;
3263
3264        public ActivityIntentInfo(Activity _activity) {
3265            activity = _activity;
3266        }
3267
3268        public String toString() {
3269            return "ActivityIntentInfo{"
3270                + Integer.toHexString(System.identityHashCode(this))
3271                + " " + activity.info.name + "}";
3272        }
3273    }
3274
3275    public final static class ServiceIntentInfo extends IntentInfo {
3276        public final Service service;
3277
3278        public ServiceIntentInfo(Service _service) {
3279            service = _service;
3280        }
3281
3282        public String toString() {
3283            return "ServiceIntentInfo{"
3284                + Integer.toHexString(System.identityHashCode(this))
3285                + " " + service.info.name + "}";
3286        }
3287    }
3288
3289    /**
3290     * @hide
3291     */
3292    public static void setCompatibilityModeEnabled(boolean compatibilityModeEnabled) {
3293        sCompatibilityModeEnabled = compatibilityModeEnabled;
3294    }
3295}
3296