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