PackageParser.java revision 37dca155aaaecd79d801f53851d1d319d7ff0726
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        int currentKeyDepth = -1;
1558        Map<PublicKey, Set<String>> definedKeySets = new HashMap<PublicKey, Set<String>>();
1559        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1560                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1561            if (type == XmlPullParser.END_TAG) {
1562                if (parser.getDepth() == currentKeyDepth) {
1563                    currentKey = null;
1564                    currentKeyDepth = -1;
1565                }
1566                continue;
1567            }
1568            String tagname = parser.getName();
1569            if (tagname.equals("publicKey")) {
1570                final TypedArray sa = res.obtainAttributes(attrs,
1571                        com.android.internal.R.styleable.PublicKey);
1572                final String encodedKey = sa.getNonResourceString(
1573                    com.android.internal.R.styleable.PublicKey_value);
1574                currentKey = parsePublicKey(encodedKey);
1575                if (currentKey == null) {
1576                    Slog.w(TAG, "No valid key in 'publicKey' tag at "
1577                            + parser.getPositionDescription());
1578                    sa.recycle();
1579                    continue;
1580                }
1581                currentKeyDepth = parser.getDepth();
1582                definedKeySets.put(currentKey, new HashSet<String>());
1583                sa.recycle();
1584            } else if (tagname.equals("keyset")) {
1585                if (currentKey == null) {
1586                    Slog.i(TAG, "'keyset' not in 'publicKey' tag at "
1587                            + parser.getPositionDescription());
1588                    continue;
1589                }
1590                final TypedArray sa = res.obtainAttributes(attrs,
1591                        com.android.internal.R.styleable.KeySet);
1592                final String name = sa.getNonResourceString(
1593                    com.android.internal.R.styleable.KeySet_name);
1594                definedKeySets.get(currentKey).add(name);
1595                sa.recycle();
1596            } else if (RIGID_PARSER) {
1597                Slog.w(TAG, "Bad element under <keys>: " + parser.getName()
1598                        + " at " + mArchiveSourcePath + " "
1599                        + parser.getPositionDescription());
1600                return false;
1601            } else {
1602                Slog.w(TAG, "Unknown element under <keys>: " + parser.getName()
1603                        + " at " + mArchiveSourcePath + " "
1604                        + parser.getPositionDescription());
1605                XmlUtils.skipCurrentTag(parser);
1606                continue;
1607            }
1608        }
1609
1610        owner.mKeySetMapping = new HashMap<String, Set<PublicKey>>();
1611        for (Map.Entry<PublicKey, Set<String>> e : definedKeySets.entrySet()) {
1612            PublicKey key = e.getKey();
1613            Set<String> keySetNames = e.getValue();
1614            for (String alias : keySetNames) {
1615                if (owner.mKeySetMapping.containsKey(alias)) {
1616                    owner.mKeySetMapping.get(alias).add(key);
1617                } else {
1618                    Set<PublicKey> keys = new HashSet<PublicKey>();
1619                    keys.add(key);
1620                    owner.mKeySetMapping.put(alias, keys);
1621                }
1622            }
1623        }
1624
1625        return true;
1626    }
1627
1628    private PermissionGroup parsePermissionGroup(Package owner, int flags, Resources res,
1629            XmlPullParser parser, AttributeSet attrs, String[] outError)
1630        throws XmlPullParserException, IOException {
1631        PermissionGroup perm = new PermissionGroup(owner);
1632
1633        TypedArray sa = res.obtainAttributes(attrs,
1634                com.android.internal.R.styleable.AndroidManifestPermissionGroup);
1635
1636        if (!parsePackageItemInfo(owner, perm.info, outError,
1637                "<permission-group>", sa,
1638                com.android.internal.R.styleable.AndroidManifestPermissionGroup_name,
1639                com.android.internal.R.styleable.AndroidManifestPermissionGroup_label,
1640                com.android.internal.R.styleable.AndroidManifestPermissionGroup_icon,
1641                com.android.internal.R.styleable.AndroidManifestPermissionGroup_logo)) {
1642            sa.recycle();
1643            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1644            return null;
1645        }
1646
1647        perm.info.descriptionRes = sa.getResourceId(
1648                com.android.internal.R.styleable.AndroidManifestPermissionGroup_description,
1649                0);
1650        perm.info.flags = sa.getInt(
1651                com.android.internal.R.styleable.AndroidManifestPermissionGroup_permissionGroupFlags, 0);
1652        perm.info.priority = sa.getInt(
1653                com.android.internal.R.styleable.AndroidManifestPermissionGroup_priority, 0);
1654        if (perm.info.priority > 0 && (flags&PARSE_IS_SYSTEM) == 0) {
1655            perm.info.priority = 0;
1656        }
1657
1658        sa.recycle();
1659
1660        if (!parseAllMetaData(res, parser, attrs, "<permission-group>", perm,
1661                outError)) {
1662            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1663            return null;
1664        }
1665
1666        owner.permissionGroups.add(perm);
1667
1668        return perm;
1669    }
1670
1671    private Permission parsePermission(Package owner, Resources res,
1672            XmlPullParser parser, AttributeSet attrs, String[] outError)
1673        throws XmlPullParserException, IOException {
1674        Permission perm = new Permission(owner);
1675
1676        TypedArray sa = res.obtainAttributes(attrs,
1677                com.android.internal.R.styleable.AndroidManifestPermission);
1678
1679        if (!parsePackageItemInfo(owner, perm.info, outError,
1680                "<permission>", sa,
1681                com.android.internal.R.styleable.AndroidManifestPermission_name,
1682                com.android.internal.R.styleable.AndroidManifestPermission_label,
1683                com.android.internal.R.styleable.AndroidManifestPermission_icon,
1684                com.android.internal.R.styleable.AndroidManifestPermission_logo)) {
1685            sa.recycle();
1686            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1687            return null;
1688        }
1689
1690        // Note: don't allow this value to be a reference to a resource
1691        // that may change.
1692        perm.info.group = sa.getNonResourceString(
1693                com.android.internal.R.styleable.AndroidManifestPermission_permissionGroup);
1694        if (perm.info.group != null) {
1695            perm.info.group = perm.info.group.intern();
1696        }
1697
1698        perm.info.descriptionRes = sa.getResourceId(
1699                com.android.internal.R.styleable.AndroidManifestPermission_description,
1700                0);
1701
1702        perm.info.protectionLevel = sa.getInt(
1703                com.android.internal.R.styleable.AndroidManifestPermission_protectionLevel,
1704                PermissionInfo.PROTECTION_NORMAL);
1705
1706        perm.info.flags = sa.getInt(
1707                com.android.internal.R.styleable.AndroidManifestPermission_permissionFlags, 0);
1708
1709        sa.recycle();
1710
1711        if (perm.info.protectionLevel == -1) {
1712            outError[0] = "<permission> does not specify protectionLevel";
1713            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1714            return null;
1715        }
1716
1717        perm.info.protectionLevel = PermissionInfo.fixProtectionLevel(perm.info.protectionLevel);
1718
1719        if ((perm.info.protectionLevel&PermissionInfo.PROTECTION_MASK_FLAGS) != 0) {
1720            if ((perm.info.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) !=
1721                    PermissionInfo.PROTECTION_SIGNATURE) {
1722                outError[0] = "<permission>  protectionLevel specifies a flag but is "
1723                        + "not based on signature type";
1724                mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1725                return null;
1726            }
1727        }
1728
1729        if (!parseAllMetaData(res, parser, attrs, "<permission>", perm,
1730                outError)) {
1731            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1732            return null;
1733        }
1734
1735        owner.permissions.add(perm);
1736
1737        return perm;
1738    }
1739
1740    private Permission parsePermissionTree(Package owner, Resources res,
1741            XmlPullParser parser, AttributeSet attrs, String[] outError)
1742        throws XmlPullParserException, IOException {
1743        Permission perm = new Permission(owner);
1744
1745        TypedArray sa = res.obtainAttributes(attrs,
1746                com.android.internal.R.styleable.AndroidManifestPermissionTree);
1747
1748        if (!parsePackageItemInfo(owner, perm.info, outError,
1749                "<permission-tree>", sa,
1750                com.android.internal.R.styleable.AndroidManifestPermissionTree_name,
1751                com.android.internal.R.styleable.AndroidManifestPermissionTree_label,
1752                com.android.internal.R.styleable.AndroidManifestPermissionTree_icon,
1753                com.android.internal.R.styleable.AndroidManifestPermissionTree_logo)) {
1754            sa.recycle();
1755            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1756            return null;
1757        }
1758
1759        sa.recycle();
1760
1761        int index = perm.info.name.indexOf('.');
1762        if (index > 0) {
1763            index = perm.info.name.indexOf('.', index+1);
1764        }
1765        if (index < 0) {
1766            outError[0] = "<permission-tree> name has less than three segments: "
1767                + perm.info.name;
1768            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1769            return null;
1770        }
1771
1772        perm.info.descriptionRes = 0;
1773        perm.info.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
1774        perm.tree = true;
1775
1776        if (!parseAllMetaData(res, parser, attrs, "<permission-tree>", perm,
1777                outError)) {
1778            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1779            return null;
1780        }
1781
1782        owner.permissions.add(perm);
1783
1784        return perm;
1785    }
1786
1787    private Instrumentation parseInstrumentation(Package owner, Resources res,
1788            XmlPullParser parser, AttributeSet attrs, String[] outError)
1789        throws XmlPullParserException, IOException {
1790        TypedArray sa = res.obtainAttributes(attrs,
1791                com.android.internal.R.styleable.AndroidManifestInstrumentation);
1792
1793        if (mParseInstrumentationArgs == null) {
1794            mParseInstrumentationArgs = new ParsePackageItemArgs(owner, outError,
1795                    com.android.internal.R.styleable.AndroidManifestInstrumentation_name,
1796                    com.android.internal.R.styleable.AndroidManifestInstrumentation_label,
1797                    com.android.internal.R.styleable.AndroidManifestInstrumentation_icon,
1798                    com.android.internal.R.styleable.AndroidManifestInstrumentation_logo);
1799            mParseInstrumentationArgs.tag = "<instrumentation>";
1800        }
1801
1802        mParseInstrumentationArgs.sa = sa;
1803
1804        Instrumentation a = new Instrumentation(mParseInstrumentationArgs,
1805                new InstrumentationInfo());
1806        if (outError[0] != null) {
1807            sa.recycle();
1808            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1809            return null;
1810        }
1811
1812        String str;
1813        // Note: don't allow this value to be a reference to a resource
1814        // that may change.
1815        str = sa.getNonResourceString(
1816                com.android.internal.R.styleable.AndroidManifestInstrumentation_targetPackage);
1817        a.info.targetPackage = str != null ? str.intern() : null;
1818
1819        a.info.handleProfiling = sa.getBoolean(
1820                com.android.internal.R.styleable.AndroidManifestInstrumentation_handleProfiling,
1821                false);
1822
1823        a.info.functionalTest = sa.getBoolean(
1824                com.android.internal.R.styleable.AndroidManifestInstrumentation_functionalTest,
1825                false);
1826
1827        sa.recycle();
1828
1829        if (a.info.targetPackage == null) {
1830            outError[0] = "<instrumentation> does not specify targetPackage";
1831            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1832            return null;
1833        }
1834
1835        if (!parseAllMetaData(res, parser, attrs, "<instrumentation>", a,
1836                outError)) {
1837            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1838            return null;
1839        }
1840
1841        owner.instrumentation.add(a);
1842
1843        return a;
1844    }
1845
1846    private boolean parseApplication(Package owner, Resources res,
1847            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
1848        throws XmlPullParserException, IOException {
1849        final ApplicationInfo ai = owner.applicationInfo;
1850        final String pkgName = owner.applicationInfo.packageName;
1851
1852        TypedArray sa = res.obtainAttributes(attrs,
1853                com.android.internal.R.styleable.AndroidManifestApplication);
1854
1855        String name = sa.getNonConfigurationString(
1856                com.android.internal.R.styleable.AndroidManifestApplication_name, 0);
1857        if (name != null) {
1858            ai.className = buildClassName(pkgName, name, outError);
1859            if (ai.className == null) {
1860                sa.recycle();
1861                mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
1862                return false;
1863            }
1864        }
1865
1866        String manageSpaceActivity = sa.getNonConfigurationString(
1867                com.android.internal.R.styleable.AndroidManifestApplication_manageSpaceActivity, 0);
1868        if (manageSpaceActivity != null) {
1869            ai.manageSpaceActivityName = buildClassName(pkgName, manageSpaceActivity,
1870                    outError);
1871        }
1872
1873        boolean allowBackup = sa.getBoolean(
1874                com.android.internal.R.styleable.AndroidManifestApplication_allowBackup, true);
1875        if (allowBackup) {
1876            ai.flags |= ApplicationInfo.FLAG_ALLOW_BACKUP;
1877
1878            // backupAgent, killAfterRestore, and restoreAnyVersion are only relevant
1879            // if backup is possible for the given application.
1880            String backupAgent = sa.getNonConfigurationString(
1881                    com.android.internal.R.styleable.AndroidManifestApplication_backupAgent, 0);
1882            if (backupAgent != null) {
1883                ai.backupAgentName = buildClassName(pkgName, backupAgent, outError);
1884                if (DEBUG_BACKUP) {
1885                    Slog.v(TAG, "android:backupAgent = " + ai.backupAgentName
1886                            + " from " + pkgName + "+" + backupAgent);
1887                }
1888
1889                if (sa.getBoolean(
1890                        com.android.internal.R.styleable.AndroidManifestApplication_killAfterRestore,
1891                        true)) {
1892                    ai.flags |= ApplicationInfo.FLAG_KILL_AFTER_RESTORE;
1893                }
1894                if (sa.getBoolean(
1895                        com.android.internal.R.styleable.AndroidManifestApplication_restoreAnyVersion,
1896                        false)) {
1897                    ai.flags |= ApplicationInfo.FLAG_RESTORE_ANY_VERSION;
1898                }
1899            }
1900        }
1901
1902        TypedValue v = sa.peekValue(
1903                com.android.internal.R.styleable.AndroidManifestApplication_label);
1904        if (v != null && (ai.labelRes=v.resourceId) == 0) {
1905            ai.nonLocalizedLabel = v.coerceToString();
1906        }
1907
1908        ai.icon = sa.getResourceId(
1909                com.android.internal.R.styleable.AndroidManifestApplication_icon, 0);
1910        ai.logo = sa.getResourceId(
1911                com.android.internal.R.styleable.AndroidManifestApplication_logo, 0);
1912        ai.theme = sa.getResourceId(
1913                com.android.internal.R.styleable.AndroidManifestApplication_theme, 0);
1914        ai.descriptionRes = sa.getResourceId(
1915                com.android.internal.R.styleable.AndroidManifestApplication_description, 0);
1916
1917        if ((flags&PARSE_IS_SYSTEM) != 0) {
1918            if (sa.getBoolean(
1919                    com.android.internal.R.styleable.AndroidManifestApplication_persistent,
1920                    false)) {
1921                ai.flags |= ApplicationInfo.FLAG_PERSISTENT;
1922            }
1923        }
1924
1925        if (sa.getBoolean(
1926                com.android.internal.R.styleable.AndroidManifestApplication_requiredForAllUsers,
1927                false)) {
1928            owner.mRequiredForAllUsers = true;
1929        }
1930
1931        String restrictedAccountType = sa.getString(com.android.internal.R.styleable
1932                .AndroidManifestApplication_restrictedAccountType);
1933        if (restrictedAccountType != null && restrictedAccountType.length() > 0) {
1934            owner.mRestrictedAccountType = restrictedAccountType;
1935        }
1936
1937        String requiredAccountType = sa.getString(com.android.internal.R.styleable
1938                .AndroidManifestApplication_requiredAccountType);
1939        if (requiredAccountType != null && requiredAccountType.length() > 0) {
1940            owner.mRequiredAccountType = requiredAccountType;
1941        }
1942
1943        if (sa.getBoolean(
1944                com.android.internal.R.styleable.AndroidManifestApplication_debuggable,
1945                false)) {
1946            ai.flags |= ApplicationInfo.FLAG_DEBUGGABLE;
1947        }
1948
1949        if (sa.getBoolean(
1950                com.android.internal.R.styleable.AndroidManifestApplication_vmSafeMode,
1951                false)) {
1952            ai.flags |= ApplicationInfo.FLAG_VM_SAFE_MODE;
1953        }
1954
1955        boolean hardwareAccelerated = sa.getBoolean(
1956                com.android.internal.R.styleable.AndroidManifestApplication_hardwareAccelerated,
1957                owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH);
1958
1959        if (sa.getBoolean(
1960                com.android.internal.R.styleable.AndroidManifestApplication_hasCode,
1961                true)) {
1962            ai.flags |= ApplicationInfo.FLAG_HAS_CODE;
1963        }
1964
1965        if (sa.getBoolean(
1966                com.android.internal.R.styleable.AndroidManifestApplication_allowTaskReparenting,
1967                false)) {
1968            ai.flags |= ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING;
1969        }
1970
1971        if (sa.getBoolean(
1972                com.android.internal.R.styleable.AndroidManifestApplication_allowClearUserData,
1973                true)) {
1974            ai.flags |= ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA;
1975        }
1976
1977        if (sa.getBoolean(
1978                com.android.internal.R.styleable.AndroidManifestApplication_testOnly,
1979                false)) {
1980            ai.flags |= ApplicationInfo.FLAG_TEST_ONLY;
1981        }
1982
1983        if (sa.getBoolean(
1984                com.android.internal.R.styleable.AndroidManifestApplication_largeHeap,
1985                false)) {
1986            ai.flags |= ApplicationInfo.FLAG_LARGE_HEAP;
1987        }
1988
1989        if (sa.getBoolean(
1990                com.android.internal.R.styleable.AndroidManifestApplication_supportsRtl,
1991                false /* default is no RTL support*/)) {
1992            ai.flags |= ApplicationInfo.FLAG_SUPPORTS_RTL;
1993        }
1994
1995        String str;
1996        str = sa.getNonConfigurationString(
1997                com.android.internal.R.styleable.AndroidManifestApplication_permission, 0);
1998        ai.permission = (str != null && str.length() > 0) ? str.intern() : null;
1999
2000        if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2001            str = sa.getNonConfigurationString(
2002                    com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity, 0);
2003        } else {
2004            // Some older apps have been seen to use a resource reference
2005            // here that on older builds was ignored (with a warning).  We
2006            // need to continue to do this for them so they don't break.
2007            str = sa.getNonResourceString(
2008                    com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity);
2009        }
2010        ai.taskAffinity = buildTaskAffinityName(ai.packageName, ai.packageName,
2011                str, outError);
2012
2013        if (outError[0] == null) {
2014            CharSequence pname;
2015            if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2016                pname = sa.getNonConfigurationString(
2017                        com.android.internal.R.styleable.AndroidManifestApplication_process, 0);
2018            } else {
2019                // Some older apps have been seen to use a resource reference
2020                // here that on older builds was ignored (with a warning).  We
2021                // need to continue to do this for them so they don't break.
2022                pname = sa.getNonResourceString(
2023                        com.android.internal.R.styleable.AndroidManifestApplication_process);
2024            }
2025            ai.processName = buildProcessName(ai.packageName, null, pname,
2026                    flags, mSeparateProcesses, outError);
2027
2028            ai.enabled = sa.getBoolean(
2029                    com.android.internal.R.styleable.AndroidManifestApplication_enabled, true);
2030
2031            if (false) {
2032                if (sa.getBoolean(
2033                        com.android.internal.R.styleable.AndroidManifestApplication_cantSaveState,
2034                        false)) {
2035                    ai.flags |= ApplicationInfo.FLAG_CANT_SAVE_STATE;
2036
2037                    // A heavy-weight application can not be in a custom process.
2038                    // We can do direct compare because we intern all strings.
2039                    if (ai.processName != null && ai.processName != ai.packageName) {
2040                        outError[0] = "cantSaveState applications can not use custom processes";
2041                    }
2042                }
2043            }
2044        }
2045
2046        ai.uiOptions = sa.getInt(
2047                com.android.internal.R.styleable.AndroidManifestApplication_uiOptions, 0);
2048
2049        sa.recycle();
2050
2051        if (outError[0] != null) {
2052            mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2053            return false;
2054        }
2055
2056        final int innerDepth = parser.getDepth();
2057
2058        int type;
2059        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2060                && (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
2061            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2062                continue;
2063            }
2064
2065            String tagName = parser.getName();
2066            if (tagName.equals("activity")) {
2067                Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false,
2068                        hardwareAccelerated);
2069                if (a == null) {
2070                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2071                    return false;
2072                }
2073
2074                owner.activities.add(a);
2075
2076            } else if (tagName.equals("receiver")) {
2077                Activity a = parseActivity(owner, res, parser, attrs, flags, outError, true, false);
2078                if (a == null) {
2079                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2080                    return false;
2081                }
2082
2083                owner.receivers.add(a);
2084
2085            } else if (tagName.equals("service")) {
2086                Service s = parseService(owner, res, parser, attrs, flags, outError);
2087                if (s == null) {
2088                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2089                    return false;
2090                }
2091
2092                owner.services.add(s);
2093
2094            } else if (tagName.equals("provider")) {
2095                Provider p = parseProvider(owner, res, parser, attrs, flags, outError);
2096                if (p == null) {
2097                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2098                    return false;
2099                }
2100
2101                owner.providers.add(p);
2102
2103            } else if (tagName.equals("activity-alias")) {
2104                Activity a = parseActivityAlias(owner, res, parser, attrs, flags, outError);
2105                if (a == null) {
2106                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2107                    return false;
2108                }
2109
2110                owner.activities.add(a);
2111
2112            } else if (parser.getName().equals("meta-data")) {
2113                // note: application meta-data is stored off to the side, so it can
2114                // remain null in the primary copy (we like to avoid extra copies because
2115                // it can be large)
2116                if ((owner.mAppMetaData = parseMetaData(res, parser, attrs, owner.mAppMetaData,
2117                        outError)) == null) {
2118                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2119                    return false;
2120                }
2121
2122            } else if (tagName.equals("library")) {
2123                sa = res.obtainAttributes(attrs,
2124                        com.android.internal.R.styleable.AndroidManifestLibrary);
2125
2126                // Note: don't allow this value to be a reference to a resource
2127                // that may change.
2128                String lname = sa.getNonResourceString(
2129                        com.android.internal.R.styleable.AndroidManifestLibrary_name);
2130
2131                sa.recycle();
2132
2133                if (lname != null) {
2134                    if (owner.libraryNames == null) {
2135                        owner.libraryNames = new ArrayList<String>();
2136                    }
2137                    if (!owner.libraryNames.contains(lname)) {
2138                        owner.libraryNames.add(lname.intern());
2139                    }
2140                }
2141
2142                XmlUtils.skipCurrentTag(parser);
2143
2144            } else if (tagName.equals("uses-library")) {
2145                sa = res.obtainAttributes(attrs,
2146                        com.android.internal.R.styleable.AndroidManifestUsesLibrary);
2147
2148                // Note: don't allow this value to be a reference to a resource
2149                // that may change.
2150                String lname = sa.getNonResourceString(
2151                        com.android.internal.R.styleable.AndroidManifestUsesLibrary_name);
2152                boolean req = sa.getBoolean(
2153                        com.android.internal.R.styleable.AndroidManifestUsesLibrary_required,
2154                        true);
2155
2156                sa.recycle();
2157
2158                if (lname != null) {
2159                    if (req) {
2160                        if (owner.usesLibraries == null) {
2161                            owner.usesLibraries = new ArrayList<String>();
2162                        }
2163                        if (!owner.usesLibraries.contains(lname)) {
2164                            owner.usesLibraries.add(lname.intern());
2165                        }
2166                    } else {
2167                        if (owner.usesOptionalLibraries == null) {
2168                            owner.usesOptionalLibraries = new ArrayList<String>();
2169                        }
2170                        if (!owner.usesOptionalLibraries.contains(lname)) {
2171                            owner.usesOptionalLibraries.add(lname.intern());
2172                        }
2173                    }
2174                }
2175
2176                XmlUtils.skipCurrentTag(parser);
2177
2178            } else if (tagName.equals("uses-package")) {
2179                // Dependencies for app installers; we don't currently try to
2180                // enforce this.
2181                XmlUtils.skipCurrentTag(parser);
2182
2183            } else {
2184                if (!RIGID_PARSER) {
2185                    Slog.w(TAG, "Unknown element under <application>: " + tagName
2186                            + " at " + mArchiveSourcePath + " "
2187                            + parser.getPositionDescription());
2188                    XmlUtils.skipCurrentTag(parser);
2189                    continue;
2190                } else {
2191                    outError[0] = "Bad element under <application>: " + tagName;
2192                    mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
2193                    return false;
2194                }
2195            }
2196        }
2197
2198        return true;
2199    }
2200
2201    private boolean parsePackageItemInfo(Package owner, PackageItemInfo outInfo,
2202            String[] outError, String tag, TypedArray sa,
2203            int nameRes, int labelRes, int iconRes, int logoRes) {
2204        String name = sa.getNonConfigurationString(nameRes, 0);
2205        if (name == null) {
2206            outError[0] = tag + " does not specify android:name";
2207            return false;
2208        }
2209
2210        outInfo.name
2211            = buildClassName(owner.applicationInfo.packageName, name, outError);
2212        if (outInfo.name == null) {
2213            return false;
2214        }
2215
2216        int iconVal = sa.getResourceId(iconRes, 0);
2217        if (iconVal != 0) {
2218            outInfo.icon = iconVal;
2219            outInfo.nonLocalizedLabel = null;
2220        }
2221
2222        int logoVal = sa.getResourceId(logoRes, 0);
2223        if (logoVal != 0) {
2224            outInfo.logo = logoVal;
2225        }
2226
2227        TypedValue v = sa.peekValue(labelRes);
2228        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
2229            outInfo.nonLocalizedLabel = v.coerceToString();
2230        }
2231
2232        outInfo.packageName = owner.packageName;
2233
2234        return true;
2235    }
2236
2237    private Activity parseActivity(Package owner, Resources res,
2238            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError,
2239            boolean receiver, boolean hardwareAccelerated)
2240            throws XmlPullParserException, IOException {
2241        TypedArray sa = res.obtainAttributes(attrs,
2242                com.android.internal.R.styleable.AndroidManifestActivity);
2243
2244        if (mParseActivityArgs == null) {
2245            mParseActivityArgs = new ParseComponentArgs(owner, outError,
2246                    com.android.internal.R.styleable.AndroidManifestActivity_name,
2247                    com.android.internal.R.styleable.AndroidManifestActivity_label,
2248                    com.android.internal.R.styleable.AndroidManifestActivity_icon,
2249                    com.android.internal.R.styleable.AndroidManifestActivity_logo,
2250                    mSeparateProcesses,
2251                    com.android.internal.R.styleable.AndroidManifestActivity_process,
2252                    com.android.internal.R.styleable.AndroidManifestActivity_description,
2253                    com.android.internal.R.styleable.AndroidManifestActivity_enabled);
2254        }
2255
2256        mParseActivityArgs.tag = receiver ? "<receiver>" : "<activity>";
2257        mParseActivityArgs.sa = sa;
2258        mParseActivityArgs.flags = flags;
2259
2260        Activity a = new Activity(mParseActivityArgs, new ActivityInfo());
2261        if (outError[0] != null) {
2262            sa.recycle();
2263            return null;
2264        }
2265
2266        boolean setExported = sa.hasValue(
2267                com.android.internal.R.styleable.AndroidManifestActivity_exported);
2268        if (setExported) {
2269            a.info.exported = sa.getBoolean(
2270                    com.android.internal.R.styleable.AndroidManifestActivity_exported, false);
2271        }
2272
2273        a.info.theme = sa.getResourceId(
2274                com.android.internal.R.styleable.AndroidManifestActivity_theme, 0);
2275
2276        a.info.uiOptions = sa.getInt(
2277                com.android.internal.R.styleable.AndroidManifestActivity_uiOptions,
2278                a.info.applicationInfo.uiOptions);
2279
2280        String parentName = sa.getNonConfigurationString(
2281                com.android.internal.R.styleable.AndroidManifestActivity_parentActivityName, 0);
2282        if (parentName != null) {
2283            String parentClassName = buildClassName(a.info.packageName, parentName, outError);
2284            if (outError[0] == null) {
2285                a.info.parentActivityName = parentClassName;
2286            } else {
2287                Log.e(TAG, "Activity " + a.info.name + " specified invalid parentActivityName " +
2288                        parentName);
2289                outError[0] = null;
2290            }
2291        }
2292
2293        String str;
2294        str = sa.getNonConfigurationString(
2295                com.android.internal.R.styleable.AndroidManifestActivity_permission, 0);
2296        if (str == null) {
2297            a.info.permission = owner.applicationInfo.permission;
2298        } else {
2299            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
2300        }
2301
2302        str = sa.getNonConfigurationString(
2303                com.android.internal.R.styleable.AndroidManifestActivity_taskAffinity, 0);
2304        a.info.taskAffinity = buildTaskAffinityName(owner.applicationInfo.packageName,
2305                owner.applicationInfo.taskAffinity, str, outError);
2306
2307        a.info.flags = 0;
2308        if (sa.getBoolean(
2309                com.android.internal.R.styleable.AndroidManifestActivity_multiprocess,
2310                false)) {
2311            a.info.flags |= ActivityInfo.FLAG_MULTIPROCESS;
2312        }
2313
2314        if (sa.getBoolean(
2315                com.android.internal.R.styleable.AndroidManifestActivity_finishOnTaskLaunch,
2316                false)) {
2317            a.info.flags |= ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH;
2318        }
2319
2320        if (sa.getBoolean(
2321                com.android.internal.R.styleable.AndroidManifestActivity_clearTaskOnLaunch,
2322                false)) {
2323            a.info.flags |= ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH;
2324        }
2325
2326        if (sa.getBoolean(
2327                com.android.internal.R.styleable.AndroidManifestActivity_noHistory,
2328                false)) {
2329            a.info.flags |= ActivityInfo.FLAG_NO_HISTORY;
2330        }
2331
2332        if (sa.getBoolean(
2333                com.android.internal.R.styleable.AndroidManifestActivity_alwaysRetainTaskState,
2334                false)) {
2335            a.info.flags |= ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE;
2336        }
2337
2338        if (sa.getBoolean(
2339                com.android.internal.R.styleable.AndroidManifestActivity_stateNotNeeded,
2340                false)) {
2341            a.info.flags |= ActivityInfo.FLAG_STATE_NOT_NEEDED;
2342        }
2343
2344        if (sa.getBoolean(
2345                com.android.internal.R.styleable.AndroidManifestActivity_excludeFromRecents,
2346                false)) {
2347            a.info.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2348        }
2349
2350        if (sa.getBoolean(
2351                com.android.internal.R.styleable.AndroidManifestActivity_allowTaskReparenting,
2352                (owner.applicationInfo.flags&ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING) != 0)) {
2353            a.info.flags |= ActivityInfo.FLAG_ALLOW_TASK_REPARENTING;
2354        }
2355
2356        if (sa.getBoolean(
2357                com.android.internal.R.styleable.AndroidManifestActivity_finishOnCloseSystemDialogs,
2358                false)) {
2359            a.info.flags |= ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
2360        }
2361
2362        if (sa.getBoolean(
2363                com.android.internal.R.styleable.AndroidManifestActivity_showOnLockScreen,
2364                false)) {
2365            a.info.flags |= ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN;
2366        }
2367
2368        if (sa.getBoolean(
2369                com.android.internal.R.styleable.AndroidManifestActivity_immersive,
2370                false)) {
2371            a.info.flags |= ActivityInfo.FLAG_IMMERSIVE;
2372        }
2373
2374        if (!receiver) {
2375            if (sa.getBoolean(
2376                    com.android.internal.R.styleable.AndroidManifestActivity_hardwareAccelerated,
2377                    hardwareAccelerated)) {
2378                a.info.flags |= ActivityInfo.FLAG_HARDWARE_ACCELERATED;
2379            }
2380
2381            a.info.launchMode = sa.getInt(
2382                    com.android.internal.R.styleable.AndroidManifestActivity_launchMode,
2383                    ActivityInfo.LAUNCH_MULTIPLE);
2384            a.info.screenOrientation = sa.getInt(
2385                    com.android.internal.R.styleable.AndroidManifestActivity_screenOrientation,
2386                    ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
2387            a.info.configChanges = sa.getInt(
2388                    com.android.internal.R.styleable.AndroidManifestActivity_configChanges,
2389                    0);
2390            a.info.softInputMode = sa.getInt(
2391                    com.android.internal.R.styleable.AndroidManifestActivity_windowSoftInputMode,
2392                    0);
2393        } else {
2394            a.info.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2395            a.info.configChanges = 0;
2396        }
2397
2398        if (receiver) {
2399            if (sa.getBoolean(
2400                    com.android.internal.R.styleable.AndroidManifestActivity_singleUser,
2401                    false)) {
2402                a.info.flags |= ActivityInfo.FLAG_SINGLE_USER;
2403                if (a.info.exported) {
2404                    Slog.w(TAG, "Activity exported request ignored due to singleUser: "
2405                            + a.className + " at " + mArchiveSourcePath + " "
2406                            + parser.getPositionDescription());
2407                    a.info.exported = false;
2408                }
2409                setExported = true;
2410            }
2411            if (sa.getBoolean(
2412                    com.android.internal.R.styleable.AndroidManifestActivity_primaryUserOnly,
2413                    false)) {
2414                a.info.flags |= ActivityInfo.FLAG_PRIMARY_USER_ONLY;
2415            }
2416        }
2417
2418        sa.recycle();
2419
2420        if (receiver && (owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2421            // A heavy-weight application can not have receives in its main process
2422            // We can do direct compare because we intern all strings.
2423            if (a.info.processName == owner.packageName) {
2424                outError[0] = "Heavy-weight applications can not have receivers in main process";
2425            }
2426        }
2427
2428        if (outError[0] != null) {
2429            return null;
2430        }
2431
2432        int outerDepth = parser.getDepth();
2433        int type;
2434        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2435               && (type != XmlPullParser.END_TAG
2436                       || parser.getDepth() > outerDepth)) {
2437            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2438                continue;
2439            }
2440
2441            if (parser.getName().equals("intent-filter")) {
2442                ActivityIntentInfo intent = new ActivityIntentInfo(a);
2443                if (!parseIntent(res, parser, attrs, flags, intent, outError, !receiver)) {
2444                    return null;
2445                }
2446                if (intent.countActions() == 0) {
2447                    Slog.w(TAG, "No actions in intent filter at "
2448                            + mArchiveSourcePath + " "
2449                            + parser.getPositionDescription());
2450                } else {
2451                    a.intents.add(intent);
2452                }
2453            } else if (parser.getName().equals("meta-data")) {
2454                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
2455                        outError)) == null) {
2456                    return null;
2457                }
2458            } else {
2459                if (!RIGID_PARSER) {
2460                    Slog.w(TAG, "Problem in package " + mArchiveSourcePath + ":");
2461                    if (receiver) {
2462                        Slog.w(TAG, "Unknown element under <receiver>: " + parser.getName()
2463                                + " at " + mArchiveSourcePath + " "
2464                                + parser.getPositionDescription());
2465                    } else {
2466                        Slog.w(TAG, "Unknown element under <activity>: " + parser.getName()
2467                                + " at " + mArchiveSourcePath + " "
2468                                + parser.getPositionDescription());
2469                    }
2470                    XmlUtils.skipCurrentTag(parser);
2471                    continue;
2472                } else {
2473                    if (receiver) {
2474                        outError[0] = "Bad element under <receiver>: " + parser.getName();
2475                    } else {
2476                        outError[0] = "Bad element under <activity>: " + parser.getName();
2477                    }
2478                    return null;
2479                }
2480            }
2481        }
2482
2483        if (!setExported) {
2484            a.info.exported = a.intents.size() > 0;
2485        }
2486
2487        return a;
2488    }
2489
2490    private Activity parseActivityAlias(Package owner, Resources res,
2491            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2492            throws XmlPullParserException, IOException {
2493        TypedArray sa = res.obtainAttributes(attrs,
2494                com.android.internal.R.styleable.AndroidManifestActivityAlias);
2495
2496        String targetActivity = sa.getNonConfigurationString(
2497                com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity, 0);
2498        if (targetActivity == null) {
2499            outError[0] = "<activity-alias> does not specify android:targetActivity";
2500            sa.recycle();
2501            return null;
2502        }
2503
2504        targetActivity = buildClassName(owner.applicationInfo.packageName,
2505                targetActivity, outError);
2506        if (targetActivity == null) {
2507            sa.recycle();
2508            return null;
2509        }
2510
2511        if (mParseActivityAliasArgs == null) {
2512            mParseActivityAliasArgs = new ParseComponentArgs(owner, outError,
2513                    com.android.internal.R.styleable.AndroidManifestActivityAlias_name,
2514                    com.android.internal.R.styleable.AndroidManifestActivityAlias_label,
2515                    com.android.internal.R.styleable.AndroidManifestActivityAlias_icon,
2516                    com.android.internal.R.styleable.AndroidManifestActivityAlias_logo,
2517                    mSeparateProcesses,
2518                    0,
2519                    com.android.internal.R.styleable.AndroidManifestActivityAlias_description,
2520                    com.android.internal.R.styleable.AndroidManifestActivityAlias_enabled);
2521            mParseActivityAliasArgs.tag = "<activity-alias>";
2522        }
2523
2524        mParseActivityAliasArgs.sa = sa;
2525        mParseActivityAliasArgs.flags = flags;
2526
2527        Activity target = null;
2528
2529        final int NA = owner.activities.size();
2530        for (int i=0; i<NA; i++) {
2531            Activity t = owner.activities.get(i);
2532            if (targetActivity.equals(t.info.name)) {
2533                target = t;
2534                break;
2535            }
2536        }
2537
2538        if (target == null) {
2539            outError[0] = "<activity-alias> target activity " + targetActivity
2540                    + " not found in manifest";
2541            sa.recycle();
2542            return null;
2543        }
2544
2545        ActivityInfo info = new ActivityInfo();
2546        info.targetActivity = targetActivity;
2547        info.configChanges = target.info.configChanges;
2548        info.flags = target.info.flags;
2549        info.icon = target.info.icon;
2550        info.logo = target.info.logo;
2551        info.labelRes = target.info.labelRes;
2552        info.nonLocalizedLabel = target.info.nonLocalizedLabel;
2553        info.launchMode = target.info.launchMode;
2554        info.processName = target.info.processName;
2555        if (info.descriptionRes == 0) {
2556            info.descriptionRes = target.info.descriptionRes;
2557        }
2558        info.screenOrientation = target.info.screenOrientation;
2559        info.taskAffinity = target.info.taskAffinity;
2560        info.theme = target.info.theme;
2561        info.softInputMode = target.info.softInputMode;
2562        info.uiOptions = target.info.uiOptions;
2563        info.parentActivityName = target.info.parentActivityName;
2564
2565        Activity a = new Activity(mParseActivityAliasArgs, info);
2566        if (outError[0] != null) {
2567            sa.recycle();
2568            return null;
2569        }
2570
2571        final boolean setExported = sa.hasValue(
2572                com.android.internal.R.styleable.AndroidManifestActivityAlias_exported);
2573        if (setExported) {
2574            a.info.exported = sa.getBoolean(
2575                    com.android.internal.R.styleable.AndroidManifestActivityAlias_exported, false);
2576        }
2577
2578        String str;
2579        str = sa.getNonConfigurationString(
2580                com.android.internal.R.styleable.AndroidManifestActivityAlias_permission, 0);
2581        if (str != null) {
2582            a.info.permission = str.length() > 0 ? str.toString().intern() : null;
2583        }
2584
2585        String parentName = sa.getNonConfigurationString(
2586                com.android.internal.R.styleable.AndroidManifestActivityAlias_parentActivityName,
2587                0);
2588        if (parentName != null) {
2589            String parentClassName = buildClassName(a.info.packageName, parentName, outError);
2590            if (outError[0] == null) {
2591                a.info.parentActivityName = parentClassName;
2592            } else {
2593                Log.e(TAG, "Activity alias " + a.info.name +
2594                        " specified invalid parentActivityName " + parentName);
2595                outError[0] = null;
2596            }
2597        }
2598
2599        sa.recycle();
2600
2601        if (outError[0] != null) {
2602            return null;
2603        }
2604
2605        int outerDepth = parser.getDepth();
2606        int type;
2607        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2608               && (type != XmlPullParser.END_TAG
2609                       || parser.getDepth() > outerDepth)) {
2610            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2611                continue;
2612            }
2613
2614            if (parser.getName().equals("intent-filter")) {
2615                ActivityIntentInfo intent = new ActivityIntentInfo(a);
2616                if (!parseIntent(res, parser, attrs, flags, intent, outError, true)) {
2617                    return null;
2618                }
2619                if (intent.countActions() == 0) {
2620                    Slog.w(TAG, "No actions in intent filter at "
2621                            + mArchiveSourcePath + " "
2622                            + parser.getPositionDescription());
2623                } else {
2624                    a.intents.add(intent);
2625                }
2626            } else if (parser.getName().equals("meta-data")) {
2627                if ((a.metaData=parseMetaData(res, parser, attrs, a.metaData,
2628                        outError)) == null) {
2629                    return null;
2630                }
2631            } else {
2632                if (!RIGID_PARSER) {
2633                    Slog.w(TAG, "Unknown element under <activity-alias>: " + parser.getName()
2634                            + " at " + mArchiveSourcePath + " "
2635                            + parser.getPositionDescription());
2636                    XmlUtils.skipCurrentTag(parser);
2637                    continue;
2638                } else {
2639                    outError[0] = "Bad element under <activity-alias>: " + parser.getName();
2640                    return null;
2641                }
2642            }
2643        }
2644
2645        if (!setExported) {
2646            a.info.exported = a.intents.size() > 0;
2647        }
2648
2649        return a;
2650    }
2651
2652    private Provider parseProvider(Package owner, Resources res,
2653            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2654            throws XmlPullParserException, IOException {
2655        TypedArray sa = res.obtainAttributes(attrs,
2656                com.android.internal.R.styleable.AndroidManifestProvider);
2657
2658        if (mParseProviderArgs == null) {
2659            mParseProviderArgs = new ParseComponentArgs(owner, outError,
2660                    com.android.internal.R.styleable.AndroidManifestProvider_name,
2661                    com.android.internal.R.styleable.AndroidManifestProvider_label,
2662                    com.android.internal.R.styleable.AndroidManifestProvider_icon,
2663                    com.android.internal.R.styleable.AndroidManifestProvider_logo,
2664                    mSeparateProcesses,
2665                    com.android.internal.R.styleable.AndroidManifestProvider_process,
2666                    com.android.internal.R.styleable.AndroidManifestProvider_description,
2667                    com.android.internal.R.styleable.AndroidManifestProvider_enabled);
2668            mParseProviderArgs.tag = "<provider>";
2669        }
2670
2671        mParseProviderArgs.sa = sa;
2672        mParseProviderArgs.flags = flags;
2673
2674        Provider p = new Provider(mParseProviderArgs, new ProviderInfo());
2675        if (outError[0] != null) {
2676            sa.recycle();
2677            return null;
2678        }
2679
2680        boolean providerExportedDefault = false;
2681
2682        if (owner.applicationInfo.targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
2683            // For compatibility, applications targeting API level 16 or lower
2684            // should have their content providers exported by default, unless they
2685            // specify otherwise.
2686            providerExportedDefault = true;
2687        }
2688
2689        p.info.exported = sa.getBoolean(
2690                com.android.internal.R.styleable.AndroidManifestProvider_exported,
2691                providerExportedDefault);
2692
2693        String cpname = sa.getNonConfigurationString(
2694                com.android.internal.R.styleable.AndroidManifestProvider_authorities, 0);
2695
2696        p.info.isSyncable = sa.getBoolean(
2697                com.android.internal.R.styleable.AndroidManifestProvider_syncable,
2698                false);
2699
2700        String permission = sa.getNonConfigurationString(
2701                com.android.internal.R.styleable.AndroidManifestProvider_permission, 0);
2702        String str = sa.getNonConfigurationString(
2703                com.android.internal.R.styleable.AndroidManifestProvider_readPermission, 0);
2704        if (str == null) {
2705            str = permission;
2706        }
2707        if (str == null) {
2708            p.info.readPermission = owner.applicationInfo.permission;
2709        } else {
2710            p.info.readPermission =
2711                str.length() > 0 ? str.toString().intern() : null;
2712        }
2713        str = sa.getNonConfigurationString(
2714                com.android.internal.R.styleable.AndroidManifestProvider_writePermission, 0);
2715        if (str == null) {
2716            str = permission;
2717        }
2718        if (str == null) {
2719            p.info.writePermission = owner.applicationInfo.permission;
2720        } else {
2721            p.info.writePermission =
2722                str.length() > 0 ? str.toString().intern() : null;
2723        }
2724
2725        p.info.grantUriPermissions = sa.getBoolean(
2726                com.android.internal.R.styleable.AndroidManifestProvider_grantUriPermissions,
2727                false);
2728
2729        p.info.multiprocess = sa.getBoolean(
2730                com.android.internal.R.styleable.AndroidManifestProvider_multiprocess,
2731                false);
2732
2733        p.info.initOrder = sa.getInt(
2734                com.android.internal.R.styleable.AndroidManifestProvider_initOrder,
2735                0);
2736
2737        p.info.flags = 0;
2738
2739        if (sa.getBoolean(
2740                com.android.internal.R.styleable.AndroidManifestProvider_singleUser,
2741                false)) {
2742            p.info.flags |= ProviderInfo.FLAG_SINGLE_USER;
2743            if (p.info.exported) {
2744                Slog.w(TAG, "Provider exported request ignored due to singleUser: "
2745                        + p.className + " at " + mArchiveSourcePath + " "
2746                        + parser.getPositionDescription());
2747                p.info.exported = false;
2748            }
2749        }
2750
2751        sa.recycle();
2752
2753        if ((owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2754            // A heavy-weight application can not have providers in its main process
2755            // We can do direct compare because we intern all strings.
2756            if (p.info.processName == owner.packageName) {
2757                outError[0] = "Heavy-weight applications can not have providers in main process";
2758                return null;
2759            }
2760        }
2761
2762        if (cpname == null) {
2763            outError[0] = "<provider> does not include authorities attribute";
2764            return null;
2765        }
2766        p.info.authority = cpname.intern();
2767
2768        if (!parseProviderTags(res, parser, attrs, p, outError)) {
2769            return null;
2770        }
2771
2772        return p;
2773    }
2774
2775    private boolean parseProviderTags(Resources res,
2776            XmlPullParser parser, AttributeSet attrs,
2777            Provider outInfo, String[] outError)
2778            throws XmlPullParserException, IOException {
2779        int outerDepth = parser.getDepth();
2780        int type;
2781        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2782               && (type != XmlPullParser.END_TAG
2783                       || parser.getDepth() > outerDepth)) {
2784            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2785                continue;
2786            }
2787
2788            if (parser.getName().equals("meta-data")) {
2789                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
2790                        outInfo.metaData, outError)) == null) {
2791                    return false;
2792                }
2793
2794            } else if (parser.getName().equals("grant-uri-permission")) {
2795                TypedArray sa = res.obtainAttributes(attrs,
2796                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission);
2797
2798                PatternMatcher pa = null;
2799
2800                String str = sa.getNonConfigurationString(
2801                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path, 0);
2802                if (str != null) {
2803                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_LITERAL);
2804                }
2805
2806                str = sa.getNonConfigurationString(
2807                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix, 0);
2808                if (str != null) {
2809                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_PREFIX);
2810                }
2811
2812                str = sa.getNonConfigurationString(
2813                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern, 0);
2814                if (str != null) {
2815                    pa = new PatternMatcher(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
2816                }
2817
2818                sa.recycle();
2819
2820                if (pa != null) {
2821                    if (outInfo.info.uriPermissionPatterns == null) {
2822                        outInfo.info.uriPermissionPatterns = new PatternMatcher[1];
2823                        outInfo.info.uriPermissionPatterns[0] = pa;
2824                    } else {
2825                        final int N = outInfo.info.uriPermissionPatterns.length;
2826                        PatternMatcher[] newp = new PatternMatcher[N+1];
2827                        System.arraycopy(outInfo.info.uriPermissionPatterns, 0, newp, 0, N);
2828                        newp[N] = pa;
2829                        outInfo.info.uriPermissionPatterns = newp;
2830                    }
2831                    outInfo.info.grantUriPermissions = true;
2832                } else {
2833                    if (!RIGID_PARSER) {
2834                        Slog.w(TAG, "Unknown element under <path-permission>: "
2835                                + parser.getName() + " at " + mArchiveSourcePath + " "
2836                                + parser.getPositionDescription());
2837                        XmlUtils.skipCurrentTag(parser);
2838                        continue;
2839                    } else {
2840                        outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2841                        return false;
2842                    }
2843                }
2844                XmlUtils.skipCurrentTag(parser);
2845
2846            } else if (parser.getName().equals("path-permission")) {
2847                TypedArray sa = res.obtainAttributes(attrs,
2848                        com.android.internal.R.styleable.AndroidManifestPathPermission);
2849
2850                PathPermission pa = null;
2851
2852                String permission = sa.getNonConfigurationString(
2853                        com.android.internal.R.styleable.AndroidManifestPathPermission_permission, 0);
2854                String readPermission = sa.getNonConfigurationString(
2855                        com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission, 0);
2856                if (readPermission == null) {
2857                    readPermission = permission;
2858                }
2859                String writePermission = sa.getNonConfigurationString(
2860                        com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission, 0);
2861                if (writePermission == null) {
2862                    writePermission = permission;
2863                }
2864
2865                boolean havePerm = false;
2866                if (readPermission != null) {
2867                    readPermission = readPermission.intern();
2868                    havePerm = true;
2869                }
2870                if (writePermission != null) {
2871                    writePermission = writePermission.intern();
2872                    havePerm = true;
2873                }
2874
2875                if (!havePerm) {
2876                    if (!RIGID_PARSER) {
2877                        Slog.w(TAG, "No readPermission or writePermssion for <path-permission>: "
2878                                + parser.getName() + " at " + mArchiveSourcePath + " "
2879                                + parser.getPositionDescription());
2880                        XmlUtils.skipCurrentTag(parser);
2881                        continue;
2882                    } else {
2883                        outError[0] = "No readPermission or writePermssion for <path-permission>";
2884                        return false;
2885                    }
2886                }
2887
2888                String path = sa.getNonConfigurationString(
2889                        com.android.internal.R.styleable.AndroidManifestPathPermission_path, 0);
2890                if (path != null) {
2891                    pa = new PathPermission(path,
2892                            PatternMatcher.PATTERN_LITERAL, readPermission, writePermission);
2893                }
2894
2895                path = sa.getNonConfigurationString(
2896                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix, 0);
2897                if (path != null) {
2898                    pa = new PathPermission(path,
2899                            PatternMatcher.PATTERN_PREFIX, readPermission, writePermission);
2900                }
2901
2902                path = sa.getNonConfigurationString(
2903                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern, 0);
2904                if (path != null) {
2905                    pa = new PathPermission(path,
2906                            PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
2907                }
2908
2909                sa.recycle();
2910
2911                if (pa != null) {
2912                    if (outInfo.info.pathPermissions == null) {
2913                        outInfo.info.pathPermissions = new PathPermission[1];
2914                        outInfo.info.pathPermissions[0] = pa;
2915                    } else {
2916                        final int N = outInfo.info.pathPermissions.length;
2917                        PathPermission[] newp = new PathPermission[N+1];
2918                        System.arraycopy(outInfo.info.pathPermissions, 0, newp, 0, N);
2919                        newp[N] = pa;
2920                        outInfo.info.pathPermissions = newp;
2921                    }
2922                } else {
2923                    if (!RIGID_PARSER) {
2924                        Slog.w(TAG, "No path, pathPrefix, or pathPattern for <path-permission>: "
2925                                + parser.getName() + " at " + mArchiveSourcePath + " "
2926                                + parser.getPositionDescription());
2927                        XmlUtils.skipCurrentTag(parser);
2928                        continue;
2929                    }
2930                    outError[0] = "No path, pathPrefix, or pathPattern for <path-permission>";
2931                    return false;
2932                }
2933                XmlUtils.skipCurrentTag(parser);
2934
2935            } else {
2936                if (!RIGID_PARSER) {
2937                    Slog.w(TAG, "Unknown element under <provider>: "
2938                            + parser.getName() + " at " + mArchiveSourcePath + " "
2939                            + parser.getPositionDescription());
2940                    XmlUtils.skipCurrentTag(parser);
2941                    continue;
2942                } else {
2943                    outError[0] = "Bad element under <provider>: " + parser.getName();
2944                    return false;
2945                }
2946            }
2947        }
2948        return true;
2949    }
2950
2951    private Service parseService(Package owner, Resources res,
2952            XmlPullParser parser, AttributeSet attrs, int flags, String[] outError)
2953            throws XmlPullParserException, IOException {
2954        TypedArray sa = res.obtainAttributes(attrs,
2955                com.android.internal.R.styleable.AndroidManifestService);
2956
2957        if (mParseServiceArgs == null) {
2958            mParseServiceArgs = new ParseComponentArgs(owner, outError,
2959                    com.android.internal.R.styleable.AndroidManifestService_name,
2960                    com.android.internal.R.styleable.AndroidManifestService_label,
2961                    com.android.internal.R.styleable.AndroidManifestService_icon,
2962                    com.android.internal.R.styleable.AndroidManifestService_logo,
2963                    mSeparateProcesses,
2964                    com.android.internal.R.styleable.AndroidManifestService_process,
2965                    com.android.internal.R.styleable.AndroidManifestService_description,
2966                    com.android.internal.R.styleable.AndroidManifestService_enabled);
2967            mParseServiceArgs.tag = "<service>";
2968        }
2969
2970        mParseServiceArgs.sa = sa;
2971        mParseServiceArgs.flags = flags;
2972
2973        Service s = new Service(mParseServiceArgs, new ServiceInfo());
2974        if (outError[0] != null) {
2975            sa.recycle();
2976            return null;
2977        }
2978
2979        boolean setExported = sa.hasValue(
2980                com.android.internal.R.styleable.AndroidManifestService_exported);
2981        if (setExported) {
2982            s.info.exported = sa.getBoolean(
2983                    com.android.internal.R.styleable.AndroidManifestService_exported, false);
2984        }
2985
2986        String str = sa.getNonConfigurationString(
2987                com.android.internal.R.styleable.AndroidManifestService_permission, 0);
2988        if (str == null) {
2989            s.info.permission = owner.applicationInfo.permission;
2990        } else {
2991            s.info.permission = str.length() > 0 ? str.toString().intern() : null;
2992        }
2993
2994        s.info.flags = 0;
2995        if (sa.getBoolean(
2996                com.android.internal.R.styleable.AndroidManifestService_stopWithTask,
2997                false)) {
2998            s.info.flags |= ServiceInfo.FLAG_STOP_WITH_TASK;
2999        }
3000        if (sa.getBoolean(
3001                com.android.internal.R.styleable.AndroidManifestService_isolatedProcess,
3002                false)) {
3003            s.info.flags |= ServiceInfo.FLAG_ISOLATED_PROCESS;
3004        }
3005        if (sa.getBoolean(
3006                com.android.internal.R.styleable.AndroidManifestService_singleUser,
3007                false)) {
3008            s.info.flags |= ServiceInfo.FLAG_SINGLE_USER;
3009            if (s.info.exported) {
3010                Slog.w(TAG, "Service exported request ignored due to singleUser: "
3011                        + s.className + " at " + mArchiveSourcePath + " "
3012                        + parser.getPositionDescription());
3013                s.info.exported = false;
3014            }
3015            setExported = true;
3016        }
3017
3018        sa.recycle();
3019
3020        if ((owner.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3021            // A heavy-weight application can not have services in its main process
3022            // We can do direct compare because we intern all strings.
3023            if (s.info.processName == owner.packageName) {
3024                outError[0] = "Heavy-weight applications can not have services in main process";
3025                return null;
3026            }
3027        }
3028
3029        int outerDepth = parser.getDepth();
3030        int type;
3031        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3032               && (type != XmlPullParser.END_TAG
3033                       || parser.getDepth() > outerDepth)) {
3034            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3035                continue;
3036            }
3037
3038            if (parser.getName().equals("intent-filter")) {
3039                ServiceIntentInfo intent = new ServiceIntentInfo(s);
3040                if (!parseIntent(res, parser, attrs, flags, intent, outError, false)) {
3041                    return null;
3042                }
3043
3044                s.intents.add(intent);
3045            } else if (parser.getName().equals("meta-data")) {
3046                if ((s.metaData=parseMetaData(res, parser, attrs, s.metaData,
3047                        outError)) == null) {
3048                    return null;
3049                }
3050            } else {
3051                if (!RIGID_PARSER) {
3052                    Slog.w(TAG, "Unknown element under <service>: "
3053                            + parser.getName() + " at " + mArchiveSourcePath + " "
3054                            + parser.getPositionDescription());
3055                    XmlUtils.skipCurrentTag(parser);
3056                    continue;
3057                } else {
3058                    outError[0] = "Bad element under <service>: " + parser.getName();
3059                    return null;
3060                }
3061            }
3062        }
3063
3064        if (!setExported) {
3065            s.info.exported = s.intents.size() > 0;
3066        }
3067
3068        return s;
3069    }
3070
3071    private boolean parseAllMetaData(Resources res,
3072            XmlPullParser parser, AttributeSet attrs, String tag,
3073            Component outInfo, String[] outError)
3074            throws XmlPullParserException, IOException {
3075        int outerDepth = parser.getDepth();
3076        int type;
3077        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3078               && (type != XmlPullParser.END_TAG
3079                       || parser.getDepth() > outerDepth)) {
3080            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3081                continue;
3082            }
3083
3084            if (parser.getName().equals("meta-data")) {
3085                if ((outInfo.metaData=parseMetaData(res, parser, attrs,
3086                        outInfo.metaData, outError)) == null) {
3087                    return false;
3088                }
3089            } else {
3090                if (!RIGID_PARSER) {
3091                    Slog.w(TAG, "Unknown element under " + tag + ": "
3092                            + parser.getName() + " at " + mArchiveSourcePath + " "
3093                            + parser.getPositionDescription());
3094                    XmlUtils.skipCurrentTag(parser);
3095                    continue;
3096                } else {
3097                    outError[0] = "Bad element under " + tag + ": " + parser.getName();
3098                    return false;
3099                }
3100            }
3101        }
3102        return true;
3103    }
3104
3105    private Bundle parseMetaData(Resources res,
3106            XmlPullParser parser, AttributeSet attrs,
3107            Bundle data, String[] outError)
3108            throws XmlPullParserException, IOException {
3109
3110        TypedArray sa = res.obtainAttributes(attrs,
3111                com.android.internal.R.styleable.AndroidManifestMetaData);
3112
3113        if (data == null) {
3114            data = new Bundle();
3115        }
3116
3117        String name = sa.getNonConfigurationString(
3118                com.android.internal.R.styleable.AndroidManifestMetaData_name, 0);
3119        if (name == null) {
3120            outError[0] = "<meta-data> requires an android:name attribute";
3121            sa.recycle();
3122            return null;
3123        }
3124
3125        name = name.intern();
3126
3127        TypedValue v = sa.peekValue(
3128                com.android.internal.R.styleable.AndroidManifestMetaData_resource);
3129        if (v != null && v.resourceId != 0) {
3130            //Slog.i(TAG, "Meta data ref " + name + ": " + v);
3131            data.putInt(name, v.resourceId);
3132        } else {
3133            v = sa.peekValue(
3134                    com.android.internal.R.styleable.AndroidManifestMetaData_value);
3135            //Slog.i(TAG, "Meta data " + name + ": " + v);
3136            if (v != null) {
3137                if (v.type == TypedValue.TYPE_STRING) {
3138                    CharSequence cs = v.coerceToString();
3139                    data.putString(name, cs != null ? cs.toString().intern() : null);
3140                } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
3141                    data.putBoolean(name, v.data != 0);
3142                } else if (v.type >= TypedValue.TYPE_FIRST_INT
3143                        && v.type <= TypedValue.TYPE_LAST_INT) {
3144                    data.putInt(name, v.data);
3145                } else if (v.type == TypedValue.TYPE_FLOAT) {
3146                    data.putFloat(name, v.getFloat());
3147                } else {
3148                    if (!RIGID_PARSER) {
3149                        Slog.w(TAG, "<meta-data> only supports string, integer, float, color, boolean, and resource reference types: "
3150                                + parser.getName() + " at " + mArchiveSourcePath + " "
3151                                + parser.getPositionDescription());
3152                    } else {
3153                        outError[0] = "<meta-data> only supports string, integer, float, color, boolean, and resource reference types";
3154                        data = null;
3155                    }
3156                }
3157            } else {
3158                outError[0] = "<meta-data> requires an android:value or android:resource attribute";
3159                data = null;
3160            }
3161        }
3162
3163        sa.recycle();
3164
3165        XmlUtils.skipCurrentTag(parser);
3166
3167        return data;
3168    }
3169
3170    private static VerifierInfo parseVerifier(Resources res, XmlPullParser parser,
3171            AttributeSet attrs, int flags, String[] outError) throws XmlPullParserException,
3172            IOException {
3173        final TypedArray sa = res.obtainAttributes(attrs,
3174                com.android.internal.R.styleable.AndroidManifestPackageVerifier);
3175
3176        final String packageName = sa.getNonResourceString(
3177                com.android.internal.R.styleable.AndroidManifestPackageVerifier_name);
3178
3179        final String encodedPublicKey = sa.getNonResourceString(
3180                com.android.internal.R.styleable.AndroidManifestPackageVerifier_publicKey);
3181
3182        sa.recycle();
3183
3184        if (packageName == null || packageName.length() == 0) {
3185            Slog.i(TAG, "verifier package name was null; skipping");
3186            return null;
3187        } else if (encodedPublicKey == null) {
3188            Slog.i(TAG, "verifier " + packageName + " public key was null; skipping");
3189        }
3190
3191        PublicKey publicKey = parsePublicKey(encodedPublicKey);
3192        if (publicKey != null) {
3193            return new VerifierInfo(packageName, publicKey);
3194        }
3195
3196        return null;
3197    }
3198
3199    public static final PublicKey parsePublicKey(String encodedPublicKey) {
3200        EncodedKeySpec keySpec;
3201        try {
3202            final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT);
3203            keySpec = new X509EncodedKeySpec(encoded);
3204        } catch (IllegalArgumentException e) {
3205            Slog.i(TAG, "Could not parse verifier public key; invalid Base64");
3206            return null;
3207        }
3208
3209        /* First try the key as an RSA key. */
3210        try {
3211            final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
3212            return keyFactory.generatePublic(keySpec);
3213        } catch (NoSuchAlgorithmException e) {
3214            Log.wtf(TAG, "Could not parse public key because RSA isn't included in build");
3215            return null;
3216        } catch (InvalidKeySpecException e) {
3217            // Not a RSA public key.
3218        }
3219
3220        /* Now try it as a DSA key. */
3221        try {
3222            final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
3223            return keyFactory.generatePublic(keySpec);
3224        } catch (NoSuchAlgorithmException e) {
3225            Log.wtf(TAG, "Could not parse public key because DSA isn't included in build");
3226            return null;
3227        } catch (InvalidKeySpecException e) {
3228            // Not a DSA public key.
3229        }
3230
3231        return null;
3232    }
3233
3234    private static final String ANDROID_RESOURCES
3235            = "http://schemas.android.com/apk/res/android";
3236
3237    private boolean parseIntent(Resources res,
3238            XmlPullParser parser, AttributeSet attrs, int flags,
3239            IntentInfo outInfo, String[] outError, boolean isActivity)
3240            throws XmlPullParserException, IOException {
3241
3242        TypedArray sa = res.obtainAttributes(attrs,
3243                com.android.internal.R.styleable.AndroidManifestIntentFilter);
3244
3245        int priority = sa.getInt(
3246                com.android.internal.R.styleable.AndroidManifestIntentFilter_priority, 0);
3247        outInfo.setPriority(priority);
3248
3249        TypedValue v = sa.peekValue(
3250                com.android.internal.R.styleable.AndroidManifestIntentFilter_label);
3251        if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
3252            outInfo.nonLocalizedLabel = v.coerceToString();
3253        }
3254
3255        outInfo.icon = sa.getResourceId(
3256                com.android.internal.R.styleable.AndroidManifestIntentFilter_icon, 0);
3257
3258        outInfo.logo = sa.getResourceId(
3259                com.android.internal.R.styleable.AndroidManifestIntentFilter_logo, 0);
3260
3261        sa.recycle();
3262
3263        int outerDepth = parser.getDepth();
3264        int type;
3265        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3266                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3267            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3268                continue;
3269            }
3270
3271            String nodeName = parser.getName();
3272            if (nodeName.equals("action")) {
3273                String value = attrs.getAttributeValue(
3274                        ANDROID_RESOURCES, "name");
3275                if (value == null || value == "") {
3276                    outError[0] = "No value supplied for <android:name>";
3277                    return false;
3278                }
3279                XmlUtils.skipCurrentTag(parser);
3280
3281                outInfo.addAction(value);
3282            } else if (nodeName.equals("category")) {
3283                String value = attrs.getAttributeValue(
3284                        ANDROID_RESOURCES, "name");
3285                if (value == null || value == "") {
3286                    outError[0] = "No value supplied for <android:name>";
3287                    return false;
3288                }
3289                XmlUtils.skipCurrentTag(parser);
3290
3291                outInfo.addCategory(value);
3292
3293            } else if (nodeName.equals("data")) {
3294                sa = res.obtainAttributes(attrs,
3295                        com.android.internal.R.styleable.AndroidManifestData);
3296
3297                String str = sa.getNonConfigurationString(
3298                        com.android.internal.R.styleable.AndroidManifestData_mimeType, 0);
3299                if (str != null) {
3300                    try {
3301                        outInfo.addDataType(str);
3302                    } catch (IntentFilter.MalformedMimeTypeException e) {
3303                        outError[0] = e.toString();
3304                        sa.recycle();
3305                        return false;
3306                    }
3307                }
3308
3309                str = sa.getNonConfigurationString(
3310                        com.android.internal.R.styleable.AndroidManifestData_scheme, 0);
3311                if (str != null) {
3312                    outInfo.addDataScheme(str);
3313                }
3314
3315                str = sa.getNonConfigurationString(
3316                        com.android.internal.R.styleable.AndroidManifestData_ssp, 0);
3317                if (str != null) {
3318                    outInfo.addDataSchemeSpecificPart(str, PatternMatcher.PATTERN_LITERAL);
3319                }
3320
3321                str = sa.getNonConfigurationString(
3322                        com.android.internal.R.styleable.AndroidManifestData_sspPrefix, 0);
3323                if (str != null) {
3324                    outInfo.addDataSchemeSpecificPart(str, PatternMatcher.PATTERN_PREFIX);
3325                }
3326
3327                str = sa.getNonConfigurationString(
3328                        com.android.internal.R.styleable.AndroidManifestData_sspPattern, 0);
3329                if (str != null) {
3330                    outInfo.addDataSchemeSpecificPart(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
3331                }
3332
3333                String host = sa.getNonConfigurationString(
3334                        com.android.internal.R.styleable.AndroidManifestData_host, 0);
3335                String port = sa.getNonConfigurationString(
3336                        com.android.internal.R.styleable.AndroidManifestData_port, 0);
3337                if (host != null) {
3338                    outInfo.addDataAuthority(host, port);
3339                }
3340
3341                str = sa.getNonConfigurationString(
3342                        com.android.internal.R.styleable.AndroidManifestData_path, 0);
3343                if (str != null) {
3344                    outInfo.addDataPath(str, PatternMatcher.PATTERN_LITERAL);
3345                }
3346
3347                str = sa.getNonConfigurationString(
3348                        com.android.internal.R.styleable.AndroidManifestData_pathPrefix, 0);
3349                if (str != null) {
3350                    outInfo.addDataPath(str, PatternMatcher.PATTERN_PREFIX);
3351                }
3352
3353                str = sa.getNonConfigurationString(
3354                        com.android.internal.R.styleable.AndroidManifestData_pathPattern, 0);
3355                if (str != null) {
3356                    outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
3357                }
3358
3359                sa.recycle();
3360                XmlUtils.skipCurrentTag(parser);
3361            } else if (!RIGID_PARSER) {
3362                Slog.w(TAG, "Unknown element under <intent-filter>: "
3363                        + parser.getName() + " at " + mArchiveSourcePath + " "
3364                        + parser.getPositionDescription());
3365                XmlUtils.skipCurrentTag(parser);
3366            } else {
3367                outError[0] = "Bad element under <intent-filter>: " + parser.getName();
3368                return false;
3369            }
3370        }
3371
3372        outInfo.hasDefault = outInfo.hasCategory(Intent.CATEGORY_DEFAULT);
3373
3374        if (DEBUG_PARSER) {
3375            final StringBuilder cats = new StringBuilder("Intent d=");
3376            cats.append(outInfo.hasDefault);
3377            cats.append(", cat=");
3378
3379            final Iterator<String> it = outInfo.categoriesIterator();
3380            if (it != null) {
3381                while (it.hasNext()) {
3382                    cats.append(' ');
3383                    cats.append(it.next());
3384                }
3385            }
3386            Slog.d(TAG, cats.toString());
3387        }
3388
3389        return true;
3390    }
3391
3392    public final static class Package {
3393
3394        public String packageName;
3395
3396        // For now we only support one application per package.
3397        public final ApplicationInfo applicationInfo = new ApplicationInfo();
3398
3399        public final ArrayList<Permission> permissions = new ArrayList<Permission>(0);
3400        public final ArrayList<PermissionGroup> permissionGroups = new ArrayList<PermissionGroup>(0);
3401        public final ArrayList<Activity> activities = new ArrayList<Activity>(0);
3402        public final ArrayList<Activity> receivers = new ArrayList<Activity>(0);
3403        public final ArrayList<Provider> providers = new ArrayList<Provider>(0);
3404        public final ArrayList<Service> services = new ArrayList<Service>(0);
3405        public final ArrayList<Instrumentation> instrumentation = new ArrayList<Instrumentation>(0);
3406
3407        public final ArrayList<String> requestedPermissions = new ArrayList<String>();
3408        public final ArrayList<Boolean> requestedPermissionsRequired = new ArrayList<Boolean>();
3409
3410        public ArrayList<String> protectedBroadcasts;
3411
3412        public ArrayList<String> libraryNames = null;
3413        public ArrayList<String> usesLibraries = null;
3414        public ArrayList<String> usesOptionalLibraries = null;
3415        public String[] usesLibraryFiles = null;
3416
3417        public ArrayList<String> mOriginalPackages = null;
3418        public String mRealPackage = null;
3419        public ArrayList<String> mAdoptPermissions = null;
3420
3421        // We store the application meta-data independently to avoid multiple unwanted references
3422        public Bundle mAppMetaData = null;
3423
3424        // If this is a 3rd party app, this is the path of the zip file.
3425        public String mPath;
3426
3427        // The version code declared for this package.
3428        public int mVersionCode;
3429
3430        // The version name declared for this package.
3431        public String mVersionName;
3432
3433        // The shared user id that this package wants to use.
3434        public String mSharedUserId;
3435
3436        // The shared user label that this package wants to use.
3437        public int mSharedUserLabel;
3438
3439        // Signatures that were read from the package.
3440        public Signature mSignatures[];
3441
3442        // For use by package manager service for quick lookup of
3443        // preferred up order.
3444        public int mPreferredOrder = 0;
3445
3446        // For use by the package manager to keep track of the path to the
3447        // file an app came from.
3448        public String mScanPath;
3449
3450        // For use by package manager to keep track of where it has done dexopt.
3451        public boolean mDidDexOpt;
3452
3453        // // User set enabled state.
3454        // public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
3455        //
3456        // // Whether the package has been stopped.
3457        // public boolean mSetStopped = false;
3458
3459        // Additional data supplied by callers.
3460        public Object mExtras;
3461
3462        // Whether an operation is currently pending on this package
3463        public boolean mOperationPending;
3464
3465        /*
3466         *  Applications hardware preferences
3467         */
3468        public final ArrayList<ConfigurationInfo> configPreferences =
3469                new ArrayList<ConfigurationInfo>();
3470
3471        /*
3472         *  Applications requested features
3473         */
3474        public ArrayList<FeatureInfo> reqFeatures = null;
3475
3476        public int installLocation;
3477
3478        /* An app that's required for all users and cannot be uninstalled for a user */
3479        public boolean mRequiredForAllUsers;
3480
3481        /* The restricted account authenticator type that is used by this application */
3482        public String mRestrictedAccountType;
3483
3484        /* The required account type without which this application will not function */
3485        public String mRequiredAccountType;
3486
3487        /**
3488         * Digest suitable for comparing whether this package's manifest is the
3489         * same as another.
3490         */
3491        public ManifestDigest manifestDigest;
3492
3493        /**
3494         * Data used to feed the KeySetManager
3495         */
3496        public Set<PublicKey> mSigningKeys;
3497        public Map<String, Set<PublicKey>> mKeySetMapping;
3498
3499        public Package(String _name) {
3500            packageName = _name;
3501            applicationInfo.packageName = _name;
3502            applicationInfo.uid = -1;
3503        }
3504
3505        public void setPackageName(String newName) {
3506            packageName = newName;
3507            applicationInfo.packageName = newName;
3508            for (int i=permissions.size()-1; i>=0; i--) {
3509                permissions.get(i).setPackageName(newName);
3510            }
3511            for (int i=permissionGroups.size()-1; i>=0; i--) {
3512                permissionGroups.get(i).setPackageName(newName);
3513            }
3514            for (int i=activities.size()-1; i>=0; i--) {
3515                activities.get(i).setPackageName(newName);
3516            }
3517            for (int i=receivers.size()-1; i>=0; i--) {
3518                receivers.get(i).setPackageName(newName);
3519            }
3520            for (int i=providers.size()-1; i>=0; i--) {
3521                providers.get(i).setPackageName(newName);
3522            }
3523            for (int i=services.size()-1; i>=0; i--) {
3524                services.get(i).setPackageName(newName);
3525            }
3526            for (int i=instrumentation.size()-1; i>=0; i--) {
3527                instrumentation.get(i).setPackageName(newName);
3528            }
3529        }
3530
3531        public boolean hasComponentClassName(String name) {
3532            for (int i=activities.size()-1; i>=0; i--) {
3533                if (name.equals(activities.get(i).className)) {
3534                    return true;
3535                }
3536            }
3537            for (int i=receivers.size()-1; i>=0; i--) {
3538                if (name.equals(receivers.get(i).className)) {
3539                    return true;
3540                }
3541            }
3542            for (int i=providers.size()-1; i>=0; i--) {
3543                if (name.equals(providers.get(i).className)) {
3544                    return true;
3545                }
3546            }
3547            for (int i=services.size()-1; i>=0; i--) {
3548                if (name.equals(services.get(i).className)) {
3549                    return true;
3550                }
3551            }
3552            for (int i=instrumentation.size()-1; i>=0; i--) {
3553                if (name.equals(instrumentation.get(i).className)) {
3554                    return true;
3555                }
3556            }
3557            return false;
3558        }
3559
3560        public String toString() {
3561            return "Package{"
3562                + Integer.toHexString(System.identityHashCode(this))
3563                + " " + packageName + "}";
3564        }
3565    }
3566
3567    public static class Component<II extends IntentInfo> {
3568        public final Package owner;
3569        public final ArrayList<II> intents;
3570        public final String className;
3571        public Bundle metaData;
3572
3573        ComponentName componentName;
3574        String componentShortName;
3575
3576        public Component(Package _owner) {
3577            owner = _owner;
3578            intents = null;
3579            className = null;
3580        }
3581
3582        public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
3583            owner = args.owner;
3584            intents = new ArrayList<II>(0);
3585            String name = args.sa.getNonConfigurationString(args.nameRes, 0);
3586            if (name == null) {
3587                className = null;
3588                args.outError[0] = args.tag + " does not specify android:name";
3589                return;
3590            }
3591
3592            outInfo.name
3593                = buildClassName(owner.applicationInfo.packageName, name, args.outError);
3594            if (outInfo.name == null) {
3595                className = null;
3596                args.outError[0] = args.tag + " does not have valid android:name";
3597                return;
3598            }
3599
3600            className = outInfo.name;
3601
3602            int iconVal = args.sa.getResourceId(args.iconRes, 0);
3603            if (iconVal != 0) {
3604                outInfo.icon = iconVal;
3605                outInfo.nonLocalizedLabel = null;
3606            }
3607
3608            int logoVal = args.sa.getResourceId(args.logoRes, 0);
3609            if (logoVal != 0) {
3610                outInfo.logo = logoVal;
3611            }
3612
3613            TypedValue v = args.sa.peekValue(args.labelRes);
3614            if (v != null && (outInfo.labelRes=v.resourceId) == 0) {
3615                outInfo.nonLocalizedLabel = v.coerceToString();
3616            }
3617
3618            outInfo.packageName = owner.packageName;
3619        }
3620
3621        public Component(final ParseComponentArgs args, final ComponentInfo outInfo) {
3622            this(args, (PackageItemInfo)outInfo);
3623            if (args.outError[0] != null) {
3624                return;
3625            }
3626
3627            if (args.processRes != 0) {
3628                CharSequence pname;
3629                if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
3630                    pname = args.sa.getNonConfigurationString(args.processRes, 0);
3631                } else {
3632                    // Some older apps have been seen to use a resource reference
3633                    // here that on older builds was ignored (with a warning).  We
3634                    // need to continue to do this for them so they don't break.
3635                    pname = args.sa.getNonResourceString(args.processRes);
3636                }
3637                outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
3638                        owner.applicationInfo.processName, pname,
3639                        args.flags, args.sepProcesses, args.outError);
3640            }
3641
3642            if (args.descriptionRes != 0) {
3643                outInfo.descriptionRes = args.sa.getResourceId(args.descriptionRes, 0);
3644            }
3645
3646            outInfo.enabled = args.sa.getBoolean(args.enabledRes, true);
3647        }
3648
3649        public Component(Component<II> clone) {
3650            owner = clone.owner;
3651            intents = clone.intents;
3652            className = clone.className;
3653            componentName = clone.componentName;
3654            componentShortName = clone.componentShortName;
3655        }
3656
3657        public ComponentName getComponentName() {
3658            if (componentName != null) {
3659                return componentName;
3660            }
3661            if (className != null) {
3662                componentName = new ComponentName(owner.applicationInfo.packageName,
3663                        className);
3664            }
3665            return componentName;
3666        }
3667
3668        public String getComponentShortName() {
3669            if (componentShortName != null) {
3670                return componentShortName;
3671            }
3672            ComponentName component = getComponentName();
3673            if (component != null) {
3674                componentShortName = component.flattenToShortString();
3675            }
3676            return componentShortName;
3677        }
3678
3679        public void setPackageName(String packageName) {
3680            componentName = null;
3681            componentShortName = null;
3682        }
3683    }
3684
3685    public final static class Permission extends Component<IntentInfo> {
3686        public final PermissionInfo info;
3687        public boolean tree;
3688        public PermissionGroup group;
3689
3690        public Permission(Package _owner) {
3691            super(_owner);
3692            info = new PermissionInfo();
3693        }
3694
3695        public Permission(Package _owner, PermissionInfo _info) {
3696            super(_owner);
3697            info = _info;
3698        }
3699
3700        public void setPackageName(String packageName) {
3701            super.setPackageName(packageName);
3702            info.packageName = packageName;
3703        }
3704
3705        public String toString() {
3706            return "Permission{"
3707                + Integer.toHexString(System.identityHashCode(this))
3708                + " " + info.name + "}";
3709        }
3710    }
3711
3712    public final static class PermissionGroup extends Component<IntentInfo> {
3713        public final PermissionGroupInfo info;
3714
3715        public PermissionGroup(Package _owner) {
3716            super(_owner);
3717            info = new PermissionGroupInfo();
3718        }
3719
3720        public PermissionGroup(Package _owner, PermissionGroupInfo _info) {
3721            super(_owner);
3722            info = _info;
3723        }
3724
3725        public void setPackageName(String packageName) {
3726            super.setPackageName(packageName);
3727            info.packageName = packageName;
3728        }
3729
3730        public String toString() {
3731            return "PermissionGroup{"
3732                + Integer.toHexString(System.identityHashCode(this))
3733                + " " + info.name + "}";
3734        }
3735    }
3736
3737    private static boolean copyNeeded(int flags, Package p,
3738            PackageUserState state, Bundle metaData, int userId) {
3739        if (userId != 0) {
3740            // We always need to copy for other users, since we need
3741            // to fix up the uid.
3742            return true;
3743        }
3744        if (state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
3745            boolean enabled = state.enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
3746            if (p.applicationInfo.enabled != enabled) {
3747                return true;
3748            }
3749        }
3750        if (!state.installed || state.blocked) {
3751            return true;
3752        }
3753        if (state.stopped) {
3754            return true;
3755        }
3756        if ((flags & PackageManager.GET_META_DATA) != 0
3757                && (metaData != null || p.mAppMetaData != null)) {
3758            return true;
3759        }
3760        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0
3761                && p.usesLibraryFiles != null) {
3762            return true;
3763        }
3764        return false;
3765    }
3766
3767    public static ApplicationInfo generateApplicationInfo(Package p, int flags,
3768            PackageUserState state) {
3769        return generateApplicationInfo(p, flags, state, UserHandle.getCallingUserId());
3770    }
3771
3772    private static void updateApplicationInfo(ApplicationInfo ai, int flags,
3773            PackageUserState state) {
3774        // CompatibilityMode is global state.
3775        if (!sCompatibilityModeEnabled) {
3776            ai.disableCompatibilityMode();
3777        }
3778        if (state.installed) {
3779            ai.flags |= ApplicationInfo.FLAG_INSTALLED;
3780        } else {
3781            ai.flags &= ~ApplicationInfo.FLAG_INSTALLED;
3782        }
3783        if (state.blocked) {
3784            ai.flags |= ApplicationInfo.FLAG_BLOCKED;
3785        } else {
3786            ai.flags &= ~ApplicationInfo.FLAG_BLOCKED;
3787        }
3788        if (state.enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
3789            ai.enabled = true;
3790        } else if (state.enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
3791            ai.enabled = (flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) != 0;
3792        } else if (state.enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
3793                || state.enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3794            ai.enabled = false;
3795        }
3796        ai.enabledSetting = state.enabled;
3797    }
3798
3799    public static ApplicationInfo generateApplicationInfo(Package p, int flags,
3800            PackageUserState state, int userId) {
3801        if (p == null) return null;
3802        if (!checkUseInstalledOrBlocked(flags, state)) {
3803            return null;
3804        }
3805        if (!copyNeeded(flags, p, state, null, userId)
3806                && ((flags&PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) == 0
3807                        || state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
3808            // In this case it is safe to directly modify the internal ApplicationInfo state:
3809            // - CompatibilityMode is global state, so will be the same for every call.
3810            // - We only come in to here if the app should reported as installed; this is the
3811            // default state, and we will do a copy otherwise.
3812            // - The enable state will always be reported the same for the application across
3813            // calls; the only exception is for the UNTIL_USED mode, and in that case we will
3814            // be doing a copy.
3815            updateApplicationInfo(p.applicationInfo, flags, state);
3816            return p.applicationInfo;
3817        }
3818
3819        // Make shallow copy so we can store the metadata/libraries safely
3820        ApplicationInfo ai = new ApplicationInfo(p.applicationInfo);
3821        if (userId != 0) {
3822            ai.uid = UserHandle.getUid(userId, ai.uid);
3823            ai.dataDir = PackageManager.getDataDirForUser(userId, ai.packageName);
3824        }
3825        if ((flags & PackageManager.GET_META_DATA) != 0) {
3826            ai.metaData = p.mAppMetaData;
3827        }
3828        if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0) {
3829            ai.sharedLibraryFiles = p.usesLibraryFiles;
3830        }
3831        if (state.stopped) {
3832            ai.flags |= ApplicationInfo.FLAG_STOPPED;
3833        } else {
3834            ai.flags &= ~ApplicationInfo.FLAG_STOPPED;
3835        }
3836        updateApplicationInfo(ai, flags, state);
3837        return ai;
3838    }
3839
3840    public static final PermissionInfo generatePermissionInfo(
3841            Permission p, int flags) {
3842        if (p == null) return null;
3843        if ((flags&PackageManager.GET_META_DATA) == 0) {
3844            return p.info;
3845        }
3846        PermissionInfo pi = new PermissionInfo(p.info);
3847        pi.metaData = p.metaData;
3848        return pi;
3849    }
3850
3851    public static final PermissionGroupInfo generatePermissionGroupInfo(
3852            PermissionGroup pg, int flags) {
3853        if (pg == null) return null;
3854        if ((flags&PackageManager.GET_META_DATA) == 0) {
3855            return pg.info;
3856        }
3857        PermissionGroupInfo pgi = new PermissionGroupInfo(pg.info);
3858        pgi.metaData = pg.metaData;
3859        return pgi;
3860    }
3861
3862    public final static class Activity extends Component<ActivityIntentInfo> {
3863        public final ActivityInfo info;
3864
3865        public Activity(final ParseComponentArgs args, final ActivityInfo _info) {
3866            super(args, _info);
3867            info = _info;
3868            info.applicationInfo = args.owner.applicationInfo;
3869        }
3870
3871        public void setPackageName(String packageName) {
3872            super.setPackageName(packageName);
3873            info.packageName = packageName;
3874        }
3875
3876        public String toString() {
3877            return "Activity{"
3878                + Integer.toHexString(System.identityHashCode(this))
3879                + " " + getComponentShortName() + "}";
3880        }
3881    }
3882
3883    public static final ActivityInfo generateActivityInfo(Activity a, int flags,
3884            PackageUserState state, int userId) {
3885        if (a == null) return null;
3886        if (!checkUseInstalledOrBlocked(flags, state)) {
3887            return null;
3888        }
3889        if (!copyNeeded(flags, a.owner, state, a.metaData, userId)) {
3890            return a.info;
3891        }
3892        // Make shallow copies so we can store the metadata safely
3893        ActivityInfo ai = new ActivityInfo(a.info);
3894        ai.metaData = a.metaData;
3895        ai.applicationInfo = generateApplicationInfo(a.owner, flags, state, userId);
3896        return ai;
3897    }
3898
3899    public final static class Service extends Component<ServiceIntentInfo> {
3900        public final ServiceInfo info;
3901
3902        public Service(final ParseComponentArgs args, final ServiceInfo _info) {
3903            super(args, _info);
3904            info = _info;
3905            info.applicationInfo = args.owner.applicationInfo;
3906        }
3907
3908        public void setPackageName(String packageName) {
3909            super.setPackageName(packageName);
3910            info.packageName = packageName;
3911        }
3912
3913        public String toString() {
3914            return "Service{"
3915                + Integer.toHexString(System.identityHashCode(this))
3916                + " " + getComponentShortName() + "}";
3917        }
3918    }
3919
3920    public static final ServiceInfo generateServiceInfo(Service s, int flags,
3921            PackageUserState state, int userId) {
3922        if (s == null) return null;
3923        if (!checkUseInstalledOrBlocked(flags, state)) {
3924            return null;
3925        }
3926        if (!copyNeeded(flags, s.owner, state, s.metaData, userId)) {
3927            return s.info;
3928        }
3929        // Make shallow copies so we can store the metadata safely
3930        ServiceInfo si = new ServiceInfo(s.info);
3931        si.metaData = s.metaData;
3932        si.applicationInfo = generateApplicationInfo(s.owner, flags, state, userId);
3933        return si;
3934    }
3935
3936    public final static class Provider extends Component {
3937        public final ProviderInfo info;
3938        public boolean syncable;
3939
3940        public Provider(final ParseComponentArgs args, final ProviderInfo _info) {
3941            super(args, _info);
3942            info = _info;
3943            info.applicationInfo = args.owner.applicationInfo;
3944            syncable = false;
3945        }
3946
3947        public Provider(Provider existingProvider) {
3948            super(existingProvider);
3949            this.info = existingProvider.info;
3950            this.syncable = existingProvider.syncable;
3951        }
3952
3953        public void setPackageName(String packageName) {
3954            super.setPackageName(packageName);
3955            info.packageName = packageName;
3956        }
3957
3958        public String toString() {
3959            return "Provider{"
3960                + Integer.toHexString(System.identityHashCode(this))
3961                + " " + info.name + "}";
3962        }
3963    }
3964
3965    public static final ProviderInfo generateProviderInfo(Provider p, int flags,
3966            PackageUserState state, int userId) {
3967        if (p == null) return null;
3968        if (!checkUseInstalledOrBlocked(flags, state)) {
3969            return null;
3970        }
3971        if (!copyNeeded(flags, p.owner, state, p.metaData, userId)
3972                && ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) != 0
3973                        || p.info.uriPermissionPatterns == null)) {
3974            return p.info;
3975        }
3976        // Make shallow copies so we can store the metadata safely
3977        ProviderInfo pi = new ProviderInfo(p.info);
3978        pi.metaData = p.metaData;
3979        if ((flags & PackageManager.GET_URI_PERMISSION_PATTERNS) == 0) {
3980            pi.uriPermissionPatterns = null;
3981        }
3982        pi.applicationInfo = generateApplicationInfo(p.owner, flags, state, userId);
3983        return pi;
3984    }
3985
3986    public final static class Instrumentation extends Component {
3987        public final InstrumentationInfo info;
3988
3989        public Instrumentation(final ParsePackageItemArgs args, final InstrumentationInfo _info) {
3990            super(args, _info);
3991            info = _info;
3992        }
3993
3994        public void setPackageName(String packageName) {
3995            super.setPackageName(packageName);
3996            info.packageName = packageName;
3997        }
3998
3999        public String toString() {
4000            return "Instrumentation{"
4001                + Integer.toHexString(System.identityHashCode(this))
4002                + " " + getComponentShortName() + "}";
4003        }
4004    }
4005
4006    public static final InstrumentationInfo generateInstrumentationInfo(
4007            Instrumentation i, int flags) {
4008        if (i == null) return null;
4009        if ((flags&PackageManager.GET_META_DATA) == 0) {
4010            return i.info;
4011        }
4012        InstrumentationInfo ii = new InstrumentationInfo(i.info);
4013        ii.metaData = i.metaData;
4014        return ii;
4015    }
4016
4017    public static class IntentInfo extends IntentFilter {
4018        public boolean hasDefault;
4019        public int labelRes;
4020        public CharSequence nonLocalizedLabel;
4021        public int icon;
4022        public int logo;
4023    }
4024
4025    public final static class ActivityIntentInfo extends IntentInfo {
4026        public final Activity activity;
4027
4028        public ActivityIntentInfo(Activity _activity) {
4029            activity = _activity;
4030        }
4031
4032        public String toString() {
4033            return "ActivityIntentInfo{"
4034                + Integer.toHexString(System.identityHashCode(this))
4035                + " " + activity.info.name + "}";
4036        }
4037    }
4038
4039    public final static class ServiceIntentInfo extends IntentInfo {
4040        public final Service service;
4041
4042        public ServiceIntentInfo(Service _service) {
4043            service = _service;
4044        }
4045
4046        public String toString() {
4047            return "ServiceIntentInfo{"
4048                + Integer.toHexString(System.identityHashCode(this))
4049                + " " + service.info.name + "}";
4050        }
4051    }
4052
4053    /**
4054     * @hide
4055     */
4056    public static void setCompatibilityModeEnabled(boolean compatibilityModeEnabled) {
4057        sCompatibilityModeEnabled = compatibilityModeEnabled;
4058    }
4059}
4060