Command.cpp revision 56088a55ca6c9277f09040a7883117cb127e1e56
1//
2// Copyright 2006 The Android Open Source Project
3//
4// Android Asset Packaging Tool main entry point.
5//
6#include "Main.h"
7#include "Bundle.h"
8#include "ResourceTable.h"
9#include "XMLNode.h"
10
11#include <utils/Log.h>
12#include <utils/threads.h>
13#include <utils/List.h>
14#include <utils/Errors.h>
15
16#include <fcntl.h>
17#include <errno.h>
18
19using namespace android;
20
21/*
22 * Show version info.  All the cool kids do it.
23 */
24int doVersion(Bundle* bundle)
25{
26    if (bundle->getFileSpecCount() != 0)
27        printf("(ignoring extra arguments)\n");
28    printf("Android Asset Packaging Tool, v0.2\n");
29
30    return 0;
31}
32
33
34/*
35 * Open the file read only.  The call fails if the file doesn't exist.
36 *
37 * Returns NULL on failure.
38 */
39ZipFile* openReadOnly(const char* fileName)
40{
41    ZipFile* zip;
42    status_t result;
43
44    zip = new ZipFile;
45    result = zip->open(fileName, ZipFile::kOpenReadOnly);
46    if (result != NO_ERROR) {
47        if (result == NAME_NOT_FOUND)
48            fprintf(stderr, "ERROR: '%s' not found\n", fileName);
49        else if (result == PERMISSION_DENIED)
50            fprintf(stderr, "ERROR: '%s' access denied\n", fileName);
51        else
52            fprintf(stderr, "ERROR: failed opening '%s' as Zip file\n",
53                fileName);
54        delete zip;
55        return NULL;
56    }
57
58    return zip;
59}
60
61/*
62 * Open the file read-write.  The file will be created if it doesn't
63 * already exist and "okayToCreate" is set.
64 *
65 * Returns NULL on failure.
66 */
67ZipFile* openReadWrite(const char* fileName, bool okayToCreate)
68{
69    ZipFile* zip = NULL;
70    status_t result;
71    int flags;
72
73    flags = ZipFile::kOpenReadWrite;
74    if (okayToCreate)
75        flags |= ZipFile::kOpenCreate;
76
77    zip = new ZipFile;
78    result = zip->open(fileName, flags);
79    if (result != NO_ERROR) {
80        delete zip;
81        zip = NULL;
82        goto bail;
83    }
84
85bail:
86    return zip;
87}
88
89
90/*
91 * Return a short string describing the compression method.
92 */
93const char* compressionName(int method)
94{
95    if (method == ZipEntry::kCompressStored)
96        return "Stored";
97    else if (method == ZipEntry::kCompressDeflated)
98        return "Deflated";
99    else
100        return "Unknown";
101}
102
103/*
104 * Return the percent reduction in size (0% == no compression).
105 */
106int calcPercent(long uncompressedLen, long compressedLen)
107{
108    if (!uncompressedLen)
109        return 0;
110    else
111        return (int) (100.0 - (compressedLen * 100.0) / uncompressedLen + 0.5);
112}
113
114/*
115 * Handle the "list" command, which can be a simple file dump or
116 * a verbose listing.
117 *
118 * The verbose listing closely matches the output of the Info-ZIP "unzip"
119 * command.
120 */
121int doList(Bundle* bundle)
122{
123    int result = 1;
124    ZipFile* zip = NULL;
125    const ZipEntry* entry;
126    long totalUncLen, totalCompLen;
127    const char* zipFileName;
128
129    if (bundle->getFileSpecCount() != 1) {
130        fprintf(stderr, "ERROR: specify zip file name (only)\n");
131        goto bail;
132    }
133    zipFileName = bundle->getFileSpecEntry(0);
134
135    zip = openReadOnly(zipFileName);
136    if (zip == NULL)
137        goto bail;
138
139    int count, i;
140
141    if (bundle->getVerbose()) {
142        printf("Archive:  %s\n", zipFileName);
143        printf(
144            " Length   Method    Size  Ratio   Offset      Date  Time  CRC-32    Name\n");
145        printf(
146            "--------  ------  ------- -----  -------      ----  ----  ------    ----\n");
147    }
148
149    totalUncLen = totalCompLen = 0;
150
151    count = zip->getNumEntries();
152    for (i = 0; i < count; i++) {
153        entry = zip->getEntryByIndex(i);
154        if (bundle->getVerbose()) {
155            char dateBuf[32];
156            time_t when;
157
158            when = entry->getModWhen();
159            strftime(dateBuf, sizeof(dateBuf), "%m-%d-%y %H:%M",
160                localtime(&when));
161
162            printf("%8ld  %-7.7s %7ld %3d%%  %8zd  %s  %08lx  %s\n",
163                (long) entry->getUncompressedLen(),
164                compressionName(entry->getCompressionMethod()),
165                (long) entry->getCompressedLen(),
166                calcPercent(entry->getUncompressedLen(),
167                            entry->getCompressedLen()),
168                (size_t) entry->getLFHOffset(),
169                dateBuf,
170                entry->getCRC32(),
171                entry->getFileName());
172        } else {
173            printf("%s\n", entry->getFileName());
174        }
175
176        totalUncLen += entry->getUncompressedLen();
177        totalCompLen += entry->getCompressedLen();
178    }
179
180    if (bundle->getVerbose()) {
181        printf(
182        "--------          -------  ---                            -------\n");
183        printf("%8ld          %7ld  %2d%%                            %d files\n",
184            totalUncLen,
185            totalCompLen,
186            calcPercent(totalUncLen, totalCompLen),
187            zip->getNumEntries());
188    }
189
190    if (bundle->getAndroidList()) {
191        AssetManager assets;
192        if (!assets.addAssetPath(String8(zipFileName), NULL)) {
193            fprintf(stderr, "ERROR: list -a failed because assets could not be loaded\n");
194            goto bail;
195        }
196
197        const ResTable& res = assets.getResources(false);
198        if (&res == NULL) {
199            printf("\nNo resource table found.\n");
200        } else {
201#ifndef HAVE_ANDROID_OS
202            printf("\nResource table:\n");
203            res.print(false);
204#endif
205        }
206
207        Asset* manifestAsset = assets.openNonAsset("AndroidManifest.xml",
208                                                   Asset::ACCESS_BUFFER);
209        if (manifestAsset == NULL) {
210            printf("\nNo AndroidManifest.xml found.\n");
211        } else {
212            printf("\nAndroid manifest:\n");
213            ResXMLTree tree;
214            tree.setTo(manifestAsset->getBuffer(true),
215                       manifestAsset->getLength());
216            printXMLBlock(&tree);
217        }
218        delete manifestAsset;
219    }
220
221    result = 0;
222
223bail:
224    delete zip;
225    return result;
226}
227
228static ssize_t indexOfAttribute(const ResXMLTree& tree, uint32_t attrRes)
229{
230    size_t N = tree.getAttributeCount();
231    for (size_t i=0; i<N; i++) {
232        if (tree.getAttributeNameResID(i) == attrRes) {
233            return (ssize_t)i;
234        }
235    }
236    return -1;
237}
238
239String8 getAttribute(const ResXMLTree& tree, const char* ns,
240                            const char* attr, String8* outError)
241{
242    ssize_t idx = tree.indexOfAttribute(ns, attr);
243    if (idx < 0) {
244        return String8();
245    }
246    Res_value value;
247    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
248        if (value.dataType != Res_value::TYPE_STRING) {
249            if (outError != NULL) *outError = "attribute is not a string value";
250            return String8();
251        }
252    }
253    size_t len;
254    const uint16_t* str = tree.getAttributeStringValue(idx, &len);
255    return str ? String8(str, len) : String8();
256}
257
258static String8 getAttribute(const ResXMLTree& tree, uint32_t attrRes, String8* outError)
259{
260    ssize_t idx = indexOfAttribute(tree, attrRes);
261    if (idx < 0) {
262        return String8();
263    }
264    Res_value value;
265    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
266        if (value.dataType != Res_value::TYPE_STRING) {
267            if (outError != NULL) *outError = "attribute is not a string value";
268            return String8();
269        }
270    }
271    size_t len;
272    const uint16_t* str = tree.getAttributeStringValue(idx, &len);
273    return str ? String8(str, len) : String8();
274}
275
276static int32_t getIntegerAttribute(const ResXMLTree& tree, uint32_t attrRes,
277        String8* outError, int32_t defValue = -1)
278{
279    ssize_t idx = indexOfAttribute(tree, attrRes);
280    if (idx < 0) {
281        return defValue;
282    }
283    Res_value value;
284    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
285        if (value.dataType < Res_value::TYPE_FIRST_INT
286                || value.dataType > Res_value::TYPE_LAST_INT) {
287            if (outError != NULL) *outError = "attribute is not an integer value";
288            return defValue;
289        }
290    }
291    return value.data;
292}
293
294static int32_t getResolvedIntegerAttribute(const ResTable* resTable, const ResXMLTree& tree,
295        uint32_t attrRes, String8* outError, int32_t defValue = -1)
296{
297    ssize_t idx = indexOfAttribute(tree, attrRes);
298    if (idx < 0) {
299        return defValue;
300    }
301    Res_value value;
302    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
303        if (value.dataType == Res_value::TYPE_REFERENCE) {
304            resTable->resolveReference(&value, 0);
305        }
306        if (value.dataType < Res_value::TYPE_FIRST_INT
307                || value.dataType > Res_value::TYPE_LAST_INT) {
308            if (outError != NULL) *outError = "attribute is not an integer value";
309            return defValue;
310        }
311    }
312    return value.data;
313}
314
315static String8 getResolvedAttribute(const ResTable* resTable, const ResXMLTree& tree,
316        uint32_t attrRes, String8* outError)
317{
318    ssize_t idx = indexOfAttribute(tree, attrRes);
319    if (idx < 0) {
320        return String8();
321    }
322    Res_value value;
323    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
324        if (value.dataType == Res_value::TYPE_STRING) {
325            size_t len;
326            const uint16_t* str = tree.getAttributeStringValue(idx, &len);
327            return str ? String8(str, len) : String8();
328        }
329        resTable->resolveReference(&value, 0);
330        if (value.dataType != Res_value::TYPE_STRING) {
331            if (outError != NULL) *outError = "attribute is not a string value";
332            return String8();
333        }
334    }
335    size_t len;
336    const Res_value* value2 = &value;
337    const char16_t* str = const_cast<ResTable*>(resTable)->valueToString(value2, 0, NULL, &len);
338    return str ? String8(str, len) : String8();
339}
340
341// These are attribute resource constants for the platform, as found
342// in android.R.attr
343enum {
344    LABEL_ATTR = 0x01010001,
345    ICON_ATTR = 0x01010002,
346    NAME_ATTR = 0x01010003,
347    VERSION_CODE_ATTR = 0x0101021b,
348    VERSION_NAME_ATTR = 0x0101021c,
349    SCREEN_ORIENTATION_ATTR = 0x0101001e,
350    MIN_SDK_VERSION_ATTR = 0x0101020c,
351    MAX_SDK_VERSION_ATTR = 0x01010271,
352    REQ_TOUCH_SCREEN_ATTR = 0x01010227,
353    REQ_KEYBOARD_TYPE_ATTR = 0x01010228,
354    REQ_HARD_KEYBOARD_ATTR = 0x01010229,
355    REQ_NAVIGATION_ATTR = 0x0101022a,
356    REQ_FIVE_WAY_NAV_ATTR = 0x01010232,
357    TARGET_SDK_VERSION_ATTR = 0x01010270,
358    TEST_ONLY_ATTR = 0x01010272,
359    ANY_DENSITY_ATTR = 0x0101026c,
360    GL_ES_VERSION_ATTR = 0x01010281,
361    SMALL_SCREEN_ATTR = 0x01010284,
362    NORMAL_SCREEN_ATTR = 0x01010285,
363    LARGE_SCREEN_ATTR = 0x01010286,
364    XLARGE_SCREEN_ATTR = 0x010102bf,
365    REQUIRED_ATTR = 0x0101028e,
366    SCREEN_SIZE_ATTR = 0x010102ca,
367    SCREEN_DENSITY_ATTR = 0x010102cb,
368    REQUIRES_SMALLEST_WIDTH_DP_ATTR = 0x01010364,
369    COMPATIBLE_WIDTH_LIMIT_DP_ATTR = 0x01010365,
370    LARGEST_WIDTH_LIMIT_DP_ATTR = 0x01010366,
371    PUBLIC_KEY_ATTR = 0x010103a6,
372};
373
374const char *getComponentName(String8 &pkgName, String8 &componentName) {
375    ssize_t idx = componentName.find(".");
376    String8 retStr(pkgName);
377    if (idx == 0) {
378        retStr += componentName;
379    } else if (idx < 0) {
380        retStr += ".";
381        retStr += componentName;
382    } else {
383        return componentName.string();
384    }
385    return retStr.string();
386}
387
388static void printCompatibleScreens(ResXMLTree& tree) {
389    size_t len;
390    ResXMLTree::event_code_t code;
391    int depth = 0;
392    bool first = true;
393    printf("compatible-screens:");
394    while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
395        if (code == ResXMLTree::END_TAG) {
396            depth--;
397            if (depth < 0) {
398                break;
399            }
400            continue;
401        }
402        if (code != ResXMLTree::START_TAG) {
403            continue;
404        }
405        depth++;
406        String8 tag(tree.getElementName(&len));
407        if (tag == "screen") {
408            int32_t screenSize = getIntegerAttribute(tree,
409                    SCREEN_SIZE_ATTR, NULL, -1);
410            int32_t screenDensity = getIntegerAttribute(tree,
411                    SCREEN_DENSITY_ATTR, NULL, -1);
412            if (screenSize > 0 && screenDensity > 0) {
413                if (!first) {
414                    printf(",");
415                }
416                first = false;
417                printf("'%d/%d'", screenSize, screenDensity);
418            }
419        }
420    }
421    printf("\n");
422}
423
424/*
425 * Handle the "dump" command, to extract select data from an archive.
426 */
427int doDump(Bundle* bundle)
428{
429    status_t result = UNKNOWN_ERROR;
430    Asset* asset = NULL;
431
432    if (bundle->getFileSpecCount() < 1) {
433        fprintf(stderr, "ERROR: no dump option specified\n");
434        return 1;
435    }
436
437    if (bundle->getFileSpecCount() < 2) {
438        fprintf(stderr, "ERROR: no dump file specified\n");
439        return 1;
440    }
441
442    const char* option = bundle->getFileSpecEntry(0);
443    const char* filename = bundle->getFileSpecEntry(1);
444
445    AssetManager assets;
446    void* assetsCookie;
447    if (!assets.addAssetPath(String8(filename), &assetsCookie)) {
448        fprintf(stderr, "ERROR: dump failed because assets could not be loaded\n");
449        return 1;
450    }
451
452    // Make a dummy config for retrieving resources...  we need to supply
453    // non-default values for some configs so that we can retrieve resources
454    // in the app that don't have a default.  The most important of these is
455    // the API version because key resources like icons will have an implicit
456    // version if they are using newer config types like density.
457    ResTable_config config;
458    config.language[0] = 'e';
459    config.language[1] = 'n';
460    config.country[0] = 'U';
461    config.country[1] = 'S';
462    config.orientation = ResTable_config::ORIENTATION_PORT;
463    config.density = ResTable_config::DENSITY_MEDIUM;
464    config.sdkVersion = 10000; // Very high.
465    config.screenWidthDp = 320;
466    config.screenHeightDp = 480;
467    config.smallestScreenWidthDp = 320;
468    assets.setConfiguration(config);
469
470    const ResTable& res = assets.getResources(false);
471    if (&res == NULL) {
472        fprintf(stderr, "ERROR: dump failed because no resource table was found\n");
473        goto bail;
474    }
475
476    if (strcmp("resources", option) == 0) {
477#ifndef HAVE_ANDROID_OS
478        res.print(bundle->getValues());
479#endif
480    } else if (strcmp("xmltree", option) == 0) {
481        if (bundle->getFileSpecCount() < 3) {
482            fprintf(stderr, "ERROR: no dump xmltree resource file specified\n");
483            goto bail;
484        }
485
486        for (int i=2; i<bundle->getFileSpecCount(); i++) {
487            const char* resname = bundle->getFileSpecEntry(i);
488            ResXMLTree tree;
489            asset = assets.openNonAsset(resname, Asset::ACCESS_BUFFER);
490            if (asset == NULL) {
491                fprintf(stderr, "ERROR: dump failed because resource %s found\n", resname);
492                goto bail;
493            }
494
495            if (tree.setTo(asset->getBuffer(true),
496                           asset->getLength()) != NO_ERROR) {
497                fprintf(stderr, "ERROR: Resource %s is corrupt\n", resname);
498                goto bail;
499            }
500            tree.restart();
501            printXMLBlock(&tree);
502            tree.uninit();
503            delete asset;
504            asset = NULL;
505        }
506
507    } else if (strcmp("xmlstrings", option) == 0) {
508        if (bundle->getFileSpecCount() < 3) {
509            fprintf(stderr, "ERROR: no dump xmltree resource file specified\n");
510            goto bail;
511        }
512
513        for (int i=2; i<bundle->getFileSpecCount(); i++) {
514            const char* resname = bundle->getFileSpecEntry(i);
515            ResXMLTree tree;
516            asset = assets.openNonAsset(resname, Asset::ACCESS_BUFFER);
517            if (asset == NULL) {
518                fprintf(stderr, "ERROR: dump failed because resource %s found\n", resname);
519                goto bail;
520            }
521
522            if (tree.setTo(asset->getBuffer(true),
523                           asset->getLength()) != NO_ERROR) {
524                fprintf(stderr, "ERROR: Resource %s is corrupt\n", resname);
525                goto bail;
526            }
527            printStringPool(&tree.getStrings());
528            delete asset;
529            asset = NULL;
530        }
531
532    } else {
533        ResXMLTree tree;
534        asset = assets.openNonAsset("AndroidManifest.xml",
535                                            Asset::ACCESS_BUFFER);
536        if (asset == NULL) {
537            fprintf(stderr, "ERROR: dump failed because no AndroidManifest.xml found\n");
538            goto bail;
539        }
540
541        if (tree.setTo(asset->getBuffer(true),
542                       asset->getLength()) != NO_ERROR) {
543            fprintf(stderr, "ERROR: AndroidManifest.xml is corrupt\n");
544            goto bail;
545        }
546        tree.restart();
547
548        if (strcmp("permissions", option) == 0) {
549            size_t len;
550            ResXMLTree::event_code_t code;
551            int depth = 0;
552            while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
553                if (code == ResXMLTree::END_TAG) {
554                    depth--;
555                    continue;
556                }
557                if (code != ResXMLTree::START_TAG) {
558                    continue;
559                }
560                depth++;
561                String8 tag(tree.getElementName(&len));
562                //printf("Depth %d tag %s\n", depth, tag.string());
563                if (depth == 1) {
564                    if (tag != "manifest") {
565                        fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
566                        goto bail;
567                    }
568                    String8 pkg = getAttribute(tree, NULL, "package", NULL);
569                    printf("package: %s\n", pkg.string());
570                } else if (depth == 2 && tag == "permission") {
571                    String8 error;
572                    String8 name = getAttribute(tree, NAME_ATTR, &error);
573                    if (error != "") {
574                        fprintf(stderr, "ERROR: %s\n", error.string());
575                        goto bail;
576                    }
577                    printf("permission: %s\n", name.string());
578                } else if (depth == 2 && tag == "uses-permission") {
579                    String8 error;
580                    String8 name = getAttribute(tree, NAME_ATTR, &error);
581                    if (error != "") {
582                        fprintf(stderr, "ERROR: %s\n", error.string());
583                        goto bail;
584                    }
585                    printf("uses-permission: %s\n", name.string());
586                }
587            }
588        } else if (strcmp("badging", option) == 0) {
589            Vector<String8> locales;
590            res.getLocales(&locales);
591
592            Vector<ResTable_config> configs;
593            res.getConfigurations(&configs);
594            SortedVector<int> densities;
595            const size_t NC = configs.size();
596            for (size_t i=0; i<NC; i++) {
597                int dens = configs[i].density;
598                if (dens == 0) dens = 160;
599                densities.add(dens);
600            }
601
602            size_t len;
603            ResXMLTree::event_code_t code;
604            int depth = 0;
605            String8 error;
606            bool withinActivity = false;
607            bool isMainActivity = false;
608            bool isLauncherActivity = false;
609            bool isSearchable = false;
610            bool withinApplication = false;
611            bool withinReceiver = false;
612            bool withinService = false;
613            bool withinIntentFilter = false;
614            bool hasMainActivity = false;
615            bool hasOtherActivities = false;
616            bool hasOtherReceivers = false;
617            bool hasOtherServices = false;
618            bool hasWallpaperService = false;
619            bool hasImeService = false;
620            bool hasWidgetReceivers = false;
621            bool hasIntentFilter = false;
622            bool actMainActivity = false;
623            bool actWidgetReceivers = false;
624            bool actImeService = false;
625            bool actWallpaperService = false;
626
627            // This next group of variables is used to implement a group of
628            // backward-compatibility heuristics necessitated by the addition of
629            // some new uses-feature constants in 2.1 and 2.2. In most cases, the
630            // heuristic is "if an app requests a permission but doesn't explicitly
631            // request the corresponding <uses-feature>, presume it's there anyway".
632            bool specCameraFeature = false; // camera-related
633            bool specCameraAutofocusFeature = false;
634            bool reqCameraAutofocusFeature = false;
635            bool reqCameraFlashFeature = false;
636            bool hasCameraPermission = false;
637            bool specLocationFeature = false; // location-related
638            bool specNetworkLocFeature = false;
639            bool reqNetworkLocFeature = false;
640            bool specGpsFeature = false;
641            bool reqGpsFeature = false;
642            bool hasMockLocPermission = false;
643            bool hasCoarseLocPermission = false;
644            bool hasGpsPermission = false;
645            bool hasGeneralLocPermission = false;
646            bool specBluetoothFeature = false; // Bluetooth API-related
647            bool hasBluetoothPermission = false;
648            bool specMicrophoneFeature = false; // microphone-related
649            bool hasRecordAudioPermission = false;
650            bool specWiFiFeature = false;
651            bool hasWiFiPermission = false;
652            bool specTelephonyFeature = false; // telephony-related
653            bool reqTelephonySubFeature = false;
654            bool hasTelephonyPermission = false;
655            bool specTouchscreenFeature = false; // touchscreen-related
656            bool specMultitouchFeature = false;
657            bool reqDistinctMultitouchFeature = false;
658            bool specScreenPortraitFeature = false;
659            bool specScreenLandscapeFeature = false;
660            bool reqScreenPortraitFeature = false;
661            bool reqScreenLandscapeFeature = false;
662            // 2.2 also added some other features that apps can request, but that
663            // have no corresponding permission, so we cannot implement any
664            // back-compatibility heuristic for them. The below are thus unnecessary
665            // (but are retained here for documentary purposes.)
666            //bool specCompassFeature = false;
667            //bool specAccelerometerFeature = false;
668            //bool specProximityFeature = false;
669            //bool specAmbientLightFeature = false;
670            //bool specLiveWallpaperFeature = false;
671
672            int targetSdk = 0;
673            int smallScreen = 1;
674            int normalScreen = 1;
675            int largeScreen = 1;
676            int xlargeScreen = 1;
677            int anyDensity = 1;
678            int requiresSmallestWidthDp = 0;
679            int compatibleWidthLimitDp = 0;
680            int largestWidthLimitDp = 0;
681            String8 pkg;
682            String8 activityName;
683            String8 activityLabel;
684            String8 activityIcon;
685            String8 receiverName;
686            String8 serviceName;
687            while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
688                if (code == ResXMLTree::END_TAG) {
689                    depth--;
690                    if (depth < 2) {
691                        withinApplication = false;
692                    } else if (depth < 3) {
693                        if (withinActivity && isMainActivity && isLauncherActivity) {
694                            const char *aName = getComponentName(pkg, activityName);
695                            printf("launchable-activity:");
696                            if (aName != NULL) {
697                                printf(" name='%s' ", aName);
698                            }
699                            printf(" label='%s' icon='%s'\n",
700                                    activityLabel.string(),
701                                    activityIcon.string());
702                        }
703                        if (!hasIntentFilter) {
704                            hasOtherActivities |= withinActivity;
705                            hasOtherReceivers |= withinReceiver;
706                            hasOtherServices |= withinService;
707                        }
708                        withinActivity = false;
709                        withinService = false;
710                        withinReceiver = false;
711                        hasIntentFilter = false;
712                        isMainActivity = isLauncherActivity = false;
713                    } else if (depth < 4) {
714                        if (withinIntentFilter) {
715                            if (withinActivity) {
716                                hasMainActivity |= actMainActivity;
717                                hasOtherActivities |= !actMainActivity;
718                            } else if (withinReceiver) {
719                                hasWidgetReceivers |= actWidgetReceivers;
720                                hasOtherReceivers |= !actWidgetReceivers;
721                            } else if (withinService) {
722                                hasImeService |= actImeService;
723                                hasWallpaperService |= actWallpaperService;
724                                hasOtherServices |= (!actImeService && !actWallpaperService);
725                            }
726                        }
727                        withinIntentFilter = false;
728                    }
729                    continue;
730                }
731                if (code != ResXMLTree::START_TAG) {
732                    continue;
733                }
734                depth++;
735                String8 tag(tree.getElementName(&len));
736                //printf("Depth %d,  %s\n", depth, tag.string());
737                if (depth == 1) {
738                    if (tag != "manifest") {
739                        fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
740                        goto bail;
741                    }
742                    pkg = getAttribute(tree, NULL, "package", NULL);
743                    printf("package: name='%s' ", pkg.string());
744                    int32_t versionCode = getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
745                    if (error != "") {
746                        fprintf(stderr, "ERROR getting 'android:versionCode' attribute: %s\n", error.string());
747                        goto bail;
748                    }
749                    if (versionCode > 0) {
750                        printf("versionCode='%d' ", versionCode);
751                    } else {
752                        printf("versionCode='' ");
753                    }
754                    String8 versionName = getResolvedAttribute(&res, tree, VERSION_NAME_ATTR, &error);
755                    if (error != "") {
756                        fprintf(stderr, "ERROR getting 'android:versionName' attribute: %s\n", error.string());
757                        goto bail;
758                    }
759                    printf("versionName='%s'\n", versionName.string());
760                } else if (depth == 2) {
761                    withinApplication = false;
762                    if (tag == "application") {
763                        withinApplication = true;
764
765                        String8 label;
766                        const size_t NL = locales.size();
767                        for (size_t i=0; i<NL; i++) {
768                            const char* localeStr =  locales[i].string();
769                            assets.setLocale(localeStr != NULL ? localeStr : "");
770                            String8 llabel = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
771                            if (llabel != "") {
772                                if (localeStr == NULL || strlen(localeStr) == 0) {
773                                    label = llabel;
774                                    printf("application-label:'%s'\n", llabel.string());
775                                } else {
776                                    if (label == "") {
777                                        label = llabel;
778                                    }
779                                    printf("application-label-%s:'%s'\n", localeStr,
780                                            llabel.string());
781                                }
782                            }
783                        }
784
785                        ResTable_config tmpConfig = config;
786                        const size_t ND = densities.size();
787                        for (size_t i=0; i<ND; i++) {
788                            tmpConfig.density = densities[i];
789                            assets.setConfiguration(tmpConfig);
790                            String8 icon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
791                            if (icon != "") {
792                                printf("application-icon-%d:'%s'\n", densities[i], icon.string());
793                            }
794                        }
795                        assets.setConfiguration(config);
796
797                        String8 icon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
798                        if (error != "") {
799                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
800                            goto bail;
801                        }
802                        int32_t testOnly = getIntegerAttribute(tree, TEST_ONLY_ATTR, &error, 0);
803                        if (error != "") {
804                            fprintf(stderr, "ERROR getting 'android:testOnly' attribute: %s\n", error.string());
805                            goto bail;
806                        }
807                        printf("application: label='%s' ", label.string());
808                        printf("icon='%s'\n", icon.string());
809                        if (testOnly != 0) {
810                            printf("testOnly='%d'\n", testOnly);
811                        }
812                    } else if (tag == "uses-sdk") {
813                        int32_t code = getIntegerAttribute(tree, MIN_SDK_VERSION_ATTR, &error);
814                        if (error != "") {
815                            error = "";
816                            String8 name = getResolvedAttribute(&res, tree, MIN_SDK_VERSION_ATTR, &error);
817                            if (error != "") {
818                                fprintf(stderr, "ERROR getting 'android:minSdkVersion' attribute: %s\n",
819                                        error.string());
820                                goto bail;
821                            }
822                            if (name == "Donut") targetSdk = 4;
823                            printf("sdkVersion:'%s'\n", name.string());
824                        } else if (code != -1) {
825                            targetSdk = code;
826                            printf("sdkVersion:'%d'\n", code);
827                        }
828                        code = getIntegerAttribute(tree, MAX_SDK_VERSION_ATTR, NULL, -1);
829                        if (code != -1) {
830                            printf("maxSdkVersion:'%d'\n", code);
831                        }
832                        code = getIntegerAttribute(tree, TARGET_SDK_VERSION_ATTR, &error);
833                        if (error != "") {
834                            error = "";
835                            String8 name = getResolvedAttribute(&res, tree, TARGET_SDK_VERSION_ATTR, &error);
836                            if (error != "") {
837                                fprintf(stderr, "ERROR getting 'android:targetSdkVersion' attribute: %s\n",
838                                        error.string());
839                                goto bail;
840                            }
841                            if (name == "Donut" && targetSdk < 4) targetSdk = 4;
842                            printf("targetSdkVersion:'%s'\n", name.string());
843                        } else if (code != -1) {
844                            if (targetSdk < code) {
845                                targetSdk = code;
846                            }
847                            printf("targetSdkVersion:'%d'\n", code);
848                        }
849                    } else if (tag == "uses-configuration") {
850                        int32_t reqTouchScreen = getIntegerAttribute(tree,
851                                REQ_TOUCH_SCREEN_ATTR, NULL, 0);
852                        int32_t reqKeyboardType = getIntegerAttribute(tree,
853                                REQ_KEYBOARD_TYPE_ATTR, NULL, 0);
854                        int32_t reqHardKeyboard = getIntegerAttribute(tree,
855                                REQ_HARD_KEYBOARD_ATTR, NULL, 0);
856                        int32_t reqNavigation = getIntegerAttribute(tree,
857                                REQ_NAVIGATION_ATTR, NULL, 0);
858                        int32_t reqFiveWayNav = getIntegerAttribute(tree,
859                                REQ_FIVE_WAY_NAV_ATTR, NULL, 0);
860                        printf("uses-configuration:");
861                        if (reqTouchScreen != 0) {
862                            printf(" reqTouchScreen='%d'", reqTouchScreen);
863                        }
864                        if (reqKeyboardType != 0) {
865                            printf(" reqKeyboardType='%d'", reqKeyboardType);
866                        }
867                        if (reqHardKeyboard != 0) {
868                            printf(" reqHardKeyboard='%d'", reqHardKeyboard);
869                        }
870                        if (reqNavigation != 0) {
871                            printf(" reqNavigation='%d'", reqNavigation);
872                        }
873                        if (reqFiveWayNav != 0) {
874                            printf(" reqFiveWayNav='%d'", reqFiveWayNav);
875                        }
876                        printf("\n");
877                    } else if (tag == "supports-screens") {
878                        smallScreen = getIntegerAttribute(tree,
879                                SMALL_SCREEN_ATTR, NULL, 1);
880                        normalScreen = getIntegerAttribute(tree,
881                                NORMAL_SCREEN_ATTR, NULL, 1);
882                        largeScreen = getIntegerAttribute(tree,
883                                LARGE_SCREEN_ATTR, NULL, 1);
884                        xlargeScreen = getIntegerAttribute(tree,
885                                XLARGE_SCREEN_ATTR, NULL, 1);
886                        anyDensity = getIntegerAttribute(tree,
887                                ANY_DENSITY_ATTR, NULL, 1);
888                        requiresSmallestWidthDp = getIntegerAttribute(tree,
889                                REQUIRES_SMALLEST_WIDTH_DP_ATTR, NULL, 0);
890                        compatibleWidthLimitDp = getIntegerAttribute(tree,
891                                COMPATIBLE_WIDTH_LIMIT_DP_ATTR, NULL, 0);
892                        largestWidthLimitDp = getIntegerAttribute(tree,
893                                LARGEST_WIDTH_LIMIT_DP_ATTR, NULL, 0);
894                    } else if (tag == "uses-feature") {
895                        String8 name = getAttribute(tree, NAME_ATTR, &error);
896
897                        if (name != "" && error == "") {
898                            int req = getIntegerAttribute(tree,
899                                    REQUIRED_ATTR, NULL, 1);
900
901                            if (name == "android.hardware.camera") {
902                                specCameraFeature = true;
903                            } else if (name == "android.hardware.camera.autofocus") {
904                                // these have no corresponding permission to check for,
905                                // but should imply the foundational camera permission
906                                reqCameraAutofocusFeature = reqCameraAutofocusFeature || req;
907                                specCameraAutofocusFeature = true;
908                            } else if (req && (name == "android.hardware.camera.flash")) {
909                                // these have no corresponding permission to check for,
910                                // but should imply the foundational camera permission
911                                reqCameraFlashFeature = true;
912                            } else if (name == "android.hardware.location") {
913                                specLocationFeature = true;
914                            } else if (name == "android.hardware.location.network") {
915                                specNetworkLocFeature = true;
916                                reqNetworkLocFeature = reqNetworkLocFeature || req;
917                            } else if (name == "android.hardware.location.gps") {
918                                specGpsFeature = true;
919                                reqGpsFeature = reqGpsFeature || req;
920                            } else if (name == "android.hardware.bluetooth") {
921                                specBluetoothFeature = true;
922                            } else if (name == "android.hardware.touchscreen") {
923                                specTouchscreenFeature = true;
924                            } else if (name == "android.hardware.touchscreen.multitouch") {
925                                specMultitouchFeature = true;
926                            } else if (name == "android.hardware.touchscreen.multitouch.distinct") {
927                                reqDistinctMultitouchFeature = reqDistinctMultitouchFeature || req;
928                            } else if (name == "android.hardware.microphone") {
929                                specMicrophoneFeature = true;
930                            } else if (name == "android.hardware.wifi") {
931                                specWiFiFeature = true;
932                            } else if (name == "android.hardware.telephony") {
933                                specTelephonyFeature = true;
934                            } else if (req && (name == "android.hardware.telephony.gsm" ||
935                                               name == "android.hardware.telephony.cdma")) {
936                                // these have no corresponding permission to check for,
937                                // but should imply the foundational telephony permission
938                                reqTelephonySubFeature = true;
939                            } else if (name == "android.hardware.screen.portrait") {
940                                specScreenPortraitFeature = true;
941                            } else if (name == "android.hardware.screen.landscape") {
942                                specScreenLandscapeFeature = true;
943                            }
944                            printf("uses-feature%s:'%s'\n",
945                                    req ? "" : "-not-required", name.string());
946                        } else {
947                            int vers = getIntegerAttribute(tree,
948                                    GL_ES_VERSION_ATTR, &error);
949                            if (error == "") {
950                                printf("uses-gl-es:'0x%x'\n", vers);
951                            }
952                        }
953                    } else if (tag == "uses-permission") {
954                        String8 name = getAttribute(tree, NAME_ATTR, &error);
955                        if (name != "" && error == "") {
956                            if (name == "android.permission.CAMERA") {
957                                hasCameraPermission = true;
958                            } else if (name == "android.permission.ACCESS_FINE_LOCATION") {
959                                hasGpsPermission = true;
960                            } else if (name == "android.permission.ACCESS_MOCK_LOCATION") {
961                                hasMockLocPermission = true;
962                            } else if (name == "android.permission.ACCESS_COARSE_LOCATION") {
963                                hasCoarseLocPermission = true;
964                            } else if (name == "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" ||
965                                       name == "android.permission.INSTALL_LOCATION_PROVIDER") {
966                                hasGeneralLocPermission = true;
967                            } else if (name == "android.permission.BLUETOOTH" ||
968                                       name == "android.permission.BLUETOOTH_ADMIN") {
969                                hasBluetoothPermission = true;
970                            } else if (name == "android.permission.RECORD_AUDIO") {
971                                hasRecordAudioPermission = true;
972                            } else if (name == "android.permission.ACCESS_WIFI_STATE" ||
973                                       name == "android.permission.CHANGE_WIFI_STATE" ||
974                                       name == "android.permission.CHANGE_WIFI_MULTICAST_STATE") {
975                                hasWiFiPermission = true;
976                            } else if (name == "android.permission.CALL_PHONE" ||
977                                       name == "android.permission.CALL_PRIVILEGED" ||
978                                       name == "android.permission.MODIFY_PHONE_STATE" ||
979                                       name == "android.permission.PROCESS_OUTGOING_CALLS" ||
980                                       name == "android.permission.READ_SMS" ||
981                                       name == "android.permission.RECEIVE_SMS" ||
982                                       name == "android.permission.RECEIVE_MMS" ||
983                                       name == "android.permission.RECEIVE_WAP_PUSH" ||
984                                       name == "android.permission.SEND_SMS" ||
985                                       name == "android.permission.WRITE_APN_SETTINGS" ||
986                                       name == "android.permission.WRITE_SMS") {
987                                hasTelephonyPermission = true;
988                            }
989                            printf("uses-permission:'%s'\n", name.string());
990                        } else {
991                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
992                                    error.string());
993                            goto bail;
994                        }
995                    } else if (tag == "uses-package") {
996                        String8 name = getAttribute(tree, NAME_ATTR, &error);
997                        if (name != "" && error == "") {
998                            printf("uses-package:'%s'\n", name.string());
999                        } else {
1000                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
1001                                    error.string());
1002                                goto bail;
1003                        }
1004                    } else if (tag == "original-package") {
1005                        String8 name = getAttribute(tree, NAME_ATTR, &error);
1006                        if (name != "" && error == "") {
1007                            printf("original-package:'%s'\n", name.string());
1008                        } else {
1009                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
1010                                    error.string());
1011                                goto bail;
1012                        }
1013                    } else if (tag == "supports-gl-texture") {
1014                        String8 name = getAttribute(tree, NAME_ATTR, &error);
1015                        if (name != "" && error == "") {
1016                            printf("supports-gl-texture:'%s'\n", name.string());
1017                        } else {
1018                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
1019                                    error.string());
1020                                goto bail;
1021                        }
1022                    } else if (tag == "compatible-screens") {
1023                        printCompatibleScreens(tree);
1024                        depth--;
1025                    } else if (tag == "package-verifier") {
1026                        String8 name = getAttribute(tree, NAME_ATTR, &error);
1027                        if (name != "" && error == "") {
1028                            String8 publicKey = getAttribute(tree, PUBLIC_KEY_ATTR, &error);
1029                            if (publicKey != "" && error == "") {
1030                                printf("package-verifier: name='%s' publicKey='%s'\n",
1031                                        name.string(), publicKey.string());
1032                            }
1033                        }
1034                    }
1035                } else if (depth == 3 && withinApplication) {
1036                    withinActivity = false;
1037                    withinReceiver = false;
1038                    withinService = false;
1039                    hasIntentFilter = false;
1040                    if(tag == "activity") {
1041                        withinActivity = true;
1042                        activityName = getAttribute(tree, NAME_ATTR, &error);
1043                        if (error != "") {
1044                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
1045                            goto bail;
1046                        }
1047
1048                        activityLabel = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
1049                        if (error != "") {
1050                            fprintf(stderr, "ERROR getting 'android:label' attribute: %s\n", error.string());
1051                            goto bail;
1052                        }
1053
1054                        activityIcon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
1055                        if (error != "") {
1056                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
1057                            goto bail;
1058                        }
1059
1060                        int32_t orien = getResolvedIntegerAttribute(&res, tree,
1061                                SCREEN_ORIENTATION_ATTR, &error);
1062                        if (error == "") {
1063                            if (orien == 0 || orien == 6 || orien == 8) {
1064                                // Requests landscape, sensorLandscape, or reverseLandscape.
1065                                reqScreenLandscapeFeature = true;
1066                            } else if (orien == 1 || orien == 7 || orien == 9) {
1067                                // Requests portrait, sensorPortrait, or reversePortrait.
1068                                reqScreenPortraitFeature = true;
1069                            }
1070                        }
1071                    } else if (tag == "uses-library") {
1072                        String8 libraryName = getAttribute(tree, NAME_ATTR, &error);
1073                        if (error != "") {
1074                            fprintf(stderr, "ERROR getting 'android:name' attribute for uses-library: %s\n", error.string());
1075                            goto bail;
1076                        }
1077                        int req = getIntegerAttribute(tree,
1078                                REQUIRED_ATTR, NULL, 1);
1079                        printf("uses-library%s:'%s'\n",
1080                                req ? "" : "-not-required", libraryName.string());
1081                    } else if (tag == "receiver") {
1082                        withinReceiver = true;
1083                        receiverName = getAttribute(tree, NAME_ATTR, &error);
1084
1085                        if (error != "") {
1086                            fprintf(stderr, "ERROR getting 'android:name' attribute for receiver: %s\n", error.string());
1087                            goto bail;
1088                        }
1089                    } else if (tag == "service") {
1090                        withinService = true;
1091                        serviceName = getAttribute(tree, NAME_ATTR, &error);
1092
1093                        if (error != "") {
1094                            fprintf(stderr, "ERROR getting 'android:name' attribute for service: %s\n", error.string());
1095                            goto bail;
1096                        }
1097                    }
1098                } else if ((depth == 4) && (tag == "intent-filter")) {
1099                    hasIntentFilter = true;
1100                    withinIntentFilter = true;
1101                    actMainActivity = actWidgetReceivers = actImeService = actWallpaperService = false;
1102                } else if ((depth == 5) && withinIntentFilter){
1103                    String8 action;
1104                    if (tag == "action") {
1105                        action = getAttribute(tree, NAME_ATTR, &error);
1106                        if (error != "") {
1107                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
1108                            goto bail;
1109                        }
1110                        if (withinActivity) {
1111                            if (action == "android.intent.action.MAIN") {
1112                                isMainActivity = true;
1113                                actMainActivity = true;
1114                            }
1115                        } else if (withinReceiver) {
1116                            if (action == "android.appwidget.action.APPWIDGET_UPDATE") {
1117                                actWidgetReceivers = true;
1118                            }
1119                        } else if (withinService) {
1120                            if (action == "android.view.InputMethod") {
1121                                actImeService = true;
1122                            } else if (action == "android.service.wallpaper.WallpaperService") {
1123                                actWallpaperService = true;
1124                            }
1125                        }
1126                        if (action == "android.intent.action.SEARCH") {
1127                            isSearchable = true;
1128                        }
1129                    }
1130
1131                    if (tag == "category") {
1132                        String8 category = getAttribute(tree, NAME_ATTR, &error);
1133                        if (error != "") {
1134                            fprintf(stderr, "ERROR getting 'name' attribute: %s\n", error.string());
1135                            goto bail;
1136                        }
1137                        if (withinActivity) {
1138                            if (category == "android.intent.category.LAUNCHER") {
1139                                isLauncherActivity = true;
1140                            }
1141                        }
1142                    }
1143                }
1144            }
1145
1146            /* The following blocks handle printing "inferred" uses-features, based
1147             * on whether related features or permissions are used by the app.
1148             * Note that the various spec*Feature variables denote whether the
1149             * relevant tag was *present* in the AndroidManfest, not that it was
1150             * present and set to true.
1151             */
1152            // Camera-related back-compatibility logic
1153            if (!specCameraFeature) {
1154                if (reqCameraFlashFeature || reqCameraAutofocusFeature) {
1155                    // if app requested a sub-feature (autofocus or flash) and didn't
1156                    // request the base camera feature, we infer that it meant to
1157                    printf("uses-feature:'android.hardware.camera'\n");
1158                } else if (hasCameraPermission) {
1159                    // if app wants to use camera but didn't request the feature, we infer
1160                    // that it meant to, and further that it wants autofocus
1161                    // (which was the 1.0 - 1.5 behavior)
1162                    printf("uses-feature:'android.hardware.camera'\n");
1163                    if (!specCameraAutofocusFeature) {
1164                        printf("uses-feature:'android.hardware.camera.autofocus'\n");
1165                    }
1166                }
1167            }
1168
1169            // Location-related back-compatibility logic
1170            if (!specLocationFeature &&
1171                (hasMockLocPermission || hasCoarseLocPermission || hasGpsPermission ||
1172                 hasGeneralLocPermission || reqNetworkLocFeature || reqGpsFeature)) {
1173                // if app either takes a location-related permission or requests one of the
1174                // sub-features, we infer that it also meant to request the base location feature
1175                printf("uses-feature:'android.hardware.location'\n");
1176            }
1177            if (!specGpsFeature && hasGpsPermission) {
1178                // if app takes GPS (FINE location) perm but does not request the GPS
1179                // feature, we infer that it meant to
1180                printf("uses-feature:'android.hardware.location.gps'\n");
1181            }
1182            if (!specNetworkLocFeature && hasCoarseLocPermission) {
1183                // if app takes Network location (COARSE location) perm but does not request the
1184                // network location feature, we infer that it meant to
1185                printf("uses-feature:'android.hardware.location.network'\n");
1186            }
1187
1188            // Bluetooth-related compatibility logic
1189            if (!specBluetoothFeature && hasBluetoothPermission && (targetSdk > 4)) {
1190                // if app takes a Bluetooth permission but does not request the Bluetooth
1191                // feature, we infer that it meant to
1192                printf("uses-feature:'android.hardware.bluetooth'\n");
1193            }
1194
1195            // Microphone-related compatibility logic
1196            if (!specMicrophoneFeature && hasRecordAudioPermission) {
1197                // if app takes the record-audio permission but does not request the microphone
1198                // feature, we infer that it meant to
1199                printf("uses-feature:'android.hardware.microphone'\n");
1200            }
1201
1202            // WiFi-related compatibility logic
1203            if (!specWiFiFeature && hasWiFiPermission) {
1204                // if app takes one of the WiFi permissions but does not request the WiFi
1205                // feature, we infer that it meant to
1206                printf("uses-feature:'android.hardware.wifi'\n");
1207            }
1208
1209            // Telephony-related compatibility logic
1210            if (!specTelephonyFeature && (hasTelephonyPermission || reqTelephonySubFeature)) {
1211                // if app takes one of the telephony permissions or requests a sub-feature but
1212                // does not request the base telephony feature, we infer that it meant to
1213                printf("uses-feature:'android.hardware.telephony'\n");
1214            }
1215
1216            // Touchscreen-related back-compatibility logic
1217            if (!specTouchscreenFeature) { // not a typo!
1218                // all apps are presumed to require a touchscreen, unless they explicitly say
1219                // <uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
1220                // Note that specTouchscreenFeature is true if the tag is present, regardless
1221                // of whether its value is true or false, so this is safe
1222                printf("uses-feature:'android.hardware.touchscreen'\n");
1223            }
1224            if (!specMultitouchFeature && reqDistinctMultitouchFeature) {
1225                // if app takes one of the telephony permissions or requests a sub-feature but
1226                // does not request the base telephony feature, we infer that it meant to
1227                printf("uses-feature:'android.hardware.touchscreen.multitouch'\n");
1228            }
1229
1230            // Landscape/portrait-related compatibility logic
1231            if (!specScreenLandscapeFeature && !specScreenPortraitFeature) {
1232                // If the app has specified any activities in its manifest
1233                // that request a specific orientation, then assume that
1234                // orientation is required.
1235                if (reqScreenLandscapeFeature) {
1236                    printf("uses-feature:'android.hardware.screen.landscape'\n");
1237                }
1238                if (reqScreenPortraitFeature) {
1239                    printf("uses-feature:'android.hardware.screen.portrait'\n");
1240                }
1241            }
1242
1243            if (hasMainActivity) {
1244                printf("main\n");
1245            }
1246            if (hasWidgetReceivers) {
1247                printf("app-widget\n");
1248            }
1249            if (hasImeService) {
1250                printf("ime\n");
1251            }
1252            if (hasWallpaperService) {
1253                printf("wallpaper\n");
1254            }
1255            if (hasOtherActivities) {
1256                printf("other-activities\n");
1257            }
1258            if (isSearchable) {
1259                printf("search\n");
1260            }
1261            if (hasOtherReceivers) {
1262                printf("other-receivers\n");
1263            }
1264            if (hasOtherServices) {
1265                printf("other-services\n");
1266            }
1267
1268            // For modern apps, if screen size buckets haven't been specified
1269            // but the new width ranges have, then infer the buckets from them.
1270            if (smallScreen > 0 && normalScreen > 0 && largeScreen > 0 && xlargeScreen > 0
1271                    && requiresSmallestWidthDp > 0) {
1272                int compatWidth = compatibleWidthLimitDp;
1273                if (compatWidth <= 0) compatWidth = requiresSmallestWidthDp;
1274                if (requiresSmallestWidthDp <= 240 && compatWidth >= 240) {
1275                    smallScreen = -1;
1276                } else {
1277                    smallScreen = 0;
1278                }
1279                if (requiresSmallestWidthDp <= 320 && compatWidth >= 320) {
1280                    normalScreen = -1;
1281                } else {
1282                    normalScreen = 0;
1283                }
1284                if (requiresSmallestWidthDp <= 480 && compatWidth >= 480) {
1285                    largeScreen = -1;
1286                } else {
1287                    largeScreen = 0;
1288                }
1289                if (requiresSmallestWidthDp <= 720 && compatWidth >= 720) {
1290                    xlargeScreen = -1;
1291                } else {
1292                    xlargeScreen = 0;
1293                }
1294            }
1295
1296            // Determine default values for any unspecified screen sizes,
1297            // based on the target SDK of the package.  As of 4 (donut)
1298            // the screen size support was introduced, so all default to
1299            // enabled.
1300            if (smallScreen > 0) {
1301                smallScreen = targetSdk >= 4 ? -1 : 0;
1302            }
1303            if (normalScreen > 0) {
1304                normalScreen = -1;
1305            }
1306            if (largeScreen > 0) {
1307                largeScreen = targetSdk >= 4 ? -1 : 0;
1308            }
1309            if (xlargeScreen > 0) {
1310                // Introduced in Gingerbread.
1311                xlargeScreen = targetSdk >= 9 ? -1 : 0;
1312            }
1313            if (anyDensity > 0) {
1314                anyDensity = (targetSdk >= 4 || requiresSmallestWidthDp > 0
1315                        || compatibleWidthLimitDp > 0) ? -1 : 0;
1316            }
1317            printf("supports-screens:");
1318            if (smallScreen != 0) printf(" 'small'");
1319            if (normalScreen != 0) printf(" 'normal'");
1320            if (largeScreen != 0) printf(" 'large'");
1321            if (xlargeScreen != 0) printf(" 'xlarge'");
1322            printf("\n");
1323            printf("supports-any-density: '%s'\n", anyDensity ? "true" : "false");
1324            if (requiresSmallestWidthDp > 0) {
1325                printf("requires-smallest-width:'%d'\n", requiresSmallestWidthDp);
1326            }
1327            if (compatibleWidthLimitDp > 0) {
1328                printf("compatible-width-limit:'%d'\n", compatibleWidthLimitDp);
1329            }
1330            if (largestWidthLimitDp > 0) {
1331                printf("largest-width-limit:'%d'\n", largestWidthLimitDp);
1332            }
1333
1334            printf("locales:");
1335            const size_t NL = locales.size();
1336            for (size_t i=0; i<NL; i++) {
1337                const char* localeStr =  locales[i].string();
1338                if (localeStr == NULL || strlen(localeStr) == 0) {
1339                    localeStr = "--_--";
1340                }
1341                printf(" '%s'", localeStr);
1342            }
1343            printf("\n");
1344
1345            printf("densities:");
1346            const size_t ND = densities.size();
1347            for (size_t i=0; i<ND; i++) {
1348                printf(" '%d'", densities[i]);
1349            }
1350            printf("\n");
1351
1352            AssetDir* dir = assets.openNonAssetDir(assetsCookie, "lib");
1353            if (dir != NULL) {
1354                if (dir->getFileCount() > 0) {
1355                    printf("native-code:");
1356                    for (size_t i=0; i<dir->getFileCount(); i++) {
1357                        printf(" '%s'", dir->getFileName(i).string());
1358                    }
1359                    printf("\n");
1360                }
1361                delete dir;
1362            }
1363        } else if (strcmp("configurations", option) == 0) {
1364            Vector<ResTable_config> configs;
1365            res.getConfigurations(&configs);
1366            const size_t N = configs.size();
1367            for (size_t i=0; i<N; i++) {
1368                printf("%s\n", configs[i].toString().string());
1369            }
1370        } else {
1371            fprintf(stderr, "ERROR: unknown dump option '%s'\n", option);
1372            goto bail;
1373        }
1374    }
1375
1376    result = NO_ERROR;
1377
1378bail:
1379    if (asset) {
1380        delete asset;
1381    }
1382    return (result != NO_ERROR);
1383}
1384
1385
1386/*
1387 * Handle the "add" command, which wants to add files to a new or
1388 * pre-existing archive.
1389 */
1390int doAdd(Bundle* bundle)
1391{
1392    ZipFile* zip = NULL;
1393    status_t result = UNKNOWN_ERROR;
1394    const char* zipFileName;
1395
1396    if (bundle->getUpdate()) {
1397        /* avoid confusion */
1398        fprintf(stderr, "ERROR: can't use '-u' with add\n");
1399        goto bail;
1400    }
1401
1402    if (bundle->getFileSpecCount() < 1) {
1403        fprintf(stderr, "ERROR: must specify zip file name\n");
1404        goto bail;
1405    }
1406    zipFileName = bundle->getFileSpecEntry(0);
1407
1408    if (bundle->getFileSpecCount() < 2) {
1409        fprintf(stderr, "NOTE: nothing to do\n");
1410        goto bail;
1411    }
1412
1413    zip = openReadWrite(zipFileName, true);
1414    if (zip == NULL) {
1415        fprintf(stderr, "ERROR: failed opening/creating '%s' as Zip file\n", zipFileName);
1416        goto bail;
1417    }
1418
1419    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
1420        const char* fileName = bundle->getFileSpecEntry(i);
1421
1422        if (strcasecmp(String8(fileName).getPathExtension().string(), ".gz") == 0) {
1423            printf(" '%s'... (from gzip)\n", fileName);
1424            result = zip->addGzip(fileName, String8(fileName).getBasePath().string(), NULL);
1425        } else {
1426            if (bundle->getJunkPath()) {
1427                String8 storageName = String8(fileName).getPathLeaf();
1428                printf(" '%s' as '%s'...\n", fileName, storageName.string());
1429                result = zip->add(fileName, storageName.string(),
1430                                  bundle->getCompressionMethod(), NULL);
1431            } else {
1432                printf(" '%s'...\n", fileName);
1433                result = zip->add(fileName, bundle->getCompressionMethod(), NULL);
1434            }
1435        }
1436        if (result != NO_ERROR) {
1437            fprintf(stderr, "Unable to add '%s' to '%s'", bundle->getFileSpecEntry(i), zipFileName);
1438            if (result == NAME_NOT_FOUND)
1439                fprintf(stderr, ": file not found\n");
1440            else if (result == ALREADY_EXISTS)
1441                fprintf(stderr, ": already exists in archive\n");
1442            else
1443                fprintf(stderr, "\n");
1444            goto bail;
1445        }
1446    }
1447
1448    result = NO_ERROR;
1449
1450bail:
1451    delete zip;
1452    return (result != NO_ERROR);
1453}
1454
1455
1456/*
1457 * Delete files from an existing archive.
1458 */
1459int doRemove(Bundle* bundle)
1460{
1461    ZipFile* zip = NULL;
1462    status_t result = UNKNOWN_ERROR;
1463    const char* zipFileName;
1464
1465    if (bundle->getFileSpecCount() < 1) {
1466        fprintf(stderr, "ERROR: must specify zip file name\n");
1467        goto bail;
1468    }
1469    zipFileName = bundle->getFileSpecEntry(0);
1470
1471    if (bundle->getFileSpecCount() < 2) {
1472        fprintf(stderr, "NOTE: nothing to do\n");
1473        goto bail;
1474    }
1475
1476    zip = openReadWrite(zipFileName, false);
1477    if (zip == NULL) {
1478        fprintf(stderr, "ERROR: failed opening Zip archive '%s'\n",
1479            zipFileName);
1480        goto bail;
1481    }
1482
1483    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
1484        const char* fileName = bundle->getFileSpecEntry(i);
1485        ZipEntry* entry;
1486
1487        entry = zip->getEntryByName(fileName);
1488        if (entry == NULL) {
1489            printf(" '%s' NOT FOUND\n", fileName);
1490            continue;
1491        }
1492
1493        result = zip->remove(entry);
1494
1495        if (result != NO_ERROR) {
1496            fprintf(stderr, "Unable to delete '%s' from '%s'\n",
1497                bundle->getFileSpecEntry(i), zipFileName);
1498            goto bail;
1499        }
1500    }
1501
1502    /* update the archive */
1503    zip->flush();
1504
1505bail:
1506    delete zip;
1507    return (result != NO_ERROR);
1508}
1509
1510
1511/*
1512 * Package up an asset directory and associated application files.
1513 */
1514int doPackage(Bundle* bundle)
1515{
1516    const char* outputAPKFile;
1517    int retVal = 1;
1518    status_t err;
1519    sp<AaptAssets> assets;
1520    int N;
1521    FILE* fp;
1522    String8 dependencyFile;
1523
1524    // -c zz_ZZ means do pseudolocalization
1525    ResourceFilter filter;
1526    err = filter.parse(bundle->getConfigurations());
1527    if (err != NO_ERROR) {
1528        goto bail;
1529    }
1530    if (filter.containsPseudo()) {
1531        bundle->setPseudolocalize(true);
1532    }
1533
1534    N = bundle->getFileSpecCount();
1535    if (N < 1 && bundle->getResourceSourceDirs().size() == 0 && bundle->getJarFiles().size() == 0
1536            && bundle->getAndroidManifestFile() == NULL && bundle->getAssetSourceDir() == NULL) {
1537        fprintf(stderr, "ERROR: no input files\n");
1538        goto bail;
1539    }
1540
1541    outputAPKFile = bundle->getOutputAPKFile();
1542
1543    // Make sure the filenames provided exist and are of the appropriate type.
1544    if (outputAPKFile) {
1545        FileType type;
1546        type = getFileType(outputAPKFile);
1547        if (type != kFileTypeNonexistent && type != kFileTypeRegular) {
1548            fprintf(stderr,
1549                "ERROR: output file '%s' exists but is not regular file\n",
1550                outputAPKFile);
1551            goto bail;
1552        }
1553    }
1554
1555    // Load the assets.
1556    assets = new AaptAssets();
1557
1558    // Set up the resource gathering in assets if we're going to generate
1559    // dependency files. Every time we encounter a resource while slurping
1560    // the tree, we'll add it to these stores so we have full resource paths
1561    // to write to a dependency file.
1562    if (bundle->getGenDependencies()) {
1563        sp<FilePathStore> resPathStore = new FilePathStore;
1564        assets->setFullResPaths(resPathStore);
1565        sp<FilePathStore> assetPathStore = new FilePathStore;
1566        assets->setFullAssetPaths(assetPathStore);
1567    }
1568
1569    err = assets->slurpFromArgs(bundle);
1570    if (err < 0) {
1571        goto bail;
1572    }
1573
1574    if (bundle->getVerbose()) {
1575        assets->print();
1576    }
1577
1578    // If they asked for any fileAs that need to be compiled, do so.
1579    if (bundle->getResourceSourceDirs().size() || bundle->getAndroidManifestFile()) {
1580        err = buildResources(bundle, assets);
1581        if (err != 0) {
1582            goto bail;
1583        }
1584    }
1585
1586    // At this point we've read everything and processed everything.  From here
1587    // on out it's just writing output files.
1588    if (SourcePos::hasErrors()) {
1589        goto bail;
1590    }
1591
1592    // If we've been asked to generate a dependency file, do that here
1593    if (bundle->getGenDependencies()) {
1594        // If this is the packaging step, generate the dependency file next to
1595        // the output apk (e.g. bin/resources.ap_.d)
1596        if (outputAPKFile) {
1597            dependencyFile = String8(outputAPKFile);
1598            // Add the .d extension to the dependency file.
1599            dependencyFile.append(".d");
1600        } else {
1601            // Else if this is the R.java dependency generation step,
1602            // generate the dependency file in the R.java package subdirectory
1603            // e.g. gen/com/foo/app/R.java.d
1604            dependencyFile = String8(bundle->getRClassDir());
1605            dependencyFile.appendPath("R.java.d");
1606        }
1607        // Make sure we have a clean dependency file to start with
1608        fp = fopen(dependencyFile, "w");
1609        fclose(fp);
1610    }
1611
1612    // Write out R.java constants
1613    if (assets->getPackage() == assets->getSymbolsPrivatePackage()) {
1614        if (bundle->getCustomPackage() == NULL) {
1615            // Write the R.java file into the appropriate class directory
1616            // e.g. gen/com/foo/app/R.java
1617            err = writeResourceSymbols(bundle, assets, assets->getPackage(), true);
1618            // If we have library files, we're going to write our R.java file into
1619            // the appropriate class directory for those libraries as well.
1620            // e.g. gen/com/foo/app/lib/R.java
1621            if (bundle->getExtraPackages() != NULL) {
1622                // Split on colon
1623                String8 libs(bundle->getExtraPackages());
1624                char* packageString = strtok(libs.lockBuffer(libs.length()), ":");
1625                while (packageString != NULL) {
1626                    // Write the R.java file out with the correct package name
1627                    err = writeResourceSymbols(bundle, assets, String8(packageString), true);
1628                    packageString = strtok(NULL, ":");
1629                }
1630                libs.unlockBuffer();
1631            }
1632        } else {
1633            const String8 customPkg(bundle->getCustomPackage());
1634            err = writeResourceSymbols(bundle, assets, customPkg, true);
1635        }
1636        if (err < 0) {
1637            goto bail;
1638        }
1639    } else {
1640        err = writeResourceSymbols(bundle, assets, assets->getPackage(), false);
1641        if (err < 0) {
1642            goto bail;
1643        }
1644        err = writeResourceSymbols(bundle, assets, assets->getSymbolsPrivatePackage(), true);
1645        if (err < 0) {
1646            goto bail;
1647        }
1648    }
1649
1650    // Write out the ProGuard file
1651    err = writeProguardFile(bundle, assets);
1652    if (err < 0) {
1653        goto bail;
1654    }
1655
1656    // Write the apk
1657    if (outputAPKFile) {
1658        err = writeAPK(bundle, assets, String8(outputAPKFile));
1659        if (err != NO_ERROR) {
1660            fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputAPKFile);
1661            goto bail;
1662        }
1663    }
1664
1665    // If we've been asked to generate a dependency file, we need to finish up here.
1666    // the writeResourceSymbols and writeAPK functions have already written the target
1667    // half of the dependency file, now we need to write the prerequisites. (files that
1668    // the R.java file or .ap_ file depend on)
1669    if (bundle->getGenDependencies()) {
1670        // Now that writeResourceSymbols or writeAPK has taken care of writing
1671        // the targets to our dependency file, we'll write the prereqs
1672        fp = fopen(dependencyFile, "a+");
1673        fprintf(fp, " : ");
1674        bool includeRaw = (outputAPKFile != NULL);
1675        err = writeDependencyPreReqs(bundle, assets, fp, includeRaw);
1676        // Also manually add the AndroidManifeset since it's not under res/ or assets/
1677        // and therefore was not added to our pathstores during slurping
1678        fprintf(fp, "%s \\\n", bundle->getAndroidManifestFile());
1679        fclose(fp);
1680    }
1681
1682    retVal = 0;
1683bail:
1684    if (SourcePos::hasErrors()) {
1685        SourcePos::printErrors(stderr);
1686    }
1687    return retVal;
1688}
1689
1690/*
1691 * Do PNG Crunching
1692 * PRECONDITIONS
1693 *  -S flag points to a source directory containing drawable* folders
1694 *  -C flag points to destination directory. The folder structure in the
1695 *     source directory will be mirrored to the destination (cache) directory
1696 *
1697 * POSTCONDITIONS
1698 *  Destination directory will be updated to match the PNG files in
1699 *  the source directory.
1700 */
1701int doCrunch(Bundle* bundle)
1702{
1703    fprintf(stdout, "Crunching PNG Files in ");
1704    fprintf(stdout, "source dir: %s\n", bundle->getResourceSourceDirs()[0]);
1705    fprintf(stdout, "To destination dir: %s\n", bundle->getCrunchedOutputDir());
1706
1707    updatePreProcessedCache(bundle);
1708
1709    return NO_ERROR;
1710}
1711