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