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