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