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