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