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