Command.cpp revision 43b6803095e41e6a1cf844a77813c6cdbdc84ec3
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            printf("\nResource table:\n");
202            res.print(false);
203        }
204
205        Asset* manifestAsset = assets.openNonAsset("AndroidManifest.xml",
206                                                   Asset::ACCESS_BUFFER);
207        if (manifestAsset == NULL) {
208            printf("\nNo AndroidManifest.xml found.\n");
209        } else {
210            printf("\nAndroid manifest:\n");
211            ResXMLTree tree;
212            tree.setTo(manifestAsset->getBuffer(true),
213                       manifestAsset->getLength());
214            printXMLBlock(&tree);
215        }
216        delete manifestAsset;
217    }
218
219    result = 0;
220
221bail:
222    delete zip;
223    return result;
224}
225
226static ssize_t indexOfAttribute(const ResXMLTree& tree, uint32_t attrRes)
227{
228    size_t N = tree.getAttributeCount();
229    for (size_t i=0; i<N; i++) {
230        if (tree.getAttributeNameResID(i) == attrRes) {
231            return (ssize_t)i;
232        }
233    }
234    return -1;
235}
236
237String8 getAttribute(const ResXMLTree& tree, const char* ns,
238                            const char* attr, String8* outError)
239{
240    ssize_t idx = tree.indexOfAttribute(ns, attr);
241    if (idx < 0) {
242        return String8();
243    }
244    Res_value value;
245    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
246        if (value.dataType != Res_value::TYPE_STRING) {
247            if (outError != NULL) *outError = "attribute is not a string value";
248            return String8();
249        }
250    }
251    size_t len;
252    const uint16_t* str = tree.getAttributeStringValue(idx, &len);
253    return str ? String8(str, len) : String8();
254}
255
256static String8 getAttribute(const ResXMLTree& tree, uint32_t attrRes, String8* outError)
257{
258    ssize_t idx = indexOfAttribute(tree, attrRes);
259    if (idx < 0) {
260        return String8();
261    }
262    Res_value value;
263    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
264        if (value.dataType != Res_value::TYPE_STRING) {
265            if (outError != NULL) *outError = "attribute is not a string value";
266            return String8();
267        }
268    }
269    size_t len;
270    const uint16_t* str = tree.getAttributeStringValue(idx, &len);
271    return str ? String8(str, len) : String8();
272}
273
274static int32_t getIntegerAttribute(const ResXMLTree& tree, uint32_t attrRes,
275        String8* outError, int32_t defValue = -1)
276{
277    ssize_t idx = indexOfAttribute(tree, attrRes);
278    if (idx < 0) {
279        return defValue;
280    }
281    Res_value value;
282    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
283        if (value.dataType < Res_value::TYPE_FIRST_INT
284                || value.dataType > Res_value::TYPE_LAST_INT) {
285            if (outError != NULL) *outError = "attribute is not an integer value";
286            return defValue;
287        }
288    }
289    return value.data;
290}
291
292static String8 getResolvedAttribute(const ResTable* resTable, const ResXMLTree& tree,
293        uint32_t attrRes, String8* outError)
294{
295    ssize_t idx = indexOfAttribute(tree, attrRes);
296    if (idx < 0) {
297        return String8();
298    }
299    Res_value value;
300    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
301        if (value.dataType == Res_value::TYPE_STRING) {
302            size_t len;
303            const uint16_t* str = tree.getAttributeStringValue(idx, &len);
304            return str ? String8(str, len) : String8();
305        }
306        resTable->resolveReference(&value, 0);
307        if (value.dataType != Res_value::TYPE_STRING) {
308            if (outError != NULL) *outError = "attribute is not a string value";
309            return String8();
310        }
311    }
312    size_t len;
313    const Res_value* value2 = &value;
314    const char16_t* str = const_cast<ResTable*>(resTable)->valueToString(value2, 0, NULL, &len);
315    return str ? String8(str, len) : String8();
316}
317
318// These are attribute resource constants for the platform, as found
319// in android.R.attr
320enum {
321    NAME_ATTR = 0x01010003,
322    VERSION_CODE_ATTR = 0x0101021b,
323    VERSION_NAME_ATTR = 0x0101021c,
324    LABEL_ATTR = 0x01010001,
325    ICON_ATTR = 0x01010002,
326    MIN_SDK_VERSION_ATTR = 0x0101020c,
327    MAX_SDK_VERSION_ATTR = 0x01010271,
328    REQ_TOUCH_SCREEN_ATTR = 0x01010227,
329    REQ_KEYBOARD_TYPE_ATTR = 0x01010228,
330    REQ_HARD_KEYBOARD_ATTR = 0x01010229,
331    REQ_NAVIGATION_ATTR = 0x0101022a,
332    REQ_FIVE_WAY_NAV_ATTR = 0x01010232,
333    TARGET_SDK_VERSION_ATTR = 0x01010270,
334    TEST_ONLY_ATTR = 0x01010272,
335    DENSITY_ATTR = 0x0101026c,
336    GL_ES_VERSION_ATTR = 0x01010281,
337    SMALL_SCREEN_ATTR = 0x01010284,
338    NORMAL_SCREEN_ATTR = 0x01010285,
339    LARGE_SCREEN_ATTR = 0x01010286,
340    XLARGE_SCREEN_ATTR = 0x010102bf,
341    REQUIRED_ATTR = 0x0101028e,
342};
343
344const char *getComponentName(String8 &pkgName, String8 &componentName) {
345    ssize_t idx = componentName.find(".");
346    String8 retStr(pkgName);
347    if (idx == 0) {
348        retStr += componentName;
349    } else if (idx < 0) {
350        retStr += ".";
351        retStr += componentName;
352    } else {
353        return componentName.string();
354    }
355    return retStr.string();
356}
357
358/*
359 * Handle the "dump" command, to extract select data from an archive.
360 */
361int doDump(Bundle* bundle)
362{
363    status_t result = UNKNOWN_ERROR;
364    Asset* asset = NULL;
365
366    if (bundle->getFileSpecCount() < 1) {
367        fprintf(stderr, "ERROR: no dump option specified\n");
368        return 1;
369    }
370
371    if (bundle->getFileSpecCount() < 2) {
372        fprintf(stderr, "ERROR: no dump file specified\n");
373        return 1;
374    }
375
376    const char* option = bundle->getFileSpecEntry(0);
377    const char* filename = bundle->getFileSpecEntry(1);
378
379    AssetManager assets;
380    void* assetsCookie;
381    if (!assets.addAssetPath(String8(filename), &assetsCookie)) {
382        fprintf(stderr, "ERROR: dump failed because assets could not be loaded\n");
383        return 1;
384    }
385
386    const ResTable& res = assets.getResources(false);
387    if (&res == NULL) {
388        fprintf(stderr, "ERROR: dump failed because no resource table was found\n");
389        goto bail;
390    }
391
392    if (strcmp("resources", option) == 0) {
393        res.print(bundle->getValues());
394
395    } else if (strcmp("xmltree", option) == 0) {
396        if (bundle->getFileSpecCount() < 3) {
397            fprintf(stderr, "ERROR: no dump xmltree resource file specified\n");
398            goto bail;
399        }
400
401        for (int i=2; i<bundle->getFileSpecCount(); i++) {
402            const char* resname = bundle->getFileSpecEntry(i);
403            ResXMLTree tree;
404            asset = assets.openNonAsset(resname, Asset::ACCESS_BUFFER);
405            if (asset == NULL) {
406                fprintf(stderr, "ERROR: dump failed because resource %s found\n", resname);
407                goto bail;
408            }
409
410            if (tree.setTo(asset->getBuffer(true),
411                           asset->getLength()) != NO_ERROR) {
412                fprintf(stderr, "ERROR: Resource %s is corrupt\n", resname);
413                goto bail;
414            }
415            tree.restart();
416            printXMLBlock(&tree);
417            tree.uninit();
418            delete asset;
419            asset = NULL;
420        }
421
422    } else if (strcmp("xmlstrings", option) == 0) {
423        if (bundle->getFileSpecCount() < 3) {
424            fprintf(stderr, "ERROR: no dump xmltree resource file specified\n");
425            goto bail;
426        }
427
428        for (int i=2; i<bundle->getFileSpecCount(); i++) {
429            const char* resname = bundle->getFileSpecEntry(i);
430            ResXMLTree tree;
431            asset = assets.openNonAsset(resname, Asset::ACCESS_BUFFER);
432            if (asset == NULL) {
433                fprintf(stderr, "ERROR: dump failed because resource %s found\n", resname);
434                goto bail;
435            }
436
437            if (tree.setTo(asset->getBuffer(true),
438                           asset->getLength()) != NO_ERROR) {
439                fprintf(stderr, "ERROR: Resource %s is corrupt\n", resname);
440                goto bail;
441            }
442            printStringPool(&tree.getStrings());
443            delete asset;
444            asset = NULL;
445        }
446
447    } else {
448        ResXMLTree tree;
449        asset = assets.openNonAsset("AndroidManifest.xml",
450                                            Asset::ACCESS_BUFFER);
451        if (asset == NULL) {
452            fprintf(stderr, "ERROR: dump failed because no AndroidManifest.xml found\n");
453            goto bail;
454        }
455
456        if (tree.setTo(asset->getBuffer(true),
457                       asset->getLength()) != NO_ERROR) {
458            fprintf(stderr, "ERROR: AndroidManifest.xml is corrupt\n");
459            goto bail;
460        }
461        tree.restart();
462
463        if (strcmp("permissions", option) == 0) {
464            size_t len;
465            ResXMLTree::event_code_t code;
466            int depth = 0;
467            while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
468                if (code == ResXMLTree::END_TAG) {
469                    depth--;
470                    continue;
471                }
472                if (code != ResXMLTree::START_TAG) {
473                    continue;
474                }
475                depth++;
476                String8 tag(tree.getElementName(&len));
477                //printf("Depth %d tag %s\n", depth, tag.string());
478                if (depth == 1) {
479                    if (tag != "manifest") {
480                        fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
481                        goto bail;
482                    }
483                    String8 pkg = getAttribute(tree, NULL, "package", NULL);
484                    printf("package: %s\n", pkg.string());
485                } else if (depth == 2 && tag == "permission") {
486                    String8 error;
487                    String8 name = getAttribute(tree, NAME_ATTR, &error);
488                    if (error != "") {
489                        fprintf(stderr, "ERROR: %s\n", error.string());
490                        goto bail;
491                    }
492                    printf("permission: %s\n", name.string());
493                } else if (depth == 2 && tag == "uses-permission") {
494                    String8 error;
495                    String8 name = getAttribute(tree, NAME_ATTR, &error);
496                    if (error != "") {
497                        fprintf(stderr, "ERROR: %s\n", error.string());
498                        goto bail;
499                    }
500                    printf("uses-permission: %s\n", name.string());
501                }
502            }
503        } else if (strcmp("badging", option) == 0) {
504            size_t len;
505            ResXMLTree::event_code_t code;
506            int depth = 0;
507            String8 error;
508            bool withinActivity = false;
509            bool isMainActivity = false;
510            bool isLauncherActivity = false;
511            bool isSearchable = false;
512            bool withinApplication = false;
513            bool withinReceiver = false;
514            bool withinService = false;
515            bool withinIntentFilter = false;
516            bool hasMainActivity = false;
517            bool hasOtherActivities = false;
518            bool hasOtherReceivers = false;
519            bool hasOtherServices = false;
520            bool hasWallpaperService = false;
521            bool hasImeService = false;
522            bool hasWidgetReceivers = false;
523            bool hasIntentFilter = false;
524            bool actMainActivity = false;
525            bool actWidgetReceivers = false;
526            bool actImeService = false;
527            bool actWallpaperService = false;
528
529            // This next group of variables is used to implement a group of
530            // backward-compatibility heuristics necessitated by the addition of
531            // some new uses-feature constants in 2.1 and 2.2. In most cases, the
532            // heuristic is "if an app requests a permission but doesn't explicitly
533            // request the corresponding <uses-feature>, presume it's there anyway".
534            bool specCameraFeature = false; // camera-related
535            bool specCameraAutofocusFeature = false;
536            bool reqCameraAutofocusFeature = false;
537            bool reqCameraFlashFeature = false;
538            bool hasCameraPermission = false;
539            bool specLocationFeature = false; // location-related
540            bool specNetworkLocFeature = false;
541            bool reqNetworkLocFeature = false;
542            bool specGpsFeature = false;
543            bool reqGpsFeature = false;
544            bool hasMockLocPermission = false;
545            bool hasCoarseLocPermission = false;
546            bool hasGpsPermission = false;
547            bool hasGeneralLocPermission = false;
548            bool specBluetoothFeature = false; // Bluetooth API-related
549            bool hasBluetoothPermission = false;
550            bool specMicrophoneFeature = false; // microphone-related
551            bool hasRecordAudioPermission = false;
552            bool specWiFiFeature = false;
553            bool hasWiFiPermission = false;
554            bool specTelephonyFeature = false; // telephony-related
555            bool reqTelephonySubFeature = false;
556            bool hasTelephonyPermission = false;
557            bool specTouchscreenFeature = false; // touchscreen-related
558            bool specMultitouchFeature = false;
559            bool reqDistinctMultitouchFeature = false;
560            // 2.2 also added some other features that apps can request, but that
561            // have no corresponding permission, so we cannot implement any
562            // back-compatibility heuristic for them. The below are thus unnecessary
563            // (but are retained here for documentary purposes.)
564            //bool specCompassFeature = false;
565            //bool specAccelerometerFeature = false;
566            //bool specProximityFeature = false;
567            //bool specAmbientLightFeature = false;
568            //bool specLiveWallpaperFeature = false;
569
570            int targetSdk = 0;
571            int smallScreen = 1;
572            int normalScreen = 1;
573            int largeScreen = 1;
574            int xlargeScreen = 1;
575            String8 pkg;
576            String8 activityName;
577            String8 activityLabel;
578            String8 activityIcon;
579            String8 receiverName;
580            String8 serviceName;
581            while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
582                if (code == ResXMLTree::END_TAG) {
583                    depth--;
584                    if (depth < 2) {
585                        withinApplication = false;
586                    } else if (depth < 3) {
587                        if (withinActivity && isMainActivity && isLauncherActivity) {
588                            const char *aName = getComponentName(pkg, activityName);
589                            if (aName != NULL) {
590                                printf("launchable activity name='%s'", aName);
591                            }
592                            printf("label='%s' icon='%s'\n",
593                                    activityLabel.string(),
594                                    activityIcon.string());
595                        }
596                        if (!hasIntentFilter) {
597                            hasOtherActivities |= withinActivity;
598                            hasOtherReceivers |= withinReceiver;
599                            hasOtherServices |= withinService;
600                        }
601                        withinActivity = false;
602                        withinService = false;
603                        withinReceiver = false;
604                        hasIntentFilter = false;
605                        isMainActivity = isLauncherActivity = false;
606                    } else if (depth < 4) {
607                        if (withinIntentFilter) {
608                            if (withinActivity) {
609                                hasMainActivity |= actMainActivity;
610                                hasOtherActivities |= !actMainActivity;
611                            } else if (withinReceiver) {
612                                hasWidgetReceivers |= actWidgetReceivers;
613                                hasOtherReceivers |= !actWidgetReceivers;
614                            } else if (withinService) {
615                                hasImeService |= actImeService;
616                                hasWallpaperService |= actWallpaperService;
617                                hasOtherServices |= (!actImeService && !actWallpaperService);
618                            }
619                        }
620                        withinIntentFilter = false;
621                    }
622                    continue;
623                }
624                if (code != ResXMLTree::START_TAG) {
625                    continue;
626                }
627                depth++;
628                String8 tag(tree.getElementName(&len));
629                //printf("Depth %d,  %s\n", depth, tag.string());
630                if (depth == 1) {
631                    if (tag != "manifest") {
632                        fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
633                        goto bail;
634                    }
635                    pkg = getAttribute(tree, NULL, "package", NULL);
636                    printf("package: name='%s' ", pkg.string());
637                    int32_t versionCode = getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
638                    if (error != "") {
639                        fprintf(stderr, "ERROR getting 'android:versionCode' attribute: %s\n", error.string());
640                        goto bail;
641                    }
642                    if (versionCode > 0) {
643                        printf("versionCode='%d' ", versionCode);
644                    } else {
645                        printf("versionCode='' ");
646                    }
647                    String8 versionName = getResolvedAttribute(&res, tree, VERSION_NAME_ATTR, &error);
648                    if (error != "") {
649                        fprintf(stderr, "ERROR getting 'android:versionName' attribute: %s\n", error.string());
650                        goto bail;
651                    }
652                    printf("versionName='%s'\n", versionName.string());
653                } else if (depth == 2) {
654                    withinApplication = false;
655                    if (tag == "application") {
656                        withinApplication = true;
657                        String8 label = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
658                         if (error != "") {
659                             fprintf(stderr, "ERROR getting 'android:label' attribute: %s\n", error.string());
660                             goto bail;
661                        }
662                        printf("application: label='%s' ", label.string());
663                        String8 icon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
664                        if (error != "") {
665                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
666                            goto bail;
667                        }
668                        printf("icon='%s'\n", icon.string());
669                        int32_t testOnly = getIntegerAttribute(tree, TEST_ONLY_ATTR, &error, 0);
670                        if (error != "") {
671                            fprintf(stderr, "ERROR getting 'android:testOnly' attribute: %s\n", error.string());
672                            goto bail;
673                        }
674                        if (testOnly != 0) {
675                            printf("testOnly='%d'\n", testOnly);
676                        }
677                    } else if (tag == "uses-sdk") {
678                        int32_t code = getIntegerAttribute(tree, MIN_SDK_VERSION_ATTR, &error);
679                        if (error != "") {
680                            error = "";
681                            String8 name = getResolvedAttribute(&res, tree, MIN_SDK_VERSION_ATTR, &error);
682                            if (error != "") {
683                                fprintf(stderr, "ERROR getting 'android:minSdkVersion' attribute: %s\n",
684                                        error.string());
685                                goto bail;
686                            }
687                            if (name == "Donut") targetSdk = 4;
688                            printf("sdkVersion:'%s'\n", name.string());
689                        } else if (code != -1) {
690                            targetSdk = code;
691                            printf("sdkVersion:'%d'\n", code);
692                        }
693                        code = getIntegerAttribute(tree, MAX_SDK_VERSION_ATTR, NULL, -1);
694                        if (code != -1) {
695                            printf("maxSdkVersion:'%d'\n", code);
696                        }
697                        code = getIntegerAttribute(tree, TARGET_SDK_VERSION_ATTR, &error);
698                        if (error != "") {
699                            error = "";
700                            String8 name = getResolvedAttribute(&res, tree, TARGET_SDK_VERSION_ATTR, &error);
701                            if (error != "") {
702                                fprintf(stderr, "ERROR getting 'android:targetSdkVersion' attribute: %s\n",
703                                        error.string());
704                                goto bail;
705                            }
706                            if (name == "Donut" && targetSdk < 4) targetSdk = 4;
707                            printf("targetSdkVersion:'%s'\n", name.string());
708                        } else if (code != -1) {
709                            if (targetSdk < code) {
710                                targetSdk = code;
711                            }
712                            printf("targetSdkVersion:'%d'\n", code);
713                        }
714                    } else if (tag == "uses-configuration") {
715                        int32_t reqTouchScreen = getIntegerAttribute(tree,
716                                REQ_TOUCH_SCREEN_ATTR, NULL, 0);
717                        int32_t reqKeyboardType = getIntegerAttribute(tree,
718                                REQ_KEYBOARD_TYPE_ATTR, NULL, 0);
719                        int32_t reqHardKeyboard = getIntegerAttribute(tree,
720                                REQ_HARD_KEYBOARD_ATTR, NULL, 0);
721                        int32_t reqNavigation = getIntegerAttribute(tree,
722                                REQ_NAVIGATION_ATTR, NULL, 0);
723                        int32_t reqFiveWayNav = getIntegerAttribute(tree,
724                                REQ_FIVE_WAY_NAV_ATTR, NULL, 0);
725                        printf("uses-configuration:");
726                        if (reqTouchScreen != 0) {
727                            printf(" reqTouchScreen='%d'", reqTouchScreen);
728                        }
729                        if (reqKeyboardType != 0) {
730                            printf(" reqKeyboardType='%d'", reqKeyboardType);
731                        }
732                        if (reqHardKeyboard != 0) {
733                            printf(" reqHardKeyboard='%d'", reqHardKeyboard);
734                        }
735                        if (reqNavigation != 0) {
736                            printf(" reqNavigation='%d'", reqNavigation);
737                        }
738                        if (reqFiveWayNav != 0) {
739                            printf(" reqFiveWayNav='%d'", reqFiveWayNav);
740                        }
741                        printf("\n");
742                    } else if (tag == "supports-density") {
743                        int32_t dens = getIntegerAttribute(tree, DENSITY_ATTR, &error);
744                        if (error != "") {
745                            fprintf(stderr, "ERROR getting 'android:density' attribute: %s\n",
746                                    error.string());
747                            goto bail;
748                        }
749                        printf("supports-density:'%d'\n", dens);
750                    } else if (tag == "supports-screens") {
751                        smallScreen = getIntegerAttribute(tree,
752                                SMALL_SCREEN_ATTR, NULL, 1);
753                        normalScreen = getIntegerAttribute(tree,
754                                NORMAL_SCREEN_ATTR, NULL, 1);
755                        largeScreen = getIntegerAttribute(tree,
756                                LARGE_SCREEN_ATTR, NULL, 1);
757                        xlargeScreen = getIntegerAttribute(tree,
758                                XLARGE_SCREEN_ATTR, NULL, 1);
759                    } else if (tag == "uses-feature") {
760                        String8 name = getAttribute(tree, NAME_ATTR, &error);
761
762                        if (name != "" && error == "") {
763                            int req = getIntegerAttribute(tree,
764                                    REQUIRED_ATTR, NULL, 1);
765
766                            if (name == "android.hardware.camera") {
767                                specCameraFeature = true;
768                            } else if (name == "android.hardware.camera.autofocus") {
769                                // these have no corresponding permission to check for,
770                                // but should imply the foundational camera permission
771                                reqCameraAutofocusFeature = reqCameraAutofocusFeature || req;
772                                specCameraAutofocusFeature = true;
773                            } else if (req && (name == "android.hardware.camera.flash")) {
774                                // these have no corresponding permission to check for,
775                                // but should imply the foundational camera permission
776                                reqCameraFlashFeature = true;
777                            } else if (name == "android.hardware.location") {
778                                specLocationFeature = true;
779                            } else if (name == "android.hardware.location.network") {
780                                specNetworkLocFeature = true;
781                                reqNetworkLocFeature = reqNetworkLocFeature || req;
782                            } else if (name == "android.hardware.location.gps") {
783                                specGpsFeature = true;
784                                reqGpsFeature = reqGpsFeature || req;
785                            } else if (name == "android.hardware.bluetooth") {
786                                specBluetoothFeature = true;
787                            } else if (name == "android.hardware.touchscreen") {
788                                specTouchscreenFeature = true;
789                            } else if (name == "android.hardware.touchscreen.multitouch") {
790                                specMultitouchFeature = true;
791                            } else if (name == "android.hardware.touchscreen.multitouch.distinct") {
792                                reqDistinctMultitouchFeature = reqDistinctMultitouchFeature || req;
793                            } else if (name == "android.hardware.microphone") {
794                                specMicrophoneFeature = true;
795                            } else if (name == "android.hardware.wifi") {
796                                specWiFiFeature = true;
797                            } else if (name == "android.hardware.telephony") {
798                                specTelephonyFeature = true;
799                            } else if (req && (name == "android.hardware.telephony.gsm" ||
800                                               name == "android.hardware.telephony.cdma")) {
801                                // these have no corresponding permission to check for,
802                                // but should imply the foundational telephony permission
803                                reqTelephonySubFeature = true;
804                            }
805                            printf("uses-feature%s:'%s'\n",
806                                    req ? "" : "-not-required", name.string());
807                        } else {
808                            int vers = getIntegerAttribute(tree,
809                                    GL_ES_VERSION_ATTR, &error);
810                            if (error == "") {
811                                printf("uses-gl-es:'0x%x'\n", vers);
812                            }
813                        }
814                    } else if (tag == "uses-permission") {
815                        String8 name = getAttribute(tree, NAME_ATTR, &error);
816                        if (name != "" && error == "") {
817                            if (name == "android.permission.CAMERA") {
818                                hasCameraPermission = true;
819                            } else if (name == "android.permission.ACCESS_FINE_LOCATION") {
820                                hasGpsPermission = true;
821                            } else if (name == "android.permission.ACCESS_MOCK_LOCATION") {
822                                hasMockLocPermission = true;
823                            } else if (name == "android.permission.ACCESS_COARSE_LOCATION") {
824                                hasCoarseLocPermission = true;
825                            } else if (name == "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" ||
826                                       name == "android.permission.INSTALL_LOCATION_PROVIDER") {
827                                hasGeneralLocPermission = true;
828                            } else if (name == "android.permission.BLUETOOTH" ||
829                                       name == "android.permission.BLUETOOTH_ADMIN") {
830                                hasBluetoothPermission = true;
831                            } else if (name == "android.permission.RECORD_AUDIO") {
832                                hasRecordAudioPermission = true;
833                            } else if (name == "android.permission.ACCESS_WIFI_STATE" ||
834                                       name == "android.permission.CHANGE_WIFI_STATE" ||
835                                       name == "android.permission.CHANGE_WIFI_MULTICAST_STATE") {
836                                hasWiFiPermission = true;
837                            } else if (name == "android.permission.CALL_PHONE" ||
838                                       name == "android.permission.CALL_PRIVILEGED" ||
839                                       name == "android.permission.MODIFY_PHONE_STATE" ||
840                                       name == "android.permission.PROCESS_OUTGOING_CALLS" ||
841                                       name == "android.permission.READ_SMS" ||
842                                       name == "android.permission.RECEIVE_SMS" ||
843                                       name == "android.permission.RECEIVE_MMS" ||
844                                       name == "android.permission.RECEIVE_WAP_PUSH" ||
845                                       name == "android.permission.SEND_SMS" ||
846                                       name == "android.permission.WRITE_APN_SETTINGS" ||
847                                       name == "android.permission.WRITE_SMS") {
848                                hasTelephonyPermission = true;
849                            }
850                            printf("uses-permission:'%s'\n", name.string());
851                        } else {
852                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
853                                    error.string());
854                            goto bail;
855                        }
856                    } else if (tag == "uses-package") {
857                        String8 name = getAttribute(tree, NAME_ATTR, &error);
858                        if (name != "" && error == "") {
859                            printf("uses-package:'%s'\n", name.string());
860                        } else {
861                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
862                                    error.string());
863                                goto bail;
864                        }
865                    } else if (tag == "original-package") {
866                        String8 name = getAttribute(tree, NAME_ATTR, &error);
867                        if (name != "" && error == "") {
868                            printf("original-package:'%s'\n", name.string());
869                        } else {
870                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
871                                    error.string());
872                                goto bail;
873                        }
874                    }
875                } else if (depth == 3 && withinApplication) {
876                    withinActivity = false;
877                    withinReceiver = false;
878                    withinService = false;
879                    hasIntentFilter = false;
880                    if(tag == "activity") {
881                        withinActivity = true;
882                        activityName = getAttribute(tree, NAME_ATTR, &error);
883                        if (error != "") {
884                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
885                            goto bail;
886                        }
887
888                        activityLabel = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
889                        if (error != "") {
890                            fprintf(stderr, "ERROR getting 'android:label' attribute: %s\n", error.string());
891                            goto bail;
892                        }
893
894                        activityIcon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
895                        if (error != "") {
896                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
897                            goto bail;
898                        }
899                    } else if (tag == "uses-library") {
900                        String8 libraryName = getAttribute(tree, NAME_ATTR, &error);
901                        if (error != "") {
902                            fprintf(stderr, "ERROR getting 'android:name' attribute for uses-library: %s\n", error.string());
903                            goto bail;
904                        }
905                        int req = getIntegerAttribute(tree,
906                                REQUIRED_ATTR, NULL, 1);
907                        printf("uses-library%s:'%s'\n",
908                                req ? "" : "-not-required", libraryName.string());
909                    } else if (tag == "receiver") {
910                        withinReceiver = true;
911                        receiverName = getAttribute(tree, NAME_ATTR, &error);
912
913                        if (error != "") {
914                            fprintf(stderr, "ERROR getting 'android:name' attribute for receiver: %s\n", error.string());
915                            goto bail;
916                        }
917                    } else if (tag == "service") {
918                        withinService = true;
919                        serviceName = getAttribute(tree, NAME_ATTR, &error);
920
921                        if (error != "") {
922                            fprintf(stderr, "ERROR getting 'android:name' attribute for service: %s\n", error.string());
923                            goto bail;
924                        }
925                    }
926                } else if ((depth == 4) && (tag == "intent-filter")) {
927                    hasIntentFilter = true;
928                    withinIntentFilter = true;
929                    actMainActivity = actWidgetReceivers = actImeService = actWallpaperService = false;
930                } else if ((depth == 5) && withinIntentFilter){
931                    String8 action;
932                    if (tag == "action") {
933                        action = getAttribute(tree, NAME_ATTR, &error);
934                        if (error != "") {
935                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
936                            goto bail;
937                        }
938                        if (withinActivity) {
939                            if (action == "android.intent.action.MAIN") {
940                                isMainActivity = true;
941                                actMainActivity = true;
942                            }
943                        } else if (withinReceiver) {
944                            if (action == "android.appwidget.action.APPWIDGET_UPDATE") {
945                                actWidgetReceivers = true;
946                            }
947                        } else if (withinService) {
948                            if (action == "android.view.InputMethod") {
949                                actImeService = true;
950                            } else if (action == "android.service.wallpaper.WallpaperService") {
951                                actWallpaperService = true;
952                            }
953                        }
954                        if (action == "android.intent.action.SEARCH") {
955                            isSearchable = true;
956                        }
957                    }
958
959                    if (tag == "category") {
960                        String8 category = getAttribute(tree, NAME_ATTR, &error);
961                        if (error != "") {
962                            fprintf(stderr, "ERROR getting 'name' attribute: %s\n", error.string());
963                            goto bail;
964                        }
965                        if (withinActivity) {
966                            if (category == "android.intent.category.LAUNCHER") {
967                                isLauncherActivity = true;
968                            }
969                        }
970                    }
971                }
972            }
973
974            /* The following blocks handle printing "inferred" uses-features, based
975             * on whether related features or permissions are used by the app.
976             * Note that the various spec*Feature variables denote whether the
977             * relevant tag was *present* in the AndroidManfest, not that it was
978             * present and set to true.
979             */
980            // Camera-related back-compatibility logic
981            if (!specCameraFeature) {
982                if (reqCameraFlashFeature || reqCameraAutofocusFeature) {
983                    // if app requested a sub-feature (autofocus or flash) and didn't
984                    // request the base camera feature, we infer that it meant to
985                    printf("uses-feature:'android.hardware.camera'\n");
986                } else if (hasCameraPermission) {
987                    // if app wants to use camera but didn't request the feature, we infer
988                    // that it meant to, and further that it wants autofocus
989                    // (which was the 1.0 - 1.5 behavior)
990                    printf("uses-feature:'android.hardware.camera'\n");
991                    if (!specCameraAutofocusFeature) {
992                        printf("uses-feature:'android.hardware.camera.autofocus'\n");
993                    }
994                }
995            }
996
997            // Location-related back-compatibility logic
998            if (!specLocationFeature &&
999                (hasMockLocPermission || hasCoarseLocPermission || hasGpsPermission ||
1000                 hasGeneralLocPermission || reqNetworkLocFeature || reqGpsFeature)) {
1001                // if app either takes a location-related permission or requests one of the
1002                // sub-features, we infer that it also meant to request the base location feature
1003                printf("uses-feature:'android.hardware.location'\n");
1004            }
1005            if (!specGpsFeature && hasGpsPermission) {
1006                // if app takes GPS (FINE location) perm but does not request the GPS
1007                // feature, we infer that it meant to
1008                printf("uses-feature:'android.hardware.location.gps'\n");
1009            }
1010            if (!specNetworkLocFeature && hasCoarseLocPermission) {
1011                // if app takes Network location (COARSE location) perm but does not request the
1012                // network location feature, we infer that it meant to
1013                printf("uses-feature:'android.hardware.location.network'\n");
1014            }
1015
1016            // Bluetooth-related compatibility logic
1017            if (!specBluetoothFeature && hasBluetoothPermission && (targetSdk > 4)) {
1018                // if app takes a Bluetooth permission but does not request the Bluetooth
1019                // feature, we infer that it meant to
1020                printf("uses-feature:'android.hardware.bluetooth'\n");
1021            }
1022
1023            // Microphone-related compatibility logic
1024            if (!specMicrophoneFeature && hasRecordAudioPermission) {
1025                // if app takes the record-audio permission but does not request the microphone
1026                // feature, we infer that it meant to
1027                printf("uses-feature:'android.hardware.microphone'\n");
1028            }
1029
1030            // WiFi-related compatibility logic
1031            if (!specWiFiFeature && hasWiFiPermission) {
1032                // if app takes one of the WiFi permissions but does not request the WiFi
1033                // feature, we infer that it meant to
1034                printf("uses-feature:'android.hardware.wifi'\n");
1035            }
1036
1037            // Telephony-related compatibility logic
1038            if (!specTelephonyFeature && (hasTelephonyPermission || reqTelephonySubFeature)) {
1039                // if app takes one of the telephony permissions or requests a sub-feature but
1040                // does not request the base telephony feature, we infer that it meant to
1041                printf("uses-feature:'android.hardware.telephony'\n");
1042            }
1043
1044            // Touchscreen-related back-compatibility logic
1045            if (!specTouchscreenFeature) { // not a typo!
1046                // all apps are presumed to require a touchscreen, unless they explicitly say
1047                // <uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
1048                // Note that specTouchscreenFeature is true if the tag is present, regardless
1049                // of whether its value is true or false, so this is safe
1050                printf("uses-feature:'android.hardware.touchscreen'\n");
1051            }
1052            if (!specMultitouchFeature && reqDistinctMultitouchFeature) {
1053                // if app takes one of the telephony permissions or requests a sub-feature but
1054                // does not request the base telephony feature, we infer that it meant to
1055                printf("uses-feature:'android.hardware.touchscreen.multitouch'\n");
1056            }
1057
1058            if (hasMainActivity) {
1059                printf("main\n");
1060            }
1061            if (hasWidgetReceivers) {
1062                printf("app-widget\n");
1063            }
1064            if (hasImeService) {
1065                printf("ime\n");
1066            }
1067            if (hasWallpaperService) {
1068                printf("wallpaper\n");
1069            }
1070            if (hasOtherActivities) {
1071                printf("other-activities\n");
1072            }
1073            if (isSearchable) {
1074                printf("search\n");
1075            }
1076            if (hasOtherReceivers) {
1077                printf("other-receivers\n");
1078            }
1079            if (hasOtherServices) {
1080                printf("other-services\n");
1081            }
1082
1083            // Determine default values for any unspecified screen sizes,
1084            // based on the target SDK of the package.  As of 4 (donut)
1085            // the screen size support was introduced, so all default to
1086            // enabled.
1087            if (smallScreen > 0) {
1088                smallScreen = targetSdk >= 4 ? -1 : 0;
1089            }
1090            if (normalScreen > 0) {
1091                normalScreen = -1;
1092            }
1093            if (largeScreen > 0) {
1094                largeScreen = targetSdk >= 4 ? -1 : 0;
1095            }
1096            if (xlargeScreen > 0) {
1097                // Introduced in Honeycomb.
1098                xlargeScreen = targetSdk >= 10 ? -1 : 0;
1099            }
1100            printf("supports-screens:");
1101            if (smallScreen != 0) printf(" 'small'");
1102            if (normalScreen != 0) printf(" 'normal'");
1103            if (largeScreen != 0) printf(" 'large'");
1104            if (xlargeScreen != 0) printf(" 'xlarge'");
1105            printf("\n");
1106
1107            printf("locales:");
1108            Vector<String8> locales;
1109            res.getLocales(&locales);
1110            const size_t NL = locales.size();
1111            for (size_t i=0; i<NL; i++) {
1112                const char* localeStr =  locales[i].string();
1113                if (localeStr == NULL || strlen(localeStr) == 0) {
1114                    localeStr = "--_--";
1115                }
1116                printf(" '%s'", localeStr);
1117            }
1118            printf("\n");
1119
1120            Vector<ResTable_config> configs;
1121            res.getConfigurations(&configs);
1122            SortedVector<int> densities;
1123            const size_t NC = configs.size();
1124            for (size_t i=0; i<NC; i++) {
1125                int dens = configs[i].density;
1126                if (dens == 0) dens = 160;
1127                densities.add(dens);
1128            }
1129
1130            printf("densities:");
1131            const size_t ND = densities.size();
1132            for (size_t i=0; i<ND; i++) {
1133                printf(" '%d'", densities[i]);
1134            }
1135            printf("\n");
1136
1137            AssetDir* dir = assets.openNonAssetDir(assetsCookie, "lib");
1138            if (dir != NULL) {
1139                if (dir->getFileCount() > 0) {
1140                    printf("native-code:");
1141                    for (size_t i=0; i<dir->getFileCount(); i++) {
1142                        printf(" '%s'", dir->getFileName(i).string());
1143                    }
1144                    printf("\n");
1145                }
1146                delete dir;
1147            }
1148        } else if (strcmp("configurations", option) == 0) {
1149            Vector<ResTable_config> configs;
1150            res.getConfigurations(&configs);
1151            const size_t N = configs.size();
1152            for (size_t i=0; i<N; i++) {
1153                printf("%s\n", configs[i].toString().string());
1154            }
1155        } else {
1156            fprintf(stderr, "ERROR: unknown dump option '%s'\n", option);
1157            goto bail;
1158        }
1159    }
1160
1161    result = NO_ERROR;
1162
1163bail:
1164    if (asset) {
1165        delete asset;
1166    }
1167    return (result != NO_ERROR);
1168}
1169
1170
1171/*
1172 * Handle the "add" command, which wants to add files to a new or
1173 * pre-existing archive.
1174 */
1175int doAdd(Bundle* bundle)
1176{
1177    ZipFile* zip = NULL;
1178    status_t result = UNKNOWN_ERROR;
1179    const char* zipFileName;
1180
1181    if (bundle->getUpdate()) {
1182        /* avoid confusion */
1183        fprintf(stderr, "ERROR: can't use '-u' with add\n");
1184        goto bail;
1185    }
1186
1187    if (bundle->getFileSpecCount() < 1) {
1188        fprintf(stderr, "ERROR: must specify zip file name\n");
1189        goto bail;
1190    }
1191    zipFileName = bundle->getFileSpecEntry(0);
1192
1193    if (bundle->getFileSpecCount() < 2) {
1194        fprintf(stderr, "NOTE: nothing to do\n");
1195        goto bail;
1196    }
1197
1198    zip = openReadWrite(zipFileName, true);
1199    if (zip == NULL) {
1200        fprintf(stderr, "ERROR: failed opening/creating '%s' as Zip file\n", zipFileName);
1201        goto bail;
1202    }
1203
1204    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
1205        const char* fileName = bundle->getFileSpecEntry(i);
1206
1207        if (strcasecmp(String8(fileName).getPathExtension().string(), ".gz") == 0) {
1208            printf(" '%s'... (from gzip)\n", fileName);
1209            result = zip->addGzip(fileName, String8(fileName).getBasePath().string(), NULL);
1210        } else {
1211            if (bundle->getJunkPath()) {
1212                String8 storageName = String8(fileName).getPathLeaf();
1213                printf(" '%s' as '%s'...\n", fileName, storageName.string());
1214                result = zip->add(fileName, storageName.string(),
1215                                  bundle->getCompressionMethod(), NULL);
1216            } else {
1217                printf(" '%s'...\n", fileName);
1218                result = zip->add(fileName, bundle->getCompressionMethod(), NULL);
1219            }
1220        }
1221        if (result != NO_ERROR) {
1222            fprintf(stderr, "Unable to add '%s' to '%s'", bundle->getFileSpecEntry(i), zipFileName);
1223            if (result == NAME_NOT_FOUND)
1224                fprintf(stderr, ": file not found\n");
1225            else if (result == ALREADY_EXISTS)
1226                fprintf(stderr, ": already exists in archive\n");
1227            else
1228                fprintf(stderr, "\n");
1229            goto bail;
1230        }
1231    }
1232
1233    result = NO_ERROR;
1234
1235bail:
1236    delete zip;
1237    return (result != NO_ERROR);
1238}
1239
1240
1241/*
1242 * Delete files from an existing archive.
1243 */
1244int doRemove(Bundle* bundle)
1245{
1246    ZipFile* zip = NULL;
1247    status_t result = UNKNOWN_ERROR;
1248    const char* zipFileName;
1249
1250    if (bundle->getFileSpecCount() < 1) {
1251        fprintf(stderr, "ERROR: must specify zip file name\n");
1252        goto bail;
1253    }
1254    zipFileName = bundle->getFileSpecEntry(0);
1255
1256    if (bundle->getFileSpecCount() < 2) {
1257        fprintf(stderr, "NOTE: nothing to do\n");
1258        goto bail;
1259    }
1260
1261    zip = openReadWrite(zipFileName, false);
1262    if (zip == NULL) {
1263        fprintf(stderr, "ERROR: failed opening Zip archive '%s'\n",
1264            zipFileName);
1265        goto bail;
1266    }
1267
1268    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
1269        const char* fileName = bundle->getFileSpecEntry(i);
1270        ZipEntry* entry;
1271
1272        entry = zip->getEntryByName(fileName);
1273        if (entry == NULL) {
1274            printf(" '%s' NOT FOUND\n", fileName);
1275            continue;
1276        }
1277
1278        result = zip->remove(entry);
1279
1280        if (result != NO_ERROR) {
1281            fprintf(stderr, "Unable to delete '%s' from '%s'\n",
1282                bundle->getFileSpecEntry(i), zipFileName);
1283            goto bail;
1284        }
1285    }
1286
1287    /* update the archive */
1288    zip->flush();
1289
1290bail:
1291    delete zip;
1292    return (result != NO_ERROR);
1293}
1294
1295
1296/*
1297 * Package up an asset directory and associated application files.
1298 */
1299int doPackage(Bundle* bundle)
1300{
1301    const char* outputAPKFile;
1302    int retVal = 1;
1303    status_t err;
1304    sp<AaptAssets> assets;
1305    int N;
1306
1307    // -c zz_ZZ means do pseudolocalization
1308    ResourceFilter filter;
1309    err = filter.parse(bundle->getConfigurations());
1310    if (err != NO_ERROR) {
1311        goto bail;
1312    }
1313    if (filter.containsPseudo()) {
1314        bundle->setPseudolocalize(true);
1315    }
1316
1317    N = bundle->getFileSpecCount();
1318    if (N < 1 && bundle->getResourceSourceDirs().size() == 0 && bundle->getJarFiles().size() == 0
1319            && bundle->getAndroidManifestFile() == NULL && bundle->getAssetSourceDir() == NULL) {
1320        fprintf(stderr, "ERROR: no input files\n");
1321        goto bail;
1322    }
1323
1324    outputAPKFile = bundle->getOutputAPKFile();
1325
1326    // Make sure the filenames provided exist and are of the appropriate type.
1327    if (outputAPKFile) {
1328        FileType type;
1329        type = getFileType(outputAPKFile);
1330        if (type != kFileTypeNonexistent && type != kFileTypeRegular) {
1331            fprintf(stderr,
1332                "ERROR: output file '%s' exists but is not regular file\n",
1333                outputAPKFile);
1334            goto bail;
1335        }
1336    }
1337
1338    // Load the assets.
1339    assets = new AaptAssets();
1340    err = assets->slurpFromArgs(bundle);
1341    if (err < 0) {
1342        goto bail;
1343    }
1344
1345    if (bundle->getVerbose()) {
1346        assets->print();
1347    }
1348
1349    // If they asked for any files that need to be compiled, do so.
1350    if (bundle->getResourceSourceDirs().size() || bundle->getAndroidManifestFile()) {
1351        err = buildResources(bundle, assets);
1352        if (err != 0) {
1353            goto bail;
1354        }
1355    }
1356
1357    // At this point we've read everything and processed everything.  From here
1358    // on out it's just writing output files.
1359    if (SourcePos::hasErrors()) {
1360        goto bail;
1361    }
1362
1363    // Write out R.java constants
1364    if (assets->getPackage() == assets->getSymbolsPrivatePackage()) {
1365        if (bundle->getCustomPackage() == NULL) {
1366            err = writeResourceSymbols(bundle, assets, assets->getPackage(), true);
1367        } else {
1368            const String8 customPkg(bundle->getCustomPackage());
1369            err = writeResourceSymbols(bundle, assets, customPkg, true);
1370        }
1371        if (err < 0) {
1372            goto bail;
1373        }
1374    } else {
1375        err = writeResourceSymbols(bundle, assets, assets->getPackage(), false);
1376        if (err < 0) {
1377            goto bail;
1378        }
1379        err = writeResourceSymbols(bundle, assets, assets->getSymbolsPrivatePackage(), true);
1380        if (err < 0) {
1381            goto bail;
1382        }
1383    }
1384
1385    // Write out the ProGuard file
1386    err = writeProguardFile(bundle, assets);
1387    if (err < 0) {
1388        goto bail;
1389    }
1390
1391    // Write the apk
1392    if (outputAPKFile) {
1393        err = writeAPK(bundle, assets, String8(outputAPKFile));
1394        if (err != NO_ERROR) {
1395            fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputAPKFile);
1396            goto bail;
1397        }
1398    }
1399
1400    retVal = 0;
1401bail:
1402    if (SourcePos::hasErrors()) {
1403        SourcePos::printErrors(stderr);
1404    }
1405    return retVal;
1406}
1407