PackageParser.java revision 546d64f56d0f930070289e26021f97638601e388
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
1003                // This is a trick to get a boolean and still able to detect
1004                // if a value was actually set.
1005                supportsSmallScreens = sa.getInteger(
1006                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_smallScreens,
1007                        supportsSmallScreens);
1008                supportsNormalScreens = sa.getInteger(
1009                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_normalScreens,
1010                        supportsNormalScreens);
1011                supportsLargeScreens = sa.getInteger(
1012                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_largeScreens,
1013                        supportsLargeScreens);
1014                supportsXLargeScreens = sa.getInteger(
1015                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_xlargeScreens,
1016                        supportsXLargeScreens);
1017                resizeable = sa.getInteger(
1018                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_resizeable,
1019                        resizeable);
1020                anyDensity = sa.getInteger(
1021                        com.android.internal.R.styleable.AndroidManifestSupportsScreens_anyDensity,
1022                        anyDensity);
1023
1024                sa.recycle();
1025
1026                XmlUtils.skipCurrentTag(parser);
1027
1028            } else if (tagName.equals("protected-broadcast")) {
1029                sa = res.obtainAttributes(attrs,
1030                        com.android.internal.R.styleable.AndroidManifestProtectedBroadcast);
1031
1032                // Note: don't allow this value to be a reference to a resource
1033                // that may change.
1034                String name = sa.getNonResourceString(
1035                        com.android.internal.R.styleable.AndroidManifestProtectedBroadcast_name);
1036
1037                sa.recycle();
1038
1039                if (name != null && (flags&PARSE_IS_SYSTEM) != 0) {
1040                    if (pkg.protectedBroadcasts == null) {
1041                        pkg.protectedBroadcasts = new ArrayList<String>();
1042                    }
1043                    if (!pkg.protectedBroadcasts.contains(name)) {
1044                        pkg.protectedBroadcasts.add(name.intern());
1045                    }
1046                }
1047
1048                XmlUtils.skipCurrentTag(parser);
1049
1050            } else if (tagName.equals("instrumentation")) {
1051                if (parseInstrumentation(pkg, res, parser, attrs, outError) == null) {
1052                    return null;
1053                }
1054
1055            } else if (tagName.equals("original-package")) {
1056                sa = res.obtainAttributes(attrs,
1057                        com.android.internal.R.styleable.AndroidManifestOriginalPackage);
1058
1059                String orig =sa.getNonConfigurationString(
1060                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
1061                if (!pkg.packageName.equals(orig)) {
1062                    if (pkg.mOriginalPackages == null) {
1063                        pkg.mOriginalPackages = new ArrayList<String>();
1064                        pkg.mRealPackage = pkg.packageName;
1065                    }
1066                    pkg.mOriginalPackages.add(orig);
1067                }
1068
1069                sa.recycle();
1070
1071                XmlUtils.skipCurrentTag(parser);
1072
1073            } else if (tagName.equals("adopt-permissions")) {
1074                sa = res.obtainAttributes(attrs,
1075                        com.android.internal.R.styleable.AndroidManifestOriginalPackage);
1076
1077                String name = sa.getNonConfigurationString(
1078                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
1079
1080                sa.recycle();
1081
1082                if (name != null) {
1083                    if (pkg.mAdoptPermissions == null) {
1084                        pkg.mAdoptPermissions = new ArrayList<String>();
1085                    }
1086                    pkg.mAdoptPermissions.add(name);
1087                }
1088
1089                XmlUtils.skipCurrentTag(parser);
1090
1091            } else if (tagName.equals("uses-gl-texture")) {
1092                // Just skip this tag
1093                XmlUtils.skipCurrentTag(parser);
1094                continue;
1095
1096            } else if (tagName.equals("compatible-screens")) {
1097                // Just skip this tag
1098                XmlUtils.skipCurrentTag(parser);
1099                continue;
1100
1101            } else if (tagName.equals("eat-comment")) {
1102                // Just skip this tag
1103                XmlUtils.skipCurrentTag(parser);
1104                continue;
1105
1106            } else if (RIGID_PARSER) {
1107                outError[0] = "Bad element under <manifest>: "
1108                    + parser.getName();
1109                mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1110                return null;
1111
1112            } else {
1113                Log.w(TAG, "Unknown element under <manifest>: " + parser.getName()
1114                        + " at " + mArchiveSourcePath + " "
1115                        + parser.getPositionDescription());
1116                XmlUtils.skipCurrentTag(parser);
1117                continue;
1118            }
1119        }
1120
1121        if (!foundApp && pkg.instrumentation.size() == 0) {
1122            outError[0] = "<manifest> does not contain an <application> or <instrumentation>";
1123            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_EMPTY;
1124        }
1125
1126        final int NP = PackageParser.NEW_PERMISSIONS.length;
1127        StringBuilder implicitPerms = null;
1128        for (int ip=0; ip<NP; ip++) {
1129            final PackageParser.NewPermissionInfo npi
1130                    = PackageParser.NEW_PERMISSIONS[ip];
1131            if (pkg.applicationInfo.targetSdkVersion >= npi.sdkVersion) {
1132                break;
1133            }
1134            if (!pkg.requestedPermissions.contains(npi.name)) {
1135                if (implicitPerms == null) {
1136                    implicitPerms = new StringBuilder(128);
1137                    implicitPerms.append(pkg.packageName);
1138                    implicitPerms.append(": compat added ");
1139                } else {
1140                    implicitPerms.append(' ');
1141                }
1142                implicitPerms.append(npi.name);
1143                pkg.requestedPermissions.add(npi.name);
1144            }
1145        }
1146        if (implicitPerms != null) {
1147            Log.i(TAG, implicitPerms.toString());
1148        }
1149
1150        if (supportsSmallScreens < 0 || (supportsSmallScreens > 0
1151                && pkg.applicationInfo.targetSdkVersion
1152                        >= android.os.Build.VERSION_CODES.DONUT)) {
1153            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS;
1154        }
1155        if (supportsNormalScreens != 0) {
1156            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS;
1157        }
1158        if (supportsLargeScreens < 0 || (supportsLargeScreens > 0
1159                && pkg.applicationInfo.targetSdkVersion
1160                        >= android.os.Build.VERSION_CODES.DONUT)) {
1161            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS;
1162        }
1163        if (supportsXLargeScreens < 0 || (supportsXLargeScreens > 0
1164                && pkg.applicationInfo.targetSdkVersion
1165                        >= android.os.Build.VERSION_CODES.GINGERBREAD)) {
1166            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS;
1167        }
1168        if (resizeable < 0 || (resizeable > 0
1169                && pkg.applicationInfo.targetSdkVersion
1170                        >= android.os.Build.VERSION_CODES.DONUT)) {
1171            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS;
1172        }
1173        if (anyDensity < 0 || (anyDensity > 0
1174                && pkg.applicationInfo.targetSdkVersion
1175                        >= android.os.Build.VERSION_CODES.DONUT)) {
1176            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES;
1177        }
1178
1179        return pkg;
1180    }
1181
1182    private static String buildClassName(String pkg, CharSequence clsSeq,
1183            String[] outError) {
1184        if (clsSeq == null || clsSeq.length() <= 0) {
1185            outError[0] = "Empty class name in package " + pkg;
1186            return null;
1187        }
1188        String cls = clsSeq.toString();
1189        char c = cls.charAt(0);
1190        if (c == '.') {
1191            return (pkg + cls).intern();
1192        }
1193        if (cls.indexOf('.') < 0) {
1194            StringBuilder b = new StringBuilder(pkg);
1195            b.append('.');
1196            b.append(cls);
1197            return b.toString().intern();
1198        }
1199        if (c >= 'a' && c <= 'z') {
1200            return cls.intern();
1201        }
1202        outError[0] = "Bad class name " + cls + " in package " + pkg;
1203        return null;
1204    }
1205
1206    private static String buildCompoundName(String pkg,
1207            CharSequence procSeq, String type, String[] outError) {
1208        String proc = procSeq.toString();
1209        char c = proc.charAt(0);
1210        if (pkg != null && c == ':') {
1211            if (proc.length() < 2) {
1212                outError[0] = "Bad " + type + " name " + proc + " in package " + pkg
1213                        + ": must be at least two characters";
1214                return null;
1215            }
1216            String subName = proc.substring(1);
1217            String nameError = validateName(subName, false);
1218            if (nameError != null) {
1219                outError[0] = "Invalid " + type + " name " + proc + " in package "
1220                        + pkg + ": " + nameError;
1221                return null;
1222            }
1223            return (pkg + proc).intern();
1224        }
1225        String nameError = validateName(proc, true);
1226        if (nameError != null && !"system".equals(proc)) {
1227            outError[0] = "Invalid " + type + " name " + proc + " in package "
1228                    + pkg + ": " + nameError;
1229            return null;
1230        }
1231        return proc.intern();
1232    }
1233
1234    private static String buildProcessName(String pkg, String defProc,
1235            CharSequence procSeq, int flags, String[] separateProcesses,
1236            String[] outError) {
1237        if ((flags&PARSE_IGNORE_PROCESSES) != 0 && !"system".equals(procSeq)) {
1238            return defProc != null ? defProc : pkg;
1239        }
1240        if (separateProcesses != null) {
1241            for (int i=separateProcesses.length-1; i>=0; i--) {
1242                String sp = separateProcesses[i];
1243                if (sp.equals(pkg) || sp.equals(defProc) || sp.equals(procSeq)) {
1244                    return pkg;
1245                }
1246            }
1247        }
1248        if (procSeq == null || procSeq.length() <= 0) {
1249            return defProc;
1250        }
1251        return buildCompoundName(pkg, procSeq, "process", outError);
1252    }
1253
1254    private static String buildTaskAffinityName(String pkg, String defProc,
1255            CharSequence procSeq, String[] outError) {
1256        if (procSeq == null) {
1257            return defProc;
1258        }
1259        if (procSeq.length() <= 0) {
1260            return null;
1261        }
1262        return buildCompoundName(pkg, procSeq, "taskAffinity", outError);
1263    }
1264
1265    private PermissionGroup parsePermissionGroup(Package owner, Resources res,
1266            XmlPullParser parser, AttributeSet attrs, String[] outError)
1267        throws XmlPullParserException, IOException {
1268        PermissionGroup perm = new PermissionGroup(owner);
1269
1270        TypedArray sa = res.obtainAttributes(attrs,
1271                com.android.internal.R.styleable.AndroidManifestPermissionGroup);
1272
1273        if (!parsePackageItemInfo(owner, perm.info, outError,
1274                "<permission-group>", sa,
1275                com.android.internal.R.styleable.AndroidManifestPermissionGroup_name,
1276                com.android.internal.R.styleable.AndroidManifestPermissionGroup_label,
1277                com.android.internal.R.styleable.AndroidManifestPermissionGroup_icon,
1278                com.android.internal.R.styleable.AndroidManifestPermissionGroup_logo)) {
1279            sa.recycle();
1280            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1281            return null;
1282        }
1283
1284        perm.info.descriptionRes = sa.getResourceId(
1285                com.android.internal.R.styleable.AndroidManifestPermissionGroup_description,
1286                0);
1287
1288        sa.recycle();
1289
1290        if (!parseAllMetaData(res, parser, attrs, "<permission-group>", perm,
1291                outError)) {
1292            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1293            return null;
1294        }
1295
1296        owner.permissionGroups.add(perm);
1297
1298        return perm;
1299    }
1300
1301    private Permission parsePermission(Package owner, Resources res,
1302            XmlPullParser parser, AttributeSet attrs, String[] outError)
1303        throws XmlPullParserException, IOException {
1304        Permission perm = new Permission(owner);
1305
1306        TypedArray sa = res.obtainAttributes(attrs,
1307                com.android.internal.R.styleable.AndroidManifestPermission);
1308
1309        if (!parsePackageItemInfo(owner, perm.info, outError,
1310                "<permission>", sa,
1311                com.android.internal.R.styleable.AndroidManifestPermission_name,
1312                com.android.internal.R.styleable.AndroidManifestPermission_label,
1313                com.android.internal.R.styleable.AndroidManifestPermission_icon,
1314                com.android.internal.R.styleable.AndroidManifestPermission_logo)) {
1315            sa.recycle();
1316            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1317            return null;
1318        }
1319
1320        // Note: don't allow this value to be a reference to a resource
1321        // that may change.
1322        perm.info.group = sa.getNonResourceString(
1323                com.android.internal.R.styleable.AndroidManifestPermission_permissionGroup);
1324        if (perm.info.group != null) {
1325            perm.info.group = perm.info.group.intern();
1326        }
1327
1328        perm.info.descriptionRes = sa.getResourceId(
1329                com.android.internal.R.styleable.AndroidManifestPermission_description,
1330                0);
1331
1332        perm.info.protectionLevel = sa.getInt(
1333                com.android.internal.R.styleable.AndroidManifestPermission_protectionLevel,
1334                PermissionInfo.PROTECTION_NORMAL);
1335
1336        sa.recycle();
1337
1338        if (perm.info.protectionLevel == -1) {
1339            outError[0] = "<permission> does not specify protectionLevel";
1340            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1341            return null;
1342        }
1343
1344        if (!parseAllMetaData(res, parser, attrs, "<permission>", perm,
1345                outError)) {
1346            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1347            return null;
1348        }
1349
1350        owner.permissions.add(perm);
1351
1352        return perm;
1353    }
1354
1355    private Permission parsePermissionTree(Package owner, Resources res,
1356            XmlPullParser parser, AttributeSet attrs, String[] outError)
1357        throws XmlPullParserException, IOException {
1358        Permission perm = new Permission(owner);
1359
1360        TypedArray sa = res.obtainAttributes(attrs,
1361                com.android.internal.R.styleable.AndroidManifestPermissionTree);
1362
1363        if (!parsePackageItemInfo(owner, perm.info, outError,
1364                "<permission-tree>", sa,
1365                com.android.internal.R.styleable.AndroidManifestPermissionTree_name,
1366                com.android.internal.R.styleable.AndroidManifestPermissionTree_label,
1367                com.android.internal.R.styleable.AndroidManifestPermissionTree_icon,
1368                com.android.internal.R.styleable.AndroidManifestPermissionTree_logo)) {
1369            sa.recycle();
1370            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1371            return null;
1372        }
1373
1374        sa.recycle();
1375
1376        int index = perm.info.name.indexOf('.');
1377        if (index > 0) {
1378            index = perm.info.name.indexOf('.', index+1);
1379        }
1380        if (index < 0) {
1381            outError[0] = "<permission-tree> name has less than three segments: "
1382                + perm.info.name;
1383            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1384            return null;
1385        }
1386
1387        perm.info.descriptionRes = 0;
1388        perm.info.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
1389        perm.tree = true;
1390
1391        if (!parseAllMetaData(res, parser, attrs, "<permission-tree>", perm,
1392                outError)) {
1393            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1394            return null;
1395        }
1396
1397        owner.permissions.add(perm);
1398
1399        return perm;
1400    }
1401
1402    private Instrumentation parseInstrumentation(Package owner, Resources res,
1403            XmlPullParser parser, AttributeSet attrs, String[] outError)
1404        throws XmlPullParserException, IOException {
1405        TypedArray sa = res.obtainAttributes(attrs,
1406                com.android.internal.R.styleable.AndroidManifestInstrumentation);
1407
1408        if (mParseInstrumentationArgs == null) {
1409            mParseInstrumentationArgs = new ParsePackageItemArgs(owner, outError,
1410                    com.android.internal.R.styleable.AndroidManifestInstrumentation_name,
1411                    com.android.internal.R.styleable.AndroidManifestInstrumentation_label,
1412                    com.android.internal.R.styleable.AndroidManifestInstrumentation_icon,
1413                    com.android.internal.R.styleable.AndroidManifestInstrumentation_logo);
1414            mParseInstrumentationArgs.tag = "<instrumentation>";
1415        }
1416
1417        mParseInstrumentationArgs.sa = sa;
1418
1419        Instrumentation a = new Instrumentation(mParseInstrumentationArgs,
1420                new InstrumentationInfo());
1421        if (outError[0] != null) {
1422            sa.recycle();
1423            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1424            return null;
1425        }
1426
1427        String str;
1428        // Note: don't allow this value to be a reference to a resource
1429        // that may change.
1430        str = sa.getNonResourceString(
1431                com.android.internal.R.styleable.AndroidManifestInstrumentation_targetPackage);
1432        a.info.targetPackage = str != null ? str.intern() : null;
1433
1434        a.info.handleProfiling = sa.getBoolean(
1435                com.android.internal.R.styleable.AndroidManifestInstrumentation_handleProfiling,
1436                false);
1437
1438        a.info.functionalTest = sa.getBoolean(
1439                com.android.internal.R.styleable.AndroidManifestInstrumentation_functionalTest,
1440                false);
1441
1442        sa.recycle();
1443
1444        if (a.info.targetPackage == null) {
1445            outError[0] = "<instrumentation> does not specify targetPackage";
1446            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1447            return null;
1448        }
1449
1450        if (!parseAllMetaData(res, parser, attrs, "<instrumentation>", a,
1451                outError)) {
1452            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1453            return null;
1454        }
1455
1456        owner.instrumentation.add(a);
1457
1458        return a;
1459    }
1460
1461    private boolean parseApplication(Package owner, Resources res,
1462            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
1463        throws XmlPullParserException, IOException {
1464        final ApplicationInfo ai = owner.applicationInfo;
1465        final String pkgName = owner.applicationInfo.packageName;
1466
1467        TypedArray sa = res.obtainAttributes(attrs,
1468                com.android.internal.R.styleable.AndroidManifestApplication);
1469
1470        String name = sa.getNonConfigurationString(
1471                com.android.internal.R.styleable.AndroidManifestApplication_name, 0);
1472        if (name != null) {
1473            ai.className = buildClassName(pkgName, name, outError);
1474            if (ai.className == null) {
1475                sa.recycle();
1476                mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1477                return false;
1478            }
1479        }
1480
1481        String manageSpaceActivity = sa.getNonConfigurationString(
1482                com.android.internal.R.styleable.AndroidManifestApplication_manageSpaceActivity, 0);
1483        if (manageSpaceActivity != null) {
1484            ai.manageSpaceActivityName = buildClassName(pkgName, manageSpaceActivity,
1485                    outError);
1486        }
1487
1488        boolean allowBackup = sa.getBoolean(
1489                com.android.internal.R.styleable.AndroidManifestApplication_allowBackup, true);
1490        if (allowBackup) {
1491            ai.flags |= ApplicationInfo.FLAG_ALLOW_BACKUP;
1492
1493            // backupAgent, killAfterRestore, and restoreAnyVersion are only relevant
1494            // if backup is possible for the given application.
1495            String backupAgent = sa.getNonConfigurationString(
1496                    com.android.internal.R.styleable.AndroidManifestApplication_backupAgent, 0);
1497            if (backupAgent != null) {
1498                ai.backupAgentName = buildClassName(pkgName, backupAgent, outError);
1499                if (false) {
1500                    Log.v(TAG, "android:backupAgent = " + ai.backupAgentName
1501                            + " from " + pkgName + "+" + backupAgent);
1502                }
1503
1504                if (sa.getBoolean(
1505                        com.android.internal.R.styleable.AndroidManifestApplication_killAfterRestore,
1506                        true)) {
1507                    ai.flags |= ApplicationInfo.FLAG_KILL_AFTER_RESTORE;
1508                }
1509                if (sa.getBoolean(
1510                        com.android.internal.R.styleable.AndroidManifestApplication_restoreAnyVersion,
1511                        false)) {
1512                    ai.flags |= ApplicationInfo.FLAG_RESTORE_ANY_VERSION;
1513                }
1514            }
1515        }
1516
1517        name = sa.getNonConfigurationString(
1518                com.android.internal.R.styleable.AndroidManifestApplication_fullBackupAgent, 0);
1519        if (name != null) {
1520            ai.fullBackupAgentName = buildClassName(pkgName, name, outError);
1521            if (true) {
1522                Log.v(TAG, "android:fullBackupAgent=" + ai.fullBackupAgentName
1523                        + " from " + pkgName + "+" + name);
1524            }
1525        }
1526
1527        TypedValue v = sa.peekValue(
1528                com.android.internal.R.styleable.AndroidManifestApplication_label);
1529        if (v != null && (ai.labelRes=v.resourceId) == 0) {
1530            ai.nonLocalizedLabel = v.coerceToString();
1531        }
1532
1533        ai.icon = sa.getResourceId(
1534                com.android.internal.R.styleable.AndroidManifestApplication_icon, 0);
1535        ai.logo = sa.getResourceId(
1536                com.android.internal.R.styleable.AndroidManifestApplication_logo, 0);
1537        ai.theme = sa.getResourceId(
1538                com.android.internal.R.styleable.AndroidManifestApplication_theme, 0);
1539        ai.descriptionRes = sa.getResourceId(
1540                com.android.internal.R.styleable.AndroidManifestApplication_description, 0);
1541
1542        if ((flags&PARSE_IS_SYSTEM) != 0) {
1543            if (sa.getBoolean(
1544                    com.android.internal.R.styleable.AndroidManifestApplication_persistent,
1545                    false)) {
1546                ai.flags |= ApplicationInfo.FLAG_PERSISTENT;
1547            }
1548        }
1549
1550        if ((flags & PARSE_FORWARD_LOCK) != 0) {
1551            ai.flags |= ApplicationInfo.FLAG_FORWARD_LOCK;
1552        }
1553
1554        if ((flags & PARSE_ON_SDCARD) != 0) {
1555            ai.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
1556        }
1557
1558        if (sa.getBoolean(
1559                com.android.internal.R.styleable.AndroidManifestApplication_debuggable,
1560                false)) {
1561            ai.flags |= ApplicationInfo.FLAG_DEBUGGABLE;
1562        }
1563
1564        if (sa.getBoolean(
1565                com.android.internal.R.styleable.AndroidManifestApplication_vmSafeMode,
1566                false)) {
1567            ai.flags |= ApplicationInfo.FLAG_VM_SAFE_MODE;
1568        }
1569
1570        boolean hardwareAccelerated = sa.getBoolean(
1571                com.android.internal.R.styleable.AndroidManifestApplication_hardwareAccelerated,
1572                false);
1573
1574        if (sa.getBoolean(
1575                com.android.internal.R.styleable.AndroidManifestApplication_hasCode,
1576                true)) {
1577            ai.flags |= ApplicationInfo.FLAG_HAS_CODE;
1578        }
1579
1580        if (sa.getBoolean(
1581                com.android.internal.R.styleable.AndroidManifestApplication_allowTaskReparenting,
1582                false)) {
1583            ai.flags |= ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING;
1584        }
1585
1586        if (sa.getBoolean(
1587                com.android.internal.R.styleable.AndroidManifestApplication_allowClearUserData,
1588                true)) {
1589            ai.flags |= ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA;
1590        }
1591
1592        if (sa.getBoolean(
1593                com.android.internal.R.styleable.AndroidManifestApplication_testOnly,
1594                false)) {
1595            ai.flags |= ApplicationInfo.FLAG_TEST_ONLY;
1596        }
1597
1598        if (sa.getBoolean(
1599                com.android.internal.R.styleable.AndroidManifestApplication_largeHeap,
1600                false)) {
1601            ai.flags |= ApplicationInfo.FLAG_LARGE_HEAP;
1602        }
1603
1604        String str;
1605        str = sa.getNonConfigurationString(
1606                com.android.internal.R.styleable.AndroidManifestApplication_permission, 0);
1607        ai.permission = (str != null && str.length() > 0) ? str.intern() : null;
1608
1609        if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1610            str = sa.getNonConfigurationString(
1611                    com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity, 0);
1612        } else {
1613            // Some older apps have been seen to use a resource reference
1614            // here that on older builds was ignored (with a warning).  We
1615            // need to continue to do this for them so they don't break.
1616            str = sa.getNonResourceString(
1617                    com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity);
1618        }
1619        ai.taskAffinity = buildTaskAffinityName(ai.packageName, ai.packageName,
1620                str, outError);
1621
1622        if (outError[0] == null) {
1623            CharSequence pname;
1624            if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1625                pname = sa.getNonConfigurationString(
1626                        com.android.internal.R.styleable.AndroidManifestApplication_process, 0);
1627            } else {
1628                // Some older apps have been seen to use a resource reference
1629                // here that on older builds was ignored (with a warning).  We
1630                // need to continue to do this for them so they don't break.
1631                pname = sa.getNonResourceString(
1632                        com.android.internal.R.styleable.AndroidManifestApplication_process);
1633            }
1634            ai.processName = buildProcessName(ai.packageName, null, pname,
1635                    flags, mSeparateProcesses, outError);
1636
1637            ai.enabled = sa.getBoolean(
1638                    com.android.internal.R.styleable.AndroidManifestApplication_enabled, true);
1639
1640            if (false) {
1641                if (sa.getBoolean(
1642                        com.android.internal.R.styleable.AndroidManifestApplication_cantSaveState,
1643                        false)) {
1644                    ai.flags |= ApplicationInfo.FLAG_CANT_SAVE_STATE;
1645
1646                    // A heavy-weight application can not be in a custom process.
1647                    // We can do direct compare because we intern all strings.
1648                    if (ai.processName != null && ai.processName != ai.packageName) {
1649                        outError[0] = "cantSaveState applications can not use custom processes";
1650                    }
1651                }
1652            }
1653        }
1654
1655        sa.recycle();
1656
1657        if (outError[0] != null) {
1658            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1659            return false;
1660        }
1661
1662        final int innerDepth = parser.getDepth();
1663
1664        int type;
1665        while ((type=parser.next()) != parser.END_DOCUMENT
1666               && (type != parser.END_TAG || parser.getDepth() > innerDepth)) {
1667            if (type == parser.END_TAG || type == parser.TEXT) {
1668                continue;
1669            }
1670
1671            String tagName = parser.getName();
1672            if (tagName.equals("activity")) {
1673                Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false,
1674                        hardwareAccelerated);
1675                if (a == null) {
1676                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1677                    return false;
1678                }
1679
1680                owner.activities.add(a);
1681
1682            } else if (tagName.equals("receiver")) {
1683                Activity a = parseActivity(owner, res, parser, attrs, flags, outError, true, false);
1684                if (a == null) {
1685                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1686                    return false;
1687                }
1688
1689                owner.receivers.add(a);
1690
1691            } else if (tagName.equals("service")) {
1692                Service s = parseService(owner, res, parser, attrs, flags, outError);
1693                if (s == null) {
1694                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1695                    return false;
1696                }
1697
1698                owner.services.add(s);
1699
1700            } else if (tagName.equals("provider")) {
1701                Provider p = parseProvider(owner, res, parser, attrs, flags, outError);
1702                if (p == null) {
1703                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1704                    return false;
1705                }
1706
1707                owner.providers.add(p);
1708
1709            } else if (tagName.equals("activity-alias")) {
1710                Activity a = parseActivityAlias(owner, res, parser, attrs, flags, outError);
1711                if (a == null) {
1712                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1713                    return false;
1714                }
1715
1716                owner.activities.add(a);
1717
1718            } else if (parser.getName().equals("meta-data")) {
1719                // note: application meta-data is stored off to the side, so it can
1720                // remain null in the primary copy (we like to avoid extra copies because
1721                // it can be large)
1722                if ((owner.mAppMetaData = parseMetaData(res, parser, attrs, owner.mAppMetaData,
1723                        outError)) == null) {
1724                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1725                    return false;
1726                }
1727
1728            } else if (tagName.equals("uses-library")) {
1729                sa = res.obtainAttributes(attrs,
1730                        com.android.internal.R.styleable.AndroidManifestUsesLibrary);
1731
1732                // Note: don't allow this value to be a reference to a resource
1733                // that may change.
1734                String lname = sa.getNonResourceString(
1735                        com.android.internal.R.styleable.AndroidManifestUsesLibrary_name);
1736                boolean req = sa.getBoolean(
1737                        com.android.internal.R.styleable.AndroidManifestUsesLibrary_required,
1738                        true);
1739
1740                sa.recycle();
1741
1742                if (lname != null) {
1743                    if (req) {
1744                        if (owner.usesLibraries == null) {
1745                            owner.usesLibraries = new ArrayList<String>();
1746                        }
1747                        if (!owner.usesLibraries.contains(lname)) {
1748                            owner.usesLibraries.add(lname.intern());
1749                        }
1750                    } else {
1751                        if (owner.usesOptionalLibraries == null) {
1752                            owner.usesOptionalLibraries = new ArrayList<String>();
1753                        }
1754                        if (!owner.usesOptionalLibraries.contains(lname)) {
1755                            owner.usesOptionalLibraries.add(lname.intern());
1756                        }
1757                    }
1758                }
1759
1760                XmlUtils.skipCurrentTag(parser);
1761
1762            } else if (tagName.equals("uses-package")) {
1763                // Dependencies for app installers; we don't currently try to
1764                // enforce this.
1765                XmlUtils.skipCurrentTag(parser);
1766
1767            } else {
1768                if (!RIGID_PARSER) {
1769                    Log.w(TAG, "Unknown element under <application>: " + tagName
1770                            + " at " + mArchiveSourcePath + " "
1771                            + parser.getPositionDescription());
1772                    XmlUtils.skipCurrentTag(parser);
1773                    continue;
1774                } else {
1775                    outError[0] = "Bad element under <application>: " + tagName;
1776                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1777                    return false;
1778                }
1779            }
1780        }
1781
1782        return true;
1783    }
1784
1785    private boolean parsePackageItemInfo(Package owner, PackageItemInfo outInfo,
1786            String[] outError, String tag, TypedArray sa,
1787            int nameRes, int labelRes, int iconRes, int logoRes) {
1788        String name = sa.getNonConfigurationString(nameRes, 0);
1789        if (name == null) {
1790            outError[0] = tag + " does not specify android:name";
1791            return false;
1792        }
1793
1794        outInfo.name
1795            = buildClassName(owner.applicationInfo.packageName, name, outError);
1796        if (outInfo.name == null) {
1797            return false;
1798        }
1799
1800        int iconVal = sa.getResourceId(iconRes, 0);
1801        if (iconVal != 0) {
1802            outInfo.icon = iconVal;
1803            outInfo.nonLocalizedLabel = null;
1804        }
1805
1806        int logoVal = sa.getResourceId(logoRes, 0);
1807        if (logoVal != 0) {
1808            outInfo.logo = logoVal;
1809        }
1810
1811        TypedValue v = sa.peekValue(labelRes);
1812        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
1813            outInfo.nonLocalizedLabel = v.coerceToString();
1814        }
1815
1816        outInfo.packageName = owner.packageName;
1817
1818        return true;
1819    }
1820
1821    private Activity parseActivity(Package owner, Resources res,
1822            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError,
1823            boolean receiver, boolean hardwareAccelerated)
1824            throws XmlPullParserException, IOException {
1825        TypedArray sa = res.obtainAttributes(attrs,
1826                com.android.internal.R.styleable.AndroidManifestActivity);
1827
1828        if (mParseActivityArgs == null) {
1829            mParseActivityArgs = new ParseComponentArgs(owner, outError,
1830                    com.android.internal.R.styleable.AndroidManifestActivity_name,
1831                    com.android.internal.R.styleable.AndroidManifestActivity_label,
1832                    com.android.internal.R.styleable.AndroidManifestActivity_icon,
1833                    com.android.internal.R.styleable.AndroidManifestActivity_logo,
1834                    mSeparateProcesses,
1835                    com.android.internal.R.styleable.AndroidManifestActivity_process,
1836                    com.android.internal.R.styleable.AndroidManifestActivity_description,
1837                    com.android.internal.R.styleable.AndroidManifestActivity_enabled);
1838        }
1839
1840        mParseActivityArgs.tag = receiver ? "<receiver>" : "<activity>";
1841        mParseActivityArgs.sa = sa;
1842        mParseActivityArgs.flags = flags;
1843
1844        Activity a = new Activity(mParseActivityArgs, new ActivityInfo());
1845        if (outError[0] != null) {
1846            sa.recycle();
1847            return null;
1848        }
1849
1850        final boolean setExported = sa.hasValue(
1851                com.android.internal.R.styleable.AndroidManifestActivity_exported);
1852        if (setExported) {
1853            a.info.exported = sa.getBoolean(
1854                    com.android.internal.R.styleable.AndroidManifestActivity_exported, false);
1855        }
1856
1857        a.info.theme = sa.getResourceId(
1858                com.android.internal.R.styleable.AndroidManifestActivity_theme, 0);
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            if (owner.applicationInfo.targetSdkVersion
1952                        < android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
1953                a.info.configChanges |= ActivityInfo.CONFIG_SCREEN_SIZE
1954                        | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
1955            }
1956            a.info.softInputMode = sa.getInt(
1957                    com.android.internal.R.styleable.AndroidManifestActivity_windowSoftInputMode,
1958                    0);
1959        } else {
1960            a.info.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1961            a.info.configChanges = 0;
1962        }
1963
1964        sa.recycle();
1965
1966        if (receiver && (owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
1967            // A heavy-weight application can not have receives in its main process
1968            // We can do direct compare because we intern all strings.
1969            if (a.info.processName == owner.packageName) {
1970                outError[0] = "Heavy-weight applications can not have receivers in main process";
1971            }
1972        }
1973
1974        if (outError[0] != null) {
1975            return null;
1976        }
1977
1978        int outerDepth = parser.getDepth();
1979        int type;
1980        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1981               && (type != XmlPullParser.END_TAG
1982                       || parser.getDepth() > outerDepth)) {
1983            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1984                continue;
1985            }
1986
1987            if (parser.getName().equals("intent-filter")) {
1988                ActivityIntentInfo intent = new ActivityIntentInfo(a);
1989                if (!parseIntent(res, parser, attrs, flags, intent, outError, !receiver)) {
1990                    return null;
1991                }
1992                if (intent.countActions() == 0) {
1993                    Log.w(TAG, "No actions in intent filter at "
1994                            + mArchiveSourcePath + " "
1995                            + parser.getPositionDescription());
1996                } else {
1997                    a.intents.add(intent);
1998                }
1999            } else if (parser.getName().equals("meta-data")) {
2000                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
2001                        outError)) == null) {
2002                    return null;
2003                }
2004            } else {
2005                if (!RIGID_PARSER) {
2006                    Log.w(TAG, "Problem in package " + mArchiveSourcePath + ":");
2007                    if (receiver) {
2008                        Log.w(TAG, "Unknown element under <receiver>: " + parser.getName()
2009                                + " at " + mArchiveSourcePath + " "
2010                                + parser.getPositionDescription());
2011                    } else {
2012                        Log.w(TAG, "Unknown element under <activity>: " + parser.getName()
2013                                + " at " + mArchiveSourcePath + " "
2014                                + parser.getPositionDescription());
2015                    }
2016                    XmlUtils.skipCurrentTag(parser);
2017                    continue;
2018                }
2019                if (receiver) {
2020                    outError[0] = "Bad element under <receiver>: " + parser.getName();
2021                } else {
2022                    outError[0] = "Bad element under <activity>: " + parser.getName();
2023                }
2024                return null;
2025            }
2026        }
2027
2028        if (!setExported) {
2029            a.info.exported = a.intents.size() > 0;
2030        }
2031
2032        return a;
2033    }
2034
2035    private Activity parseActivityAlias(Package owner, Resources res,
2036            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2037            throws XmlPullParserException, IOException {
2038        TypedArray sa = res.obtainAttributes(attrs,
2039                com.android.internal.R.styleable.AndroidManifestActivityAlias);
2040
2041        String targetActivity = sa.getNonConfigurationString(
2042                com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity, 0);
2043        if (targetActivity == null) {
2044            outError[0] = "<activity-alias> does not specify android:targetActivity";
2045            sa.recycle();
2046            return null;
2047        }
2048
2049        targetActivity = buildClassName(owner.applicationInfo.packageName,
2050                targetActivity, outError);
2051        if (targetActivity == null) {
2052            sa.recycle();
2053            return null;
2054        }
2055
2056        if (mParseActivityAliasArgs == null) {
2057            mParseActivityAliasArgs = new ParseComponentArgs(owner, outError,
2058                    com.android.internal.R.styleable.AndroidManifestActivityAlias_name,
2059                    com.android.internal.R.styleable.AndroidManifestActivityAlias_label,
2060                    com.android.internal.R.styleable.AndroidManifestActivityAlias_icon,
2061                    com.android.internal.R.styleable.AndroidManifestActivityAlias_logo,
2062                    mSeparateProcesses,
2063                    0,
2064                    com.android.internal.R.styleable.AndroidManifestActivityAlias_description,
2065                    com.android.internal.R.styleable.AndroidManifestActivityAlias_enabled);
2066            mParseActivityAliasArgs.tag = "<activity-alias>";
2067        }
2068
2069        mParseActivityAliasArgs.sa = sa;
2070        mParseActivityAliasArgs.flags = flags;
2071
2072        Activity target = null;
2073
2074        final int NA = owner.activities.size();
2075        for (int i=0; i<NA; i++) {
2076            Activity t = owner.activities.get(i);
2077            if (targetActivity.equals(t.info.name)) {
2078                target = t;
2079                break;
2080            }
2081        }
2082
2083        if (target == null) {
2084            outError[0] = "<activity-alias> target activity " + targetActivity
2085                    + " not found in manifest";
2086            sa.recycle();
2087            return null;
2088        }
2089
2090        ActivityInfo info = new ActivityInfo();
2091        info.targetActivity = targetActivity;
2092        info.configChanges = target.info.configChanges;
2093        info.flags = target.info.flags;
2094        info.icon = target.info.icon;
2095        info.logo = target.info.logo;
2096        info.labelRes = target.info.labelRes;
2097        info.nonLocalizedLabel = target.info.nonLocalizedLabel;
2098        info.launchMode = target.info.launchMode;
2099        info.processName = target.info.processName;
2100        if (info.descriptionRes == 0) {
2101            info.descriptionRes = target.info.descriptionRes;
2102        }
2103        info.screenOrientation = target.info.screenOrientation;
2104        info.taskAffinity = target.info.taskAffinity;
2105        info.theme = target.info.theme;
2106
2107        Activity a = new Activity(mParseActivityAliasArgs, info);
2108        if (outError[0] != null) {
2109            sa.recycle();
2110            return null;
2111        }
2112
2113        final boolean setExported = sa.hasValue(
2114                com.android.internal.R.styleable.AndroidManifestActivityAlias_exported);
2115        if (setExported) {
2116            a.info.exported = sa.getBoolean(
2117                    com.android.internal.R.styleable.AndroidManifestActivityAlias_exported, false);
2118        }
2119
2120        String str;
2121        str = sa.getNonConfigurationString(
2122                com.android.internal.R.styleable.AndroidManifestActivityAlias_permission, 0);
2123        if (str != null) {
2124            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
2125        }
2126
2127        sa.recycle();
2128
2129        if (outError[0] != null) {
2130            return null;
2131        }
2132
2133        int outerDepth = parser.getDepth();
2134        int type;
2135        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2136               && (type != XmlPullParser.END_TAG
2137                       || parser.getDepth() > outerDepth)) {
2138            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2139                continue;
2140            }
2141
2142            if (parser.getName().equals("intent-filter")) {
2143                ActivityIntentInfo intent = new ActivityIntentInfo(a);
2144                if (!parseIntent(res, parser, attrs, flags, intent, outError, true)) {
2145                    return null;
2146                }
2147                if (intent.countActions() == 0) {
2148                    Log.w(TAG, "No actions in intent filter at "
2149                            + mArchiveSourcePath + " "
2150                            + parser.getPositionDescription());
2151                } else {
2152                    a.intents.add(intent);
2153                }
2154            } else if (parser.getName().equals("meta-data")) {
2155                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
2156                        outError)) == null) {
2157                    return null;
2158                }
2159            } else {
2160                if (!RIGID_PARSER) {
2161                    Log.w(TAG, "Unknown element under <activity-alias>: " + parser.getName()
2162                            + " at " + mArchiveSourcePath + " "
2163                            + parser.getPositionDescription());
2164                    XmlUtils.skipCurrentTag(parser);
2165                    continue;
2166                }
2167                outError[0] = "Bad element under <activity-alias>: " + parser.getName();
2168                return null;
2169            }
2170        }
2171
2172        if (!setExported) {
2173            a.info.exported = a.intents.size() > 0;
2174        }
2175
2176        return a;
2177    }
2178
2179    private Provider parseProvider(Package owner, Resources res,
2180            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2181            throws XmlPullParserException, IOException {
2182        TypedArray sa = res.obtainAttributes(attrs,
2183                com.android.internal.R.styleable.AndroidManifestProvider);
2184
2185        if (mParseProviderArgs == null) {
2186            mParseProviderArgs = new ParseComponentArgs(owner, outError,
2187                    com.android.internal.R.styleable.AndroidManifestProvider_name,
2188                    com.android.internal.R.styleable.AndroidManifestProvider_label,
2189                    com.android.internal.R.styleable.AndroidManifestProvider_icon,
2190                    com.android.internal.R.styleable.AndroidManifestProvider_logo,
2191                    mSeparateProcesses,
2192                    com.android.internal.R.styleable.AndroidManifestProvider_process,
2193                    com.android.internal.R.styleable.AndroidManifestProvider_description,
2194                    com.android.internal.R.styleable.AndroidManifestProvider_enabled);
2195            mParseProviderArgs.tag = "<provider>";
2196        }
2197
2198        mParseProviderArgs.sa = sa;
2199        mParseProviderArgs.flags = flags;
2200
2201        Provider p = new Provider(mParseProviderArgs, new ProviderInfo());
2202        if (outError[0] != null) {
2203            sa.recycle();
2204            return null;
2205        }
2206
2207        p.info.exported = sa.getBoolean(
2208                com.android.internal.R.styleable.AndroidManifestProvider_exported, true);
2209
2210        String cpname = sa.getNonConfigurationString(
2211                com.android.internal.R.styleable.AndroidManifestProvider_authorities, 0);
2212
2213        p.info.isSyncable = sa.getBoolean(
2214                com.android.internal.R.styleable.AndroidManifestProvider_syncable,
2215                false);
2216
2217        String permission = sa.getNonConfigurationString(
2218                com.android.internal.R.styleable.AndroidManifestProvider_permission, 0);
2219        String str = sa.getNonConfigurationString(
2220                com.android.internal.R.styleable.AndroidManifestProvider_readPermission, 0);
2221        if (str == null) {
2222            str = permission;
2223        }
2224        if (str == null) {
2225            p.info.readPermission = owner.applicationInfo.permission;
2226        } else {
2227            p.info.readPermission =
2228                str.length() > 0 ? str.toString().intern() : null;
2229        }
2230        str = sa.getNonConfigurationString(
2231                com.android.internal.R.styleable.AndroidManifestProvider_writePermission, 0);
2232        if (str == null) {
2233            str = permission;
2234        }
2235        if (str == null) {
2236            p.info.writePermission = owner.applicationInfo.permission;
2237        } else {
2238            p.info.writePermission =
2239                str.length() > 0 ? str.toString().intern() : null;
2240        }
2241
2242        p.info.grantUriPermissions = sa.getBoolean(
2243                com.android.internal.R.styleable.AndroidManifestProvider_grantUriPermissions,
2244                false);
2245
2246        p.info.multiprocess = sa.getBoolean(
2247                com.android.internal.R.styleable.AndroidManifestProvider_multiprocess,
2248                false);
2249
2250        p.info.initOrder = sa.getInt(
2251                com.android.internal.R.styleable.AndroidManifestProvider_initOrder,
2252                0);
2253
2254        sa.recycle();
2255
2256        if ((owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2257            // A heavy-weight application can not have providers in its main process
2258            // We can do direct compare because we intern all strings.
2259            if (p.info.processName == owner.packageName) {
2260                outError[0] = "Heavy-weight applications can not have providers in main process";
2261                return null;
2262            }
2263        }
2264
2265        if (cpname == null) {
2266            outError[0] = "<provider> does not incude authorities attribute";
2267            return null;
2268        }
2269        p.info.authority = cpname.intern();
2270
2271        if (!parseProviderTags(res, parser, attrs, p, outError)) {
2272            return null;
2273        }
2274
2275        return p;
2276    }
2277
2278    private boolean parseProviderTags(Resources res,
2279            XmlPullParser parser, AttributeSet attrs,
2280            Provider outInfo, String[] outError)
2281            throws XmlPullParserException, IOException {
2282        int outerDepth = parser.getDepth();
2283        int type;
2284        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2285               && (type != XmlPullParser.END_TAG
2286                       || parser.getDepth() > outerDepth)) {
2287            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2288                continue;
2289            }
2290
2291            if (parser.getName().equals("meta-data")) {
2292                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2293                        outInfo.metaData, outError)) == null) {
2294                    return false;
2295                }
2296
2297            } else if (parser.getName().equals("grant-uri-permission")) {
2298                TypedArray sa = res.obtainAttributes(attrs,
2299                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission);
2300
2301                PatternMatcher pa = null;
2302
2303                String str = sa.getNonConfigurationString(
2304                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path, 0);
2305                if (str != null) {
2306                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_LITERAL);
2307                }
2308
2309                str = sa.getNonConfigurationString(
2310                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix, 0);
2311                if (str != null) {
2312                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_PREFIX);
2313                }
2314
2315                str = sa.getNonConfigurationString(
2316                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern, 0);
2317                if (str != null) {
2318                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2319                }
2320
2321                sa.recycle();
2322
2323                if (pa != null) {
2324                    if (outInfo.info.uriPermissionPatterns == null) {
2325                        outInfo.info.uriPermissionPatterns = new PatternMatcher[1];
2326                        outInfo.info.uriPermissionPatterns[0] = pa;
2327                    } else {
2328                        final int N = outInfo.info.uriPermissionPatterns.length;
2329                        PatternMatcher[] newp = new PatternMatcher[N+1];
2330                        System.arraycopy(outInfo.info.uriPermissionPatterns, 0, newp, 0, N);
2331                        newp[N] = pa;
2332                        outInfo.info.uriPermissionPatterns = newp;
2333                    }
2334                    outInfo.info.grantUriPermissions = true;
2335                } else {
2336                    if (!RIGID_PARSER) {
2337                        Log.w(TAG, "Unknown element under <path-permission>: "
2338                                + parser.getName() + " at " + mArchiveSourcePath + " "
2339                                + parser.getPositionDescription());
2340                        XmlUtils.skipCurrentTag(parser);
2341                        continue;
2342                    }
2343                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2344                    return false;
2345                }
2346                XmlUtils.skipCurrentTag(parser);
2347
2348            } else if (parser.getName().equals("path-permission")) {
2349                TypedArray sa = res.obtainAttributes(attrs,
2350                        com.android.internal.R.styleable.AndroidManifestPathPermission);
2351
2352                PathPermission pa = null;
2353
2354                String permission = sa.getNonConfigurationString(
2355                        com.android.internal.R.styleable.AndroidManifestPathPermission_permission, 0);
2356                String readPermission = sa.getNonConfigurationString(
2357                        com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission, 0);
2358                if (readPermission == null) {
2359                    readPermission = permission;
2360                }
2361                String writePermission = sa.getNonConfigurationString(
2362                        com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission, 0);
2363                if (writePermission == null) {
2364                    writePermission = permission;
2365                }
2366
2367                boolean havePerm = false;
2368                if (readPermission != null) {
2369                    readPermission = readPermission.intern();
2370                    havePerm = true;
2371                }
2372                if (writePermission != null) {
2373                    writePermission = writePermission.intern();
2374                    havePerm = true;
2375                }
2376
2377                if (!havePerm) {
2378                    if (!RIGID_PARSER) {
2379                        Log.w(TAG, "No readPermission or writePermssion for <path-permission>: "
2380                                + parser.getName() + " at " + mArchiveSourcePath + " "
2381                                + parser.getPositionDescription());
2382                        XmlUtils.skipCurrentTag(parser);
2383                        continue;
2384                    }
2385                    outError[0] = "No readPermission or writePermssion for <path-permission>";
2386                    return false;
2387                }
2388
2389                String path = sa.getNonConfigurationString(
2390                        com.android.internal.R.styleable.AndroidManifestPathPermission_path, 0);
2391                if (path != null) {
2392                    pa = new PathPermission(path,
2393                            PatternMatcher.PATTERN_LITERAL, readPermission, writePermission);
2394                }
2395
2396                path = sa.getNonConfigurationString(
2397                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix, 0);
2398                if (path != null) {
2399                    pa = new PathPermission(path,
2400                            PatternMatcher.PATTERN_PREFIX, readPermission, writePermission);
2401                }
2402
2403                path = sa.getNonConfigurationString(
2404                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern, 0);
2405                if (path != null) {
2406                    pa = new PathPermission(path,
2407                            PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
2408                }
2409
2410                sa.recycle();
2411
2412                if (pa != null) {
2413                    if (outInfo.info.pathPermissions == null) {
2414                        outInfo.info.pathPermissions = new PathPermission[1];
2415                        outInfo.info.pathPermissions[0] = pa;
2416                    } else {
2417                        final int N = outInfo.info.pathPermissions.length;
2418                        PathPermission[] newp = new PathPermission[N+1];
2419                        System.arraycopy(outInfo.info.pathPermissions, 0, newp, 0, N);
2420                        newp[N] = pa;
2421                        outInfo.info.pathPermissions = newp;
2422                    }
2423                } else {
2424                    if (!RIGID_PARSER) {
2425                        Log.w(TAG, "No path, pathPrefix, or pathPattern for <path-permission>: "
2426                                + parser.getName() + " at " + mArchiveSourcePath + " "
2427                                + parser.getPositionDescription());
2428                        XmlUtils.skipCurrentTag(parser);
2429                        continue;
2430                    }
2431                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2432                    return false;
2433                }
2434                XmlUtils.skipCurrentTag(parser);
2435
2436            } else {
2437                if (!RIGID_PARSER) {
2438                    Log.w(TAG, "Unknown element under <provider>: "
2439                            + parser.getName() + " at " + mArchiveSourcePath + " "
2440                            + parser.getPositionDescription());
2441                    XmlUtils.skipCurrentTag(parser);
2442                    continue;
2443                }
2444                outError[0] = "Bad element under <provider>: "
2445                    + parser.getName();
2446                return false;
2447            }
2448        }
2449        return true;
2450    }
2451
2452    private Service parseService(Package owner, Resources res,
2453            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2454            throws XmlPullParserException, IOException {
2455        TypedArray sa = res.obtainAttributes(attrs,
2456                com.android.internal.R.styleable.AndroidManifestService);
2457
2458        if (mParseServiceArgs == null) {
2459            mParseServiceArgs = new ParseComponentArgs(owner, outError,
2460                    com.android.internal.R.styleable.AndroidManifestService_name,
2461                    com.android.internal.R.styleable.AndroidManifestService_label,
2462                    com.android.internal.R.styleable.AndroidManifestService_icon,
2463                    com.android.internal.R.styleable.AndroidManifestService_logo,
2464                    mSeparateProcesses,
2465                    com.android.internal.R.styleable.AndroidManifestService_process,
2466                    com.android.internal.R.styleable.AndroidManifestService_description,
2467                    com.android.internal.R.styleable.AndroidManifestService_enabled);
2468            mParseServiceArgs.tag = "<service>";
2469        }
2470
2471        mParseServiceArgs.sa = sa;
2472        mParseServiceArgs.flags = flags;
2473
2474        Service s = new Service(mParseServiceArgs, new ServiceInfo());
2475        if (outError[0] != null) {
2476            sa.recycle();
2477            return null;
2478        }
2479
2480        final boolean setExported = sa.hasValue(
2481                com.android.internal.R.styleable.AndroidManifestService_exported);
2482        if (setExported) {
2483            s.info.exported = sa.getBoolean(
2484                    com.android.internal.R.styleable.AndroidManifestService_exported, false);
2485        }
2486
2487        String str = sa.getNonConfigurationString(
2488                com.android.internal.R.styleable.AndroidManifestService_permission, 0);
2489        if (str == null) {
2490            s.info.permission = owner.applicationInfo.permission;
2491        } else {
2492            s.info.permission = str.length() > 0 ? str.toString().intern() : null;
2493        }
2494
2495        s.info.flags = 0;
2496        if (sa.getBoolean(
2497                com.android.internal.R.styleable.AndroidManifestService_stopWithTask,
2498                false)) {
2499            s.info.flags |= ServiceInfo.FLAG_STOP_WITH_TASK;
2500        }
2501
2502        sa.recycle();
2503
2504        if ((owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2505            // A heavy-weight application can not have services in its main process
2506            // We can do direct compare because we intern all strings.
2507            if (s.info.processName == owner.packageName) {
2508                outError[0] = "Heavy-weight applications can not have services in main process";
2509                return null;
2510            }
2511        }
2512
2513        int outerDepth = parser.getDepth();
2514        int type;
2515        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2516               && (type != XmlPullParser.END_TAG
2517                       || parser.getDepth() > outerDepth)) {
2518            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2519                continue;
2520            }
2521
2522            if (parser.getName().equals("intent-filter")) {
2523                ServiceIntentInfo intent = new ServiceIntentInfo(s);
2524                if (!parseIntent(res, parser, attrs, flags, intent, outError, false)) {
2525                    return null;
2526                }
2527
2528                s.intents.add(intent);
2529            } else if (parser.getName().equals("meta-data")) {
2530                if ((s.metaData=parseMetaData(res, parser, attrs, s.metaData,
2531                        outError)) == null) {
2532                    return null;
2533                }
2534            } else {
2535                if (!RIGID_PARSER) {
2536                    Log.w(TAG, "Unknown element under <service>: "
2537                            + parser.getName() + " at " + mArchiveSourcePath + " "
2538                            + parser.getPositionDescription());
2539                    XmlUtils.skipCurrentTag(parser);
2540                    continue;
2541                }
2542                outError[0] = "Bad element under <service>: "
2543                    + parser.getName();
2544                return null;
2545            }
2546        }
2547
2548        if (!setExported) {
2549            s.info.exported = s.intents.size() > 0;
2550        }
2551
2552        return s;
2553    }
2554
2555    private boolean parseAllMetaData(Resources res,
2556            XmlPullParser parser, AttributeSet attrs, String tag,
2557            Component outInfo, String[] outError)
2558            throws XmlPullParserException, IOException {
2559        int outerDepth = parser.getDepth();
2560        int type;
2561        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2562               && (type != XmlPullParser.END_TAG
2563                       || parser.getDepth() > outerDepth)) {
2564            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2565                continue;
2566            }
2567
2568            if (parser.getName().equals("meta-data")) {
2569                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2570                        outInfo.metaData, outError)) == null) {
2571                    return false;
2572                }
2573            } else {
2574                if (!RIGID_PARSER) {
2575                    Log.w(TAG, "Unknown element under " + tag + ": "
2576                            + parser.getName() + " at " + mArchiveSourcePath + " "
2577                            + parser.getPositionDescription());
2578                    XmlUtils.skipCurrentTag(parser);
2579                    continue;
2580                }
2581                outError[0] = "Bad element under " + tag + ": "
2582                    + parser.getName();
2583                return false;
2584            }
2585        }
2586        return true;
2587    }
2588
2589    private Bundle parseMetaData(Resources res,
2590            XmlPullParser parser, AttributeSet attrs,
2591            Bundle data, String[] outError)
2592            throws XmlPullParserException, IOException {
2593
2594        TypedArray sa = res.obtainAttributes(attrs,
2595                com.android.internal.R.styleable.AndroidManifestMetaData);
2596
2597        if (data == null) {
2598            data = new Bundle();
2599        }
2600
2601        String name = sa.getNonConfigurationString(
2602                com.android.internal.R.styleable.AndroidManifestMetaData_name, 0);
2603        if (name == null) {
2604            outError[0] = "<meta-data> requires an android:name attribute";
2605            sa.recycle();
2606            return null;
2607        }
2608
2609        name = name.intern();
2610
2611        TypedValue v = sa.peekValue(
2612                com.android.internal.R.styleable.AndroidManifestMetaData_resource);
2613        if (v != null && v.resourceId != 0) {
2614            //Log.i(TAG, "Meta data ref " + name + ": " + v);
2615            data.putInt(name, v.resourceId);
2616        } else {
2617            v = sa.peekValue(
2618                    com.android.internal.R.styleable.AndroidManifestMetaData_value);
2619            //Log.i(TAG, "Meta data " + name + ": " + v);
2620            if (v != null) {
2621                if (v.type == TypedValue.TYPE_STRING) {
2622                    CharSequence cs = v.coerceToString();
2623                    data.putString(name, cs != null ? cs.toString().intern() : null);
2624                } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2625                    data.putBoolean(name, v.data != 0);
2626                } else if (v.type >= TypedValue.TYPE_FIRST_INT
2627                        && v.type <= TypedValue.TYPE_LAST_INT) {
2628                    data.putInt(name, v.data);
2629                } else if (v.type == TypedValue.TYPE_FLOAT) {
2630                    data.putFloat(name, v.getFloat());
2631                } else {
2632                    if (!RIGID_PARSER) {
2633                        Log.w(TAG, "<meta-data> only supports string, integer, float, color, boolean, and resource reference types: "
2634                                + parser.getName() + " at " + mArchiveSourcePath + " "
2635                                + parser.getPositionDescription());
2636                    } else {
2637                        outError[0] = "<meta-data> only supports string, integer, float, color, boolean, and resource reference types";
2638                        data = null;
2639                    }
2640                }
2641            } else {
2642                outError[0] = "<meta-data> requires an android:value or android:resource attribute";
2643                data = null;
2644            }
2645        }
2646
2647        sa.recycle();
2648
2649        XmlUtils.skipCurrentTag(parser);
2650
2651        return data;
2652    }
2653
2654    private static final String ANDROID_RESOURCES
2655            = "http://schemas.android.com/apk/res/android";
2656
2657    private boolean parseIntent(Resources res,
2658            XmlPullParser parser, AttributeSet attrs, int flags,
2659            IntentInfo outInfo, String[] outError, boolean isActivity)
2660            throws XmlPullParserException, IOException {
2661
2662        TypedArray sa = res.obtainAttributes(attrs,
2663                com.android.internal.R.styleable.AndroidManifestIntentFilter);
2664
2665        int priority = sa.getInt(
2666                com.android.internal.R.styleable.AndroidManifestIntentFilter_priority, 0);
2667        outInfo.setPriority(priority);
2668
2669        TypedValue v = sa.peekValue(
2670                com.android.internal.R.styleable.AndroidManifestIntentFilter_label);
2671        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2672            outInfo.nonLocalizedLabel = v.coerceToString();
2673        }
2674
2675        outInfo.icon = sa.getResourceId(
2676                com.android.internal.R.styleable.AndroidManifestIntentFilter_icon, 0);
2677
2678        outInfo.logo = sa.getResourceId(
2679                com.android.internal.R.styleable.AndroidManifestIntentFilter_logo, 0);
2680
2681        sa.recycle();
2682
2683        int outerDepth = parser.getDepth();
2684        int type;
2685        while ((type=parser.next()) != parser.END_DOCUMENT
2686               && (type != parser.END_TAG || parser.getDepth() > outerDepth)) {
2687            if (type == parser.END_TAG || type == parser.TEXT) {
2688                continue;
2689            }
2690
2691            String nodeName = parser.getName();
2692            if (nodeName.equals("action")) {
2693                String value = attrs.getAttributeValue(
2694                        ANDROID_RESOURCES, "name");
2695                if (value == null || value == "") {
2696                    outError[0] = "No value supplied for <android:name>";
2697                    return false;
2698                }
2699                XmlUtils.skipCurrentTag(parser);
2700
2701                outInfo.addAction(value);
2702            } else if (nodeName.equals("category")) {
2703                String value = attrs.getAttributeValue(
2704                        ANDROID_RESOURCES, "name");
2705                if (value == null || value == "") {
2706                    outError[0] = "No value supplied for <android:name>";
2707                    return false;
2708                }
2709                XmlUtils.skipCurrentTag(parser);
2710
2711                outInfo.addCategory(value);
2712
2713            } else if (nodeName.equals("data")) {
2714                sa = res.obtainAttributes(attrs,
2715                        com.android.internal.R.styleable.AndroidManifestData);
2716
2717                String str = sa.getNonConfigurationString(
2718                        com.android.internal.R.styleable.AndroidManifestData_mimeType, 0);
2719                if (str != null) {
2720                    try {
2721                        outInfo.addDataType(str);
2722                    } catch (IntentFilter.MalformedMimeTypeException e) {
2723                        outError[0] = e.toString();
2724                        sa.recycle();
2725                        return false;
2726                    }
2727                }
2728
2729                str = sa.getNonConfigurationString(
2730                        com.android.internal.R.styleable.AndroidManifestData_scheme, 0);
2731                if (str != null) {
2732                    outInfo.addDataScheme(str);
2733                }
2734
2735                String host = sa.getNonConfigurationString(
2736                        com.android.internal.R.styleable.AndroidManifestData_host, 0);
2737                String port = sa.getNonConfigurationString(
2738                        com.android.internal.R.styleable.AndroidManifestData_port, 0);
2739                if (host != null) {
2740                    outInfo.addDataAuthority(host, port);
2741                }
2742
2743                str = sa.getNonConfigurationString(
2744                        com.android.internal.R.styleable.AndroidManifestData_path, 0);
2745                if (str != null) {
2746                    outInfo.addDataPath(str, PatternMatcher.PATTERN_LITERAL);
2747                }
2748
2749                str = sa.getNonConfigurationString(
2750                        com.android.internal.R.styleable.AndroidManifestData_pathPrefix, 0);
2751                if (str != null) {
2752                    outInfo.addDataPath(str, PatternMatcher.PATTERN_PREFIX);
2753                }
2754
2755                str = sa.getNonConfigurationString(
2756                        com.android.internal.R.styleable.AndroidManifestData_pathPattern, 0);
2757                if (str != null) {
2758                    outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2759                }
2760
2761                sa.recycle();
2762                XmlUtils.skipCurrentTag(parser);
2763            } else if (!RIGID_PARSER) {
2764                Log.w(TAG, "Unknown element under <intent-filter>: "
2765                        + parser.getName() + " at " + mArchiveSourcePath + " "
2766                        + parser.getPositionDescription());
2767                XmlUtils.skipCurrentTag(parser);
2768            } else {
2769                outError[0] = "Bad element under <intent-filter>: " + parser.getName();
2770                return false;
2771            }
2772        }
2773
2774        outInfo.hasDefault = outInfo.hasCategory(Intent.CATEGORY_DEFAULT);
2775        if (false) {
2776            String cats = "";
2777            Iterator<String> it = outInfo.categoriesIterator();
2778            while (it != null && it.hasNext()) {
2779                cats += " " + it.next();
2780            }
2781            System.out.println("Intent d=" +
2782                    outInfo.hasDefault + ", cat=" + cats);
2783        }
2784
2785        return true;
2786    }
2787
2788    public final static class Package {
2789        public String packageName;
2790
2791        // For now we only support one application per package.
2792        public final ApplicationInfo applicationInfo = new ApplicationInfo();
2793
2794        public final ArrayList<Permission> permissions = new ArrayList<Permission>(0);
2795        public final ArrayList<PermissionGroup> permissionGroups = new ArrayList<PermissionGroup>(0);
2796        public final ArrayList<Activity> activities = new ArrayList<Activity>(0);
2797        public final ArrayList<Activity> receivers = new ArrayList<Activity>(0);
2798        public final ArrayList<Provider> providers = new ArrayList<Provider>(0);
2799        public final ArrayList<Service> services = new ArrayList<Service>(0);
2800        public final ArrayList<Instrumentation> instrumentation = new ArrayList<Instrumentation>(0);
2801
2802        public final ArrayList<String> requestedPermissions = new ArrayList<String>();
2803
2804        public ArrayList<String> protectedBroadcasts;
2805
2806        public ArrayList<String> usesLibraries = null;
2807        public ArrayList<String> usesOptionalLibraries = null;
2808        public String[] usesLibraryFiles = null;
2809
2810        public ArrayList<String> mOriginalPackages = null;
2811        public String mRealPackage = null;
2812        public ArrayList<String> mAdoptPermissions = null;
2813
2814        // We store the application meta-data independently to avoid multiple unwanted references
2815        public Bundle mAppMetaData = null;
2816
2817        // If this is a 3rd party app, this is the path of the zip file.
2818        public String mPath;
2819
2820        // The version code declared for this package.
2821        public int mVersionCode;
2822
2823        // The version name declared for this package.
2824        public String mVersionName;
2825
2826        // The shared user id that this package wants to use.
2827        public String mSharedUserId;
2828
2829        // The shared user label that this package wants to use.
2830        public int mSharedUserLabel;
2831
2832        // Signatures that were read from the package.
2833        public Signature mSignatures[];
2834
2835        // For use by package manager service for quick lookup of
2836        // preferred up order.
2837        public int mPreferredOrder = 0;
2838
2839        // For use by the package manager to keep track of the path to the
2840        // file an app came from.
2841        public String mScanPath;
2842
2843        // For use by package manager to keep track of where it has done dexopt.
2844        public boolean mDidDexOpt;
2845
2846        // User set enabled state.
2847        public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2848
2849        // Whether the package has been stopped.
2850        public boolean mSetStopped = false;
2851
2852        // Additional data supplied by callers.
2853        public Object mExtras;
2854
2855        // Whether an operation is currently pending on this package
2856        public boolean mOperationPending;
2857
2858        /*
2859         *  Applications hardware preferences
2860         */
2861        public final ArrayList<ConfigurationInfo> configPreferences =
2862                new ArrayList<ConfigurationInfo>();
2863
2864        /*
2865         *  Applications requested features
2866         */
2867        public ArrayList<FeatureInfo> reqFeatures = null;
2868
2869        public int installLocation;
2870
2871        public Package(String _name) {
2872            packageName = _name;
2873            applicationInfo.packageName = _name;
2874            applicationInfo.uid = -1;
2875        }
2876
2877        public void setPackageName(String newName) {
2878            packageName = newName;
2879            applicationInfo.packageName = newName;
2880            for (int i=permissions.size()-1; i>=0; i--) {
2881                permissions.get(i).setPackageName(newName);
2882            }
2883            for (int i=permissionGroups.size()-1; i>=0; i--) {
2884                permissionGroups.get(i).setPackageName(newName);
2885            }
2886            for (int i=activities.size()-1; i>=0; i--) {
2887                activities.get(i).setPackageName(newName);
2888            }
2889            for (int i=receivers.size()-1; i>=0; i--) {
2890                receivers.get(i).setPackageName(newName);
2891            }
2892            for (int i=providers.size()-1; i>=0; i--) {
2893                providers.get(i).setPackageName(newName);
2894            }
2895            for (int i=services.size()-1; i>=0; i--) {
2896                services.get(i).setPackageName(newName);
2897            }
2898            for (int i=instrumentation.size()-1; i>=0; i--) {
2899                instrumentation.get(i).setPackageName(newName);
2900            }
2901        }
2902
2903        public String toString() {
2904            return "Package{"
2905                + Integer.toHexString(System.identityHashCode(this))
2906                + " " + packageName + "}";
2907        }
2908    }
2909
2910    public static class Component<II extends IntentInfo> {
2911        public final Package owner;
2912        public final ArrayList<II> intents;
2913        public final String className;
2914        public Bundle metaData;
2915
2916        ComponentName componentName;
2917        String componentShortName;
2918
2919        public Component(Package _owner) {
2920            owner = _owner;
2921            intents = null;
2922            className = null;
2923        }
2924
2925        public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
2926            owner = args.owner;
2927            intents = new ArrayList<II>(0);
2928            String name = args.sa.getNonConfigurationString(args.nameRes, 0);
2929            if (name == null) {
2930                className = null;
2931                args.outError[0] = args.tag + " does not specify android:name";
2932                return;
2933            }
2934
2935            outInfo.name
2936                = buildClassName(owner.applicationInfo.packageName, name, args.outError);
2937            if (outInfo.name == null) {
2938                className = null;
2939                args.outError[0] = args.tag + " does not have valid android:name";
2940                return;
2941            }
2942
2943            className = outInfo.name;
2944
2945            int iconVal = args.sa.getResourceId(args.iconRes, 0);
2946            if (iconVal != 0) {
2947                outInfo.icon = iconVal;
2948                outInfo.nonLocalizedLabel = null;
2949            }
2950
2951            int logoVal = args.sa.getResourceId(args.logoRes, 0);
2952            if (logoVal != 0) {
2953                outInfo.logo = logoVal;
2954            }
2955
2956            TypedValue v = args.sa.peekValue(args.labelRes);
2957            if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2958                outInfo.nonLocalizedLabel = v.coerceToString();
2959            }
2960
2961            outInfo.packageName = owner.packageName;
2962        }
2963
2964        public Component(final ParseComponentArgs args, final ComponentInfo outInfo) {
2965            this(args, (PackageItemInfo)outInfo);
2966            if (args.outError[0] != null) {
2967                return;
2968            }
2969
2970            if (args.processRes != 0) {
2971                CharSequence pname;
2972                if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2973                    pname = args.sa.getNonConfigurationString(args.processRes, 0);
2974                } else {
2975                    // Some older apps have been seen to use a resource reference
2976                    // here that on older builds was ignored (with a warning).  We
2977                    // need to continue to do this for them so they don't break.
2978                    pname = args.sa.getNonResourceString(args.processRes);
2979                }
2980                outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
2981                        owner.applicationInfo.processName, pname,
2982                        args.flags, args.sepProcesses, args.outError);
2983            }
2984
2985            if (args.descriptionRes != 0) {
2986                outInfo.descriptionRes = args.sa.getResourceId(args.descriptionRes, 0);
2987            }
2988
2989            outInfo.enabled = args.sa.getBoolean(args.enabledRes, true);
2990        }
2991
2992        public Component(Component<II> clone) {
2993            owner = clone.owner;
2994            intents = clone.intents;
2995            className = clone.className;
2996            componentName = clone.componentName;
2997            componentShortName = clone.componentShortName;
2998        }
2999
3000        public ComponentName getComponentName() {
3001            if (componentName != null) {
3002                return componentName;
3003            }
3004            if (className != null) {
3005                componentName = new ComponentName(owner.applicationInfo.packageName,
3006                        className);
3007            }
3008            return componentName;
3009        }
3010
3011        public String getComponentShortName() {
3012            if (componentShortName != null) {
3013                return componentShortName;
3014            }
3015            ComponentName component = getComponentName();
3016            if (component != null) {
3017                componentShortName = component.flattenToShortString();
3018            }
3019            return componentShortName;
3020        }
3021
3022        public void setPackageName(String packageName) {
3023            componentName = null;
3024            componentShortName = null;
3025        }
3026    }
3027
3028    public final static class Permission extends Component<IntentInfo> {
3029        public final PermissionInfo info;
3030        public boolean tree;
3031        public PermissionGroup group;
3032
3033        public Permission(Package _owner) {
3034            super(_owner);
3035            info = new PermissionInfo();
3036        }
3037
3038        public Permission(Package _owner, PermissionInfo _info) {
3039            super(_owner);
3040            info = _info;
3041        }
3042
3043        public void setPackageName(String packageName) {
3044            super.setPackageName(packageName);
3045            info.packageName = packageName;
3046        }
3047
3048        public String toString() {
3049            return "Permission{"
3050                + Integer.toHexString(System.identityHashCode(this))
3051                + " " + info.name + "}";
3052        }
3053    }
3054
3055    public final static class PermissionGroup extends Component<IntentInfo> {
3056        public final PermissionGroupInfo info;
3057
3058        public PermissionGroup(Package _owner) {
3059            super(_owner);
3060            info = new PermissionGroupInfo();
3061        }
3062
3063        public PermissionGroup(Package _owner, PermissionGroupInfo _info) {
3064            super(_owner);
3065            info = _info;
3066        }
3067
3068        public void setPackageName(String packageName) {
3069            super.setPackageName(packageName);
3070            info.packageName = packageName;
3071        }
3072
3073        public String toString() {
3074            return "PermissionGroup{"
3075                + Integer.toHexString(System.identityHashCode(this))
3076                + " " + info.name + "}";
3077        }
3078    }
3079
3080    private static boolean copyNeeded(int flags, Package p, Bundle metaData) {
3081        if (p.mSetEnabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
3082            boolean enabled = p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
3083            if (p.applicationInfo.enabled != enabled) {
3084                return true;
3085            }
3086        }
3087        if ((flags & PackageManager.GET_META_DATA) != 0
3088                && (metaData != null || p.mAppMetaData != null)) {
3089            return true;
3090        }
3091        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0
3092                && p.usesLibraryFiles != null) {
3093            return true;
3094        }
3095        return false;
3096    }
3097
3098    public static ApplicationInfo generateApplicationInfo(Package p, int flags) {
3099        if (p == null) return null;
3100        if (!copyNeeded(flags, p, null)) {
3101            // CompatibilityMode is global state. It's safe to modify the instance
3102            // of the package.
3103            if (!sCompatibilityModeEnabled) {
3104                p.applicationInfo.disableCompatibilityMode();
3105            }
3106            if (p.mSetStopped) {
3107                p.applicationInfo.flags |= ApplicationInfo.FLAG_STOPPED;
3108            } else {
3109                p.applicationInfo.flags &= ~ApplicationInfo.FLAG_STOPPED;
3110            }
3111            return p.applicationInfo;
3112        }
3113
3114        // Make shallow copy so we can store the metadata/libraries safely
3115        ApplicationInfo ai = new ApplicationInfo(p.applicationInfo);
3116        if ((flags & PackageManager.GET_META_DATA) != 0) {
3117            ai.metaData = p.mAppMetaData;
3118        }
3119        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0) {
3120            ai.sharedLibraryFiles = p.usesLibraryFiles;
3121        }
3122        if (!sCompatibilityModeEnabled) {
3123            ai.disableCompatibilityMode();
3124        }
3125        if (p.mSetStopped) {
3126            p.applicationInfo.flags |= ApplicationInfo.FLAG_STOPPED;
3127        } else {
3128            p.applicationInfo.flags &= ~ApplicationInfo.FLAG_STOPPED;
3129        }
3130        if (p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
3131            ai.enabled = true;
3132        } else if (p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
3133            ai.enabled = false;
3134        }
3135        return ai;
3136    }
3137
3138    public static final PermissionInfo generatePermissionInfo(
3139            Permission p, int flags) {
3140        if (p == null) return null;
3141        if ((flags&PackageManager.GET_META_DATA) == 0) {
3142            return p.info;
3143        }
3144        PermissionInfo pi = new PermissionInfo(p.info);
3145        pi.metaData = p.metaData;
3146        return pi;
3147    }
3148
3149    public static final PermissionGroupInfo generatePermissionGroupInfo(
3150            PermissionGroup pg, int flags) {
3151        if (pg == null) return null;
3152        if ((flags&PackageManager.GET_META_DATA) == 0) {
3153            return pg.info;
3154        }
3155        PermissionGroupInfo pgi = new PermissionGroupInfo(pg.info);
3156        pgi.metaData = pg.metaData;
3157        return pgi;
3158    }
3159
3160    public final static class Activity extends Component<ActivityIntentInfo> {
3161        public final ActivityInfo info;
3162
3163        public Activity(final ParseComponentArgs args, final ActivityInfo _info) {
3164            super(args, _info);
3165            info = _info;
3166            info.applicationInfo = args.owner.applicationInfo;
3167        }
3168
3169        public void setPackageName(String packageName) {
3170            super.setPackageName(packageName);
3171            info.packageName = packageName;
3172        }
3173
3174        public String toString() {
3175            return "Activity{"
3176                + Integer.toHexString(System.identityHashCode(this))
3177                + " " + getComponentShortName() + "}";
3178        }
3179    }
3180
3181    public static final ActivityInfo generateActivityInfo(Activity a,
3182            int flags) {
3183        if (a == null) return null;
3184        if (!copyNeeded(flags, a.owner, a.metaData)) {
3185            return a.info;
3186        }
3187        // Make shallow copies so we can store the metadata safely
3188        ActivityInfo ai = new ActivityInfo(a.info);
3189        ai.metaData = a.metaData;
3190        ai.applicationInfo = generateApplicationInfo(a.owner, flags);
3191        return ai;
3192    }
3193
3194    public final static class Service extends Component<ServiceIntentInfo> {
3195        public final ServiceInfo info;
3196
3197        public Service(final ParseComponentArgs args, final ServiceInfo _info) {
3198            super(args, _info);
3199            info = _info;
3200            info.applicationInfo = args.owner.applicationInfo;
3201        }
3202
3203        public void setPackageName(String packageName) {
3204            super.setPackageName(packageName);
3205            info.packageName = packageName;
3206        }
3207
3208        public String toString() {
3209            return "Service{"
3210                + Integer.toHexString(System.identityHashCode(this))
3211                + " " + getComponentShortName() + "}";
3212        }
3213    }
3214
3215    public static final ServiceInfo generateServiceInfo(Service s, int flags) {
3216        if (s == null) return null;
3217        if (!copyNeeded(flags, s.owner, s.metaData)) {
3218            return s.info;
3219        }
3220        // Make shallow copies so we can store the metadata safely
3221        ServiceInfo si = new ServiceInfo(s.info);
3222        si.metaData = s.metaData;
3223        si.applicationInfo = generateApplicationInfo(s.owner, flags);
3224        return si;
3225    }
3226
3227    public final static class Provider extends Component {
3228        public final ProviderInfo info;
3229        public boolean syncable;
3230
3231        public Provider(final ParseComponentArgs args, final ProviderInfo _info) {
3232            super(args, _info);
3233            info = _info;
3234            info.applicationInfo = args.owner.applicationInfo;
3235            syncable = false;
3236        }
3237
3238        public Provider(Provider existingProvider) {
3239            super(existingProvider);
3240            this.info = existingProvider.info;
3241            this.syncable = existingProvider.syncable;
3242        }
3243
3244        public void setPackageName(String packageName) {
3245            super.setPackageName(packageName);
3246            info.packageName = packageName;
3247        }
3248
3249        public String toString() {
3250            return "Provider{"
3251                + Integer.toHexString(System.identityHashCode(this))
3252                + " " + info.name + "}";
3253        }
3254    }
3255
3256    public static final ProviderInfo generateProviderInfo(Provider p,
3257            int flags) {
3258        if (p == null) return null;
3259        if (!copyNeeded(flags, p.owner, p.metaData)
3260                && ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) != 0
3261                        || p.info.uriPermissionPatterns == null)) {
3262            return p.info;
3263        }
3264        // Make shallow copies so we can store the metadata safely
3265        ProviderInfo pi = new ProviderInfo(p.info);
3266        pi.metaData = p.metaData;
3267        if ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) == 0) {
3268            pi.uriPermissionPatterns = null;
3269        }
3270        pi.applicationInfo = generateApplicationInfo(p.owner, flags);
3271        return pi;
3272    }
3273
3274    public final static class Instrumentation extends Component {
3275        public final InstrumentationInfo info;
3276
3277        public Instrumentation(final ParsePackageItemArgs args, final InstrumentationInfo _info) {
3278            super(args, _info);
3279            info = _info;
3280        }
3281
3282        public void setPackageName(String packageName) {
3283            super.setPackageName(packageName);
3284            info.packageName = packageName;
3285        }
3286
3287        public String toString() {
3288            return "Instrumentation{"
3289                + Integer.toHexString(System.identityHashCode(this))
3290                + " " + getComponentShortName() + "}";
3291        }
3292    }
3293
3294    public static final InstrumentationInfo generateInstrumentationInfo(
3295            Instrumentation i, int flags) {
3296        if (i == null) return null;
3297        if ((flags&PackageManager.GET_META_DATA) == 0) {
3298            return i.info;
3299        }
3300        InstrumentationInfo ii = new InstrumentationInfo(i.info);
3301        ii.metaData = i.metaData;
3302        return ii;
3303    }
3304
3305    public static class IntentInfo extends IntentFilter {
3306        public boolean hasDefault;
3307        public int labelRes;
3308        public CharSequence nonLocalizedLabel;
3309        public int icon;
3310        public int logo;
3311    }
3312
3313    public final static class ActivityIntentInfo extends IntentInfo {
3314        public final Activity activity;
3315
3316        public ActivityIntentInfo(Activity _activity) {
3317            activity = _activity;
3318        }
3319
3320        public String toString() {
3321            return "ActivityIntentInfo{"
3322                + Integer.toHexString(System.identityHashCode(this))
3323                + " " + activity.info.name + "}";
3324        }
3325    }
3326
3327    public final static class ServiceIntentInfo extends IntentInfo {
3328        public final Service service;
3329
3330        public ServiceIntentInfo(Service _service) {
3331            service = _service;
3332        }
3333
3334        public String toString() {
3335            return "ServiceIntentInfo{"
3336                + Integer.toHexString(System.identityHashCode(this))
3337                + " " + service.info.name + "}";
3338        }
3339    }
3340
3341    /**
3342     * @hide
3343     */
3344    public static void setCompatibilityModeEnabled(boolean compatibilityModeEnabled) {
3345        sCompatibilityModeEnabled = compatibilityModeEnabled;
3346    }
3347}
3348