Command.cpp revision 6f51fc14d0c3df8f9153ae5df992cc2731f099c8
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                    } else if (tag == "uses-gl-texture") {
875                        String8 name = getAttribute(tree, NAME_ATTR, &error);
876                        if (name != "" && error == "") {
877                            printf("uses-gl-texture:'%s'\n", name.string());
878                        } else {
879                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n",
880                                    error.string());
881                                goto bail;
882                        }
883                    }
884                } else if (depth == 3 && withinApplication) {
885                    withinActivity = false;
886                    withinReceiver = false;
887                    withinService = false;
888                    hasIntentFilter = false;
889                    if(tag == "activity") {
890                        withinActivity = true;
891                        activityName = getAttribute(tree, NAME_ATTR, &error);
892                        if (error != "") {
893                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
894                            goto bail;
895                        }
896
897                        activityLabel = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
898                        if (error != "") {
899                            fprintf(stderr, "ERROR getting 'android:label' attribute: %s\n", error.string());
900                            goto bail;
901                        }
902
903                        activityIcon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
904                        if (error != "") {
905                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
906                            goto bail;
907                        }
908                    } else if (tag == "uses-library") {
909                        String8 libraryName = getAttribute(tree, NAME_ATTR, &error);
910                        if (error != "") {
911                            fprintf(stderr, "ERROR getting 'android:name' attribute for uses-library: %s\n", error.string());
912                            goto bail;
913                        }
914                        int req = getIntegerAttribute(tree,
915                                REQUIRED_ATTR, NULL, 1);
916                        printf("uses-library%s:'%s'\n",
917                                req ? "" : "-not-required", libraryName.string());
918                    } else if (tag == "receiver") {
919                        withinReceiver = true;
920                        receiverName = getAttribute(tree, NAME_ATTR, &error);
921
922                        if (error != "") {
923                            fprintf(stderr, "ERROR getting 'android:name' attribute for receiver: %s\n", error.string());
924                            goto bail;
925                        }
926                    } else if (tag == "service") {
927                        withinService = true;
928                        serviceName = getAttribute(tree, NAME_ATTR, &error);
929
930                        if (error != "") {
931                            fprintf(stderr, "ERROR getting 'android:name' attribute for service: %s\n", error.string());
932                            goto bail;
933                        }
934                    }
935                } else if ((depth == 4) && (tag == "intent-filter")) {
936                    hasIntentFilter = true;
937                    withinIntentFilter = true;
938                    actMainActivity = actWidgetReceivers = actImeService = actWallpaperService = false;
939                } else if ((depth == 5) && withinIntentFilter){
940                    String8 action;
941                    if (tag == "action") {
942                        action = getAttribute(tree, NAME_ATTR, &error);
943                        if (error != "") {
944                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
945                            goto bail;
946                        }
947                        if (withinActivity) {
948                            if (action == "android.intent.action.MAIN") {
949                                isMainActivity = true;
950                                actMainActivity = true;
951                            }
952                        } else if (withinReceiver) {
953                            if (action == "android.appwidget.action.APPWIDGET_UPDATE") {
954                                actWidgetReceivers = true;
955                            }
956                        } else if (withinService) {
957                            if (action == "android.view.InputMethod") {
958                                actImeService = true;
959                            } else if (action == "android.service.wallpaper.WallpaperService") {
960                                actWallpaperService = true;
961                            }
962                        }
963                        if (action == "android.intent.action.SEARCH") {
964                            isSearchable = true;
965                        }
966                    }
967
968                    if (tag == "category") {
969                        String8 category = getAttribute(tree, NAME_ATTR, &error);
970                        if (error != "") {
971                            fprintf(stderr, "ERROR getting 'name' attribute: %s\n", error.string());
972                            goto bail;
973                        }
974                        if (withinActivity) {
975                            if (category == "android.intent.category.LAUNCHER") {
976                                isLauncherActivity = true;
977                            }
978                        }
979                    }
980                }
981            }
982
983            /* The following blocks handle printing "inferred" uses-features, based
984             * on whether related features or permissions are used by the app.
985             * Note that the various spec*Feature variables denote whether the
986             * relevant tag was *present* in the AndroidManfest, not that it was
987             * present and set to true.
988             */
989            // Camera-related back-compatibility logic
990            if (!specCameraFeature) {
991                if (reqCameraFlashFeature || reqCameraAutofocusFeature) {
992                    // if app requested a sub-feature (autofocus or flash) and didn't
993                    // request the base camera feature, we infer that it meant to
994                    printf("uses-feature:'android.hardware.camera'\n");
995                } else if (hasCameraPermission) {
996                    // if app wants to use camera but didn't request the feature, we infer
997                    // that it meant to, and further that it wants autofocus
998                    // (which was the 1.0 - 1.5 behavior)
999                    printf("uses-feature:'android.hardware.camera'\n");
1000                    if (!specCameraAutofocusFeature) {
1001                        printf("uses-feature:'android.hardware.camera.autofocus'\n");
1002                    }
1003                }
1004            }
1005
1006            // Location-related back-compatibility logic
1007            if (!specLocationFeature &&
1008                (hasMockLocPermission || hasCoarseLocPermission || hasGpsPermission ||
1009                 hasGeneralLocPermission || reqNetworkLocFeature || reqGpsFeature)) {
1010                // if app either takes a location-related permission or requests one of the
1011                // sub-features, we infer that it also meant to request the base location feature
1012                printf("uses-feature:'android.hardware.location'\n");
1013            }
1014            if (!specGpsFeature && hasGpsPermission) {
1015                // if app takes GPS (FINE location) perm but does not request the GPS
1016                // feature, we infer that it meant to
1017                printf("uses-feature:'android.hardware.location.gps'\n");
1018            }
1019            if (!specNetworkLocFeature && hasCoarseLocPermission) {
1020                // if app takes Network location (COARSE location) perm but does not request the
1021                // network location feature, we infer that it meant to
1022                printf("uses-feature:'android.hardware.location.network'\n");
1023            }
1024
1025            // Bluetooth-related compatibility logic
1026            if (!specBluetoothFeature && hasBluetoothPermission && (targetSdk > 4)) {
1027                // if app takes a Bluetooth permission but does not request the Bluetooth
1028                // feature, we infer that it meant to
1029                printf("uses-feature:'android.hardware.bluetooth'\n");
1030            }
1031
1032            // Microphone-related compatibility logic
1033            if (!specMicrophoneFeature && hasRecordAudioPermission) {
1034                // if app takes the record-audio permission but does not request the microphone
1035                // feature, we infer that it meant to
1036                printf("uses-feature:'android.hardware.microphone'\n");
1037            }
1038
1039            // WiFi-related compatibility logic
1040            if (!specWiFiFeature && hasWiFiPermission) {
1041                // if app takes one of the WiFi permissions but does not request the WiFi
1042                // feature, we infer that it meant to
1043                printf("uses-feature:'android.hardware.wifi'\n");
1044            }
1045
1046            // Telephony-related compatibility logic
1047            if (!specTelephonyFeature && (hasTelephonyPermission || reqTelephonySubFeature)) {
1048                // if app takes one of the telephony permissions or requests a sub-feature but
1049                // does not request the base telephony feature, we infer that it meant to
1050                printf("uses-feature:'android.hardware.telephony'\n");
1051            }
1052
1053            // Touchscreen-related back-compatibility logic
1054            if (!specTouchscreenFeature) { // not a typo!
1055                // all apps are presumed to require a touchscreen, unless they explicitly say
1056                // <uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
1057                // Note that specTouchscreenFeature is true if the tag is present, regardless
1058                // of whether its value is true or false, so this is safe
1059                printf("uses-feature:'android.hardware.touchscreen'\n");
1060            }
1061            if (!specMultitouchFeature && reqDistinctMultitouchFeature) {
1062                // if app takes one of the telephony permissions or requests a sub-feature but
1063                // does not request the base telephony feature, we infer that it meant to
1064                printf("uses-feature:'android.hardware.touchscreen.multitouch'\n");
1065            }
1066
1067            if (hasMainActivity) {
1068                printf("main\n");
1069            }
1070            if (hasWidgetReceivers) {
1071                printf("app-widget\n");
1072            }
1073            if (hasImeService) {
1074                printf("ime\n");
1075            }
1076            if (hasWallpaperService) {
1077                printf("wallpaper\n");
1078            }
1079            if (hasOtherActivities) {
1080                printf("other-activities\n");
1081            }
1082            if (isSearchable) {
1083                printf("search\n");
1084            }
1085            if (hasOtherReceivers) {
1086                printf("other-receivers\n");
1087            }
1088            if (hasOtherServices) {
1089                printf("other-services\n");
1090            }
1091
1092            // Determine default values for any unspecified screen sizes,
1093            // based on the target SDK of the package.  As of 4 (donut)
1094            // the screen size support was introduced, so all default to
1095            // enabled.
1096            if (smallScreen > 0) {
1097                smallScreen = targetSdk >= 4 ? -1 : 0;
1098            }
1099            if (normalScreen > 0) {
1100                normalScreen = -1;
1101            }
1102            if (largeScreen > 0) {
1103                largeScreen = targetSdk >= 4 ? -1 : 0;
1104            }
1105            if (xlargeScreen > 0) {
1106                // Introduced in Honeycomb.
1107                xlargeScreen = targetSdk >= 10 ? -1 : 0;
1108            }
1109            printf("supports-screens:");
1110            if (smallScreen != 0) printf(" 'small'");
1111            if (normalScreen != 0) printf(" 'normal'");
1112            if (largeScreen != 0) printf(" 'large'");
1113            if (xlargeScreen != 0) printf(" 'xlarge'");
1114            printf("\n");
1115
1116            printf("locales:");
1117            Vector<String8> locales;
1118            res.getLocales(&locales);
1119            const size_t NL = locales.size();
1120            for (size_t i=0; i<NL; i++) {
1121                const char* localeStr =  locales[i].string();
1122                if (localeStr == NULL || strlen(localeStr) == 0) {
1123                    localeStr = "--_--";
1124                }
1125                printf(" '%s'", localeStr);
1126            }
1127            printf("\n");
1128
1129            Vector<ResTable_config> configs;
1130            res.getConfigurations(&configs);
1131            SortedVector<int> densities;
1132            const size_t NC = configs.size();
1133            for (size_t i=0; i<NC; i++) {
1134                int dens = configs[i].density;
1135                if (dens == 0) dens = 160;
1136                densities.add(dens);
1137            }
1138
1139            printf("densities:");
1140            const size_t ND = densities.size();
1141            for (size_t i=0; i<ND; i++) {
1142                printf(" '%d'", densities[i]);
1143            }
1144            printf("\n");
1145
1146            AssetDir* dir = assets.openNonAssetDir(assetsCookie, "lib");
1147            if (dir != NULL) {
1148                if (dir->getFileCount() > 0) {
1149                    printf("native-code:");
1150                    for (size_t i=0; i<dir->getFileCount(); i++) {
1151                        printf(" '%s'", dir->getFileName(i).string());
1152                    }
1153                    printf("\n");
1154                }
1155                delete dir;
1156            }
1157        } else if (strcmp("configurations", option) == 0) {
1158            Vector<ResTable_config> configs;
1159            res.getConfigurations(&configs);
1160            const size_t N = configs.size();
1161            for (size_t i=0; i<N; i++) {
1162                printf("%s\n", configs[i].toString().string());
1163            }
1164        } else {
1165            fprintf(stderr, "ERROR: unknown dump option '%s'\n", option);
1166            goto bail;
1167        }
1168    }
1169
1170    result = NO_ERROR;
1171
1172bail:
1173    if (asset) {
1174        delete asset;
1175    }
1176    return (result != NO_ERROR);
1177}
1178
1179
1180/*
1181 * Handle the "add" command, which wants to add files to a new or
1182 * pre-existing archive.
1183 */
1184int doAdd(Bundle* bundle)
1185{
1186    ZipFile* zip = NULL;
1187    status_t result = UNKNOWN_ERROR;
1188    const char* zipFileName;
1189
1190    if (bundle->getUpdate()) {
1191        /* avoid confusion */
1192        fprintf(stderr, "ERROR: can't use '-u' with add\n");
1193        goto bail;
1194    }
1195
1196    if (bundle->getFileSpecCount() < 1) {
1197        fprintf(stderr, "ERROR: must specify zip file name\n");
1198        goto bail;
1199    }
1200    zipFileName = bundle->getFileSpecEntry(0);
1201
1202    if (bundle->getFileSpecCount() < 2) {
1203        fprintf(stderr, "NOTE: nothing to do\n");
1204        goto bail;
1205    }
1206
1207    zip = openReadWrite(zipFileName, true);
1208    if (zip == NULL) {
1209        fprintf(stderr, "ERROR: failed opening/creating '%s' as Zip file\n", zipFileName);
1210        goto bail;
1211    }
1212
1213    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
1214        const char* fileName = bundle->getFileSpecEntry(i);
1215
1216        if (strcasecmp(String8(fileName).getPathExtension().string(), ".gz") == 0) {
1217            printf(" '%s'... (from gzip)\n", fileName);
1218            result = zip->addGzip(fileName, String8(fileName).getBasePath().string(), NULL);
1219        } else {
1220            if (bundle->getJunkPath()) {
1221                String8 storageName = String8(fileName).getPathLeaf();
1222                printf(" '%s' as '%s'...\n", fileName, storageName.string());
1223                result = zip->add(fileName, storageName.string(),
1224                                  bundle->getCompressionMethod(), NULL);
1225            } else {
1226                printf(" '%s'...\n", fileName);
1227                result = zip->add(fileName, bundle->getCompressionMethod(), NULL);
1228            }
1229        }
1230        if (result != NO_ERROR) {
1231            fprintf(stderr, "Unable to add '%s' to '%s'", bundle->getFileSpecEntry(i), zipFileName);
1232            if (result == NAME_NOT_FOUND)
1233                fprintf(stderr, ": file not found\n");
1234            else if (result == ALREADY_EXISTS)
1235                fprintf(stderr, ": already exists in archive\n");
1236            else
1237                fprintf(stderr, "\n");
1238            goto bail;
1239        }
1240    }
1241
1242    result = NO_ERROR;
1243
1244bail:
1245    delete zip;
1246    return (result != NO_ERROR);
1247}
1248
1249
1250/*
1251 * Delete files from an existing archive.
1252 */
1253int doRemove(Bundle* bundle)
1254{
1255    ZipFile* zip = NULL;
1256    status_t result = UNKNOWN_ERROR;
1257    const char* zipFileName;
1258
1259    if (bundle->getFileSpecCount() < 1) {
1260        fprintf(stderr, "ERROR: must specify zip file name\n");
1261        goto bail;
1262    }
1263    zipFileName = bundle->getFileSpecEntry(0);
1264
1265    if (bundle->getFileSpecCount() < 2) {
1266        fprintf(stderr, "NOTE: nothing to do\n");
1267        goto bail;
1268    }
1269
1270    zip = openReadWrite(zipFileName, false);
1271    if (zip == NULL) {
1272        fprintf(stderr, "ERROR: failed opening Zip archive '%s'\n",
1273            zipFileName);
1274        goto bail;
1275    }
1276
1277    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
1278        const char* fileName = bundle->getFileSpecEntry(i);
1279        ZipEntry* entry;
1280
1281        entry = zip->getEntryByName(fileName);
1282        if (entry == NULL) {
1283            printf(" '%s' NOT FOUND\n", fileName);
1284            continue;
1285        }
1286
1287        result = zip->remove(entry);
1288
1289        if (result != NO_ERROR) {
1290            fprintf(stderr, "Unable to delete '%s' from '%s'\n",
1291                bundle->getFileSpecEntry(i), zipFileName);
1292            goto bail;
1293        }
1294    }
1295
1296    /* update the archive */
1297    zip->flush();
1298
1299bail:
1300    delete zip;
1301    return (result != NO_ERROR);
1302}
1303
1304
1305/*
1306 * Package up an asset directory and associated application files.
1307 */
1308int doPackage(Bundle* bundle)
1309{
1310    const char* outputAPKFile;
1311    int retVal = 1;
1312    status_t err;
1313    sp<AaptAssets> assets;
1314    int N;
1315
1316    // -c zz_ZZ means do pseudolocalization
1317    ResourceFilter filter;
1318    err = filter.parse(bundle->getConfigurations());
1319    if (err != NO_ERROR) {
1320        goto bail;
1321    }
1322    if (filter.containsPseudo()) {
1323        bundle->setPseudolocalize(true);
1324    }
1325
1326    N = bundle->getFileSpecCount();
1327    if (N < 1 && bundle->getResourceSourceDirs().size() == 0 && bundle->getJarFiles().size() == 0
1328            && bundle->getAndroidManifestFile() == NULL && bundle->getAssetSourceDir() == NULL) {
1329        fprintf(stderr, "ERROR: no input files\n");
1330        goto bail;
1331    }
1332
1333    outputAPKFile = bundle->getOutputAPKFile();
1334
1335    // Make sure the filenames provided exist and are of the appropriate type.
1336    if (outputAPKFile) {
1337        FileType type;
1338        type = getFileType(outputAPKFile);
1339        if (type != kFileTypeNonexistent && type != kFileTypeRegular) {
1340            fprintf(stderr,
1341                "ERROR: output file '%s' exists but is not regular file\n",
1342                outputAPKFile);
1343            goto bail;
1344        }
1345    }
1346
1347    // Load the assets.
1348    assets = new AaptAssets();
1349    err = assets->slurpFromArgs(bundle);
1350    if (err < 0) {
1351        goto bail;
1352    }
1353
1354    if (bundle->getVerbose()) {
1355        assets->print();
1356    }
1357
1358    // If they asked for any files that need to be compiled, do so.
1359    if (bundle->getResourceSourceDirs().size() || bundle->getAndroidManifestFile()) {
1360        err = buildResources(bundle, assets);
1361        if (err != 0) {
1362            goto bail;
1363        }
1364    }
1365
1366    // At this point we've read everything and processed everything.  From here
1367    // on out it's just writing output files.
1368    if (SourcePos::hasErrors()) {
1369        goto bail;
1370    }
1371
1372    // Write out R.java constants
1373    if (assets->getPackage() == assets->getSymbolsPrivatePackage()) {
1374        if (bundle->getCustomPackage() == NULL) {
1375            err = writeResourceSymbols(bundle, assets, assets->getPackage(), true);
1376        } else {
1377            const String8 customPkg(bundle->getCustomPackage());
1378            err = writeResourceSymbols(bundle, assets, customPkg, true);
1379        }
1380        if (err < 0) {
1381            goto bail;
1382        }
1383    } else {
1384        err = writeResourceSymbols(bundle, assets, assets->getPackage(), false);
1385        if (err < 0) {
1386            goto bail;
1387        }
1388        err = writeResourceSymbols(bundle, assets, assets->getSymbolsPrivatePackage(), true);
1389        if (err < 0) {
1390            goto bail;
1391        }
1392    }
1393
1394    // Write out the ProGuard file
1395    err = writeProguardFile(bundle, assets);
1396    if (err < 0) {
1397        goto bail;
1398    }
1399
1400    // Write the apk
1401    if (outputAPKFile) {
1402        err = writeAPK(bundle, assets, String8(outputAPKFile));
1403        if (err != NO_ERROR) {
1404            fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputAPKFile);
1405            goto bail;
1406        }
1407    }
1408
1409    retVal = 0;
1410bail:
1411    if (SourcePos::hasErrors()) {
1412        SourcePos::printErrors(stderr);
1413    }
1414    return retVal;
1415}
1416