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