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