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