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