Command.cpp revision 55e3d60da5626752ffe1d15150d35ccb8fa644e7
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   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%%  %s  %08lx  %s\n",
163                (long) entry->getUncompressedLen(),
164                compressionName(entry->getCompressionMethod()),
165                (long) entry->getCompressedLen(),
166                calcPercent(entry->getUncompressedLen(),
167                            entry->getCompressedLen()),
168                dateBuf,
169                entry->getCRC32(),
170                entry->getFileName());
171        } else {
172            printf("%s\n", entry->getFileName());
173        }
174
175        totalUncLen += entry->getUncompressedLen();
176        totalCompLen += entry->getCompressedLen();
177    }
178
179    if (bundle->getVerbose()) {
180        printf(
181        "--------          -------  ---                            -------\n");
182        printf("%8ld          %7ld  %2d%%                            %d files\n",
183            totalUncLen,
184            totalCompLen,
185            calcPercent(totalUncLen, totalCompLen),
186            zip->getNumEntries());
187    }
188
189    if (bundle->getAndroidList()) {
190        AssetManager assets;
191        if (!assets.addAssetPath(String8(zipFileName), NULL)) {
192            fprintf(stderr, "ERROR: list -a failed because assets could not be loaded\n");
193            goto bail;
194        }
195
196        const ResTable& res = assets.getResources(false);
197        if (&res == NULL) {
198            printf("\nNo resource table found.\n");
199        } else {
200            printf("\nResource table:\n");
201            res.print();
202        }
203
204        Asset* manifestAsset = assets.openNonAsset("AndroidManifest.xml",
205                                                   Asset::ACCESS_BUFFER);
206        if (manifestAsset == NULL) {
207            printf("\nNo AndroidManifest.xml found.\n");
208        } else {
209            printf("\nAndroid manifest:\n");
210            ResXMLTree tree;
211            tree.setTo(manifestAsset->getBuffer(true),
212                       manifestAsset->getLength());
213            printXMLBlock(&tree);
214        }
215        delete manifestAsset;
216    }
217
218    result = 0;
219
220bail:
221    delete zip;
222    return result;
223}
224
225static ssize_t indexOfAttribute(const ResXMLTree& tree, uint32_t attrRes)
226{
227    size_t N = tree.getAttributeCount();
228    for (size_t i=0; i<N; i++) {
229        if (tree.getAttributeNameResID(i) == attrRes) {
230            return (ssize_t)i;
231        }
232    }
233    return -1;
234}
235
236static String8 getAttribute(const ResXMLTree& tree, const char* ns,
237                            const char* attr, String8* outError)
238{
239    ssize_t idx = tree.indexOfAttribute(ns, attr);
240    if (idx < 0) {
241        return String8();
242    }
243    Res_value value;
244    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
245        if (value.dataType != Res_value::TYPE_STRING) {
246            if (outError != NULL) *outError = "attribute is not a string value";
247            return String8();
248        }
249    }
250    size_t len;
251    const uint16_t* str = tree.getAttributeStringValue(idx, &len);
252    return str ? String8(str, len) : String8();
253}
254
255static String8 getAttribute(const ResXMLTree& tree, uint32_t attrRes, String8* outError)
256{
257    ssize_t idx = indexOfAttribute(tree, attrRes);
258    if (idx < 0) {
259        return String8();
260    }
261    Res_value value;
262    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
263        if (value.dataType != Res_value::TYPE_STRING) {
264            if (outError != NULL) *outError = "attribute is not a string value";
265            return String8();
266        }
267    }
268    size_t len;
269    const uint16_t* str = tree.getAttributeStringValue(idx, &len);
270    return str ? String8(str, len) : String8();
271}
272
273static int32_t getIntegerAttribute(const ResXMLTree& tree, uint32_t attrRes,
274        String8* outError, int32_t defValue = -1)
275{
276    ssize_t idx = indexOfAttribute(tree, attrRes);
277    if (idx < 0) {
278        return defValue;
279    }
280    Res_value value;
281    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
282        if (value.dataType < Res_value::TYPE_FIRST_INT
283                || value.dataType > Res_value::TYPE_LAST_INT) {
284            if (outError != NULL) *outError = "attribute is not an integer value";
285            return defValue;
286        }
287    }
288    return value.data;
289}
290
291static String8 getResolvedAttribute(const ResTable* resTable, const ResXMLTree& tree,
292        uint32_t attrRes, String8* outError)
293{
294    ssize_t idx = indexOfAttribute(tree, attrRes);
295    if (idx < 0) {
296        return String8();
297    }
298    Res_value value;
299    if (tree.getAttributeValue(idx, &value) != NO_ERROR) {
300        if (value.dataType == Res_value::TYPE_STRING) {
301            size_t len;
302            const uint16_t* str = tree.getAttributeStringValue(idx, &len);
303            return str ? String8(str, len) : String8();
304        }
305        resTable->resolveReference(&value, 0);
306        if (value.dataType != Res_value::TYPE_STRING) {
307            if (outError != NULL) *outError = "attribute is not a string value";
308            return String8();
309        }
310    }
311    size_t len;
312    const Res_value* value2 = &value;
313    const char16_t* str = const_cast<ResTable*>(resTable)->valueToString(value2, 0, NULL, &len);
314    return str ? String8(str, len) : String8();
315}
316
317// These are attribute resource constants for the platform, as found
318// in android.R.attr
319enum {
320    NAME_ATTR = 0x01010003,
321    VERSION_CODE_ATTR = 0x0101021b,
322    VERSION_NAME_ATTR = 0x0101021c,
323    LABEL_ATTR = 0x01010001,
324    ICON_ATTR = 0x01010002,
325    MIN_SDK_VERSION_ATTR = 0x0101020c,
326    REQ_TOUCH_SCREEN_ATTR = 0x01010227,
327    REQ_KEYBOARD_TYPE_ATTR = 0x01010228,
328    REQ_HARD_KEYBOARD_ATTR = 0x01010229,
329    REQ_NAVIGATION_ATTR = 0x0101022a,
330    REQ_FIVE_WAY_NAV_ATTR = 0x01010232,
331    TARGET_SDK_VERSION_ATTR = 0x01010270,
332    TEST_ONLY_ATTR = 0x01010272,
333    DENSITY_ATTR = 0x0101026c,
334};
335
336const char *getComponentName(String8 &pkgName, String8 &componentName) {
337    ssize_t idx = componentName.find(".");
338    String8 retStr(pkgName);
339    if (idx == 0) {
340        retStr += componentName;
341    } else if (idx < 0) {
342        retStr += ".";
343        retStr += componentName;
344    } else {
345        return componentName.string();
346    }
347    return retStr.string();
348}
349
350/*
351 * Handle the "dump" command, to extract select data from an archive.
352 */
353int doDump(Bundle* bundle)
354{
355    status_t result = UNKNOWN_ERROR;
356    Asset* asset = NULL;
357
358    if (bundle->getFileSpecCount() < 1) {
359        fprintf(stderr, "ERROR: no dump option specified\n");
360        return 1;
361    }
362
363    if (bundle->getFileSpecCount() < 2) {
364        fprintf(stderr, "ERROR: no dump file specified\n");
365        return 1;
366    }
367
368    const char* option = bundle->getFileSpecEntry(0);
369    const char* filename = bundle->getFileSpecEntry(1);
370
371    AssetManager assets;
372    void* assetsCookie;
373    if (!assets.addAssetPath(String8(filename), &assetsCookie)) {
374        fprintf(stderr, "ERROR: dump failed because assets could not be loaded\n");
375        return 1;
376    }
377
378    const ResTable& res = assets.getResources(false);
379    if (&res == NULL) {
380        fprintf(stderr, "ERROR: dump failed because no resource table was found\n");
381        goto bail;
382    }
383
384    if (strcmp("resources", option) == 0) {
385        res.print();
386
387    } else if (strcmp("xmltree", option) == 0) {
388        if (bundle->getFileSpecCount() < 3) {
389            fprintf(stderr, "ERROR: no dump xmltree resource file specified\n");
390            goto bail;
391        }
392
393        for (int i=2; i<bundle->getFileSpecCount(); i++) {
394            const char* resname = bundle->getFileSpecEntry(i);
395            ResXMLTree tree;
396            asset = assets.openNonAsset(resname, Asset::ACCESS_BUFFER);
397            if (asset == NULL) {
398                fprintf(stderr, "ERROR: dump failed because resource %p found\n", resname);
399                goto bail;
400            }
401
402            if (tree.setTo(asset->getBuffer(true),
403                           asset->getLength()) != NO_ERROR) {
404                fprintf(stderr, "ERROR: Resource %s is corrupt\n", resname);
405                goto bail;
406            }
407            tree.restart();
408            printXMLBlock(&tree);
409            delete asset;
410            asset = NULL;
411        }
412
413    } else if (strcmp("xmlstrings", option) == 0) {
414        if (bundle->getFileSpecCount() < 3) {
415            fprintf(stderr, "ERROR: no dump xmltree resource file specified\n");
416            goto bail;
417        }
418
419        for (int i=2; i<bundle->getFileSpecCount(); i++) {
420            const char* resname = bundle->getFileSpecEntry(i);
421            ResXMLTree tree;
422            asset = assets.openNonAsset(resname, Asset::ACCESS_BUFFER);
423            if (asset == NULL) {
424                fprintf(stderr, "ERROR: dump failed because resource %p found\n", resname);
425                goto bail;
426            }
427
428            if (tree.setTo(asset->getBuffer(true),
429                           asset->getLength()) != NO_ERROR) {
430                fprintf(stderr, "ERROR: Resource %s is corrupt\n", resname);
431                goto bail;
432            }
433            printStringPool(&tree.getStrings());
434            delete asset;
435            asset = NULL;
436        }
437
438    } else {
439        ResXMLTree tree;
440        asset = assets.openNonAsset("AndroidManifest.xml",
441                                            Asset::ACCESS_BUFFER);
442        if (asset == NULL) {
443            fprintf(stderr, "ERROR: dump failed because no AndroidManifest.xml found\n");
444            goto bail;
445        }
446
447        if (tree.setTo(asset->getBuffer(true),
448                       asset->getLength()) != NO_ERROR) {
449            fprintf(stderr, "ERROR: AndroidManifest.xml is corrupt\n");
450            goto bail;
451        }
452        tree.restart();
453
454        if (strcmp("permissions", option) == 0) {
455            size_t len;
456            ResXMLTree::event_code_t code;
457            int depth = 0;
458            while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
459                if (code == ResXMLTree::END_TAG) {
460                    depth--;
461                    continue;
462                }
463                if (code != ResXMLTree::START_TAG) {
464                    continue;
465                }
466                depth++;
467                String8 tag(tree.getElementName(&len));
468                //printf("Depth %d tag %s\n", depth, tag.string());
469                if (depth == 1) {
470                    if (tag != "manifest") {
471                        fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
472                        goto bail;
473                    }
474                    String8 pkg = getAttribute(tree, NULL, "package", NULL);
475                    printf("package: %s\n", pkg.string());
476                } else if (depth == 2 && tag == "permission") {
477                    String8 error;
478                    String8 name = getAttribute(tree, NAME_ATTR, &error);
479                    if (error != "") {
480                        fprintf(stderr, "ERROR: %s\n", error.string());
481                        goto bail;
482                    }
483                    printf("permission: %s\n", name.string());
484                } else if (depth == 2 && tag == "uses-permission") {
485                    String8 error;
486                    String8 name = getAttribute(tree, NAME_ATTR, &error);
487                    if (error != "") {
488                        fprintf(stderr, "ERROR: %s\n", error.string());
489                        goto bail;
490                    }
491                    printf("uses-permission: %s\n", name.string());
492                }
493            }
494        } else if (strcmp("badging", option) == 0) {
495            size_t len;
496            ResXMLTree::event_code_t code;
497            int depth = 0;
498            String8 error;
499            bool withinActivity = false;
500            bool isMainActivity = false;
501            bool isLauncherActivity = false;
502            bool withinApplication = false;
503            bool withinReceiver = false;
504            String8 pkg;
505            String8 activityName;
506            String8 activityLabel;
507            String8 activityIcon;
508            String8 receiverName;
509            while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
510                if (code == ResXMLTree::END_TAG) {
511                    depth--;
512                    continue;
513                }
514                if (code != ResXMLTree::START_TAG) {
515                    continue;
516                }
517                depth++;
518                String8 tag(tree.getElementName(&len));
519                //printf("Depth %d tag %s\n", depth, tag.string());
520                if (depth == 1) {
521                    if (tag != "manifest") {
522                        fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
523                        goto bail;
524                    }
525                    pkg = getAttribute(tree, NULL, "package", NULL);
526                    printf("package: name='%s' ", pkg.string());
527                    int32_t versionCode = getIntegerAttribute(tree, VERSION_CODE_ATTR, &error);
528                    if (error != "") {
529                        fprintf(stderr, "ERROR getting 'android:versionCode' attribute: %s\n", error.string());
530                        goto bail;
531                    }
532                    if (versionCode > 0) {
533                        printf("versionCode='%d' ", versionCode);
534                    } else {
535                        printf("versionCode='' ");
536                    }
537                    String8 versionName = getAttribute(tree, VERSION_NAME_ATTR, &error);
538                    if (error != "") {
539                        fprintf(stderr, "ERROR getting 'android:versionName' attribute: %s\n", error.string());
540                        goto bail;
541                    }
542                    printf("versionName='%s'\n", versionName.string());
543                } else if (depth == 2) {
544                    withinApplication = false;
545                    if (tag == "application") {
546                        withinApplication = true;
547                        String8 label = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
548                         if (error != "") {
549                             fprintf(stderr, "ERROR getting 'android:label' attribute: %s\n", error.string());
550                             goto bail;
551                        }
552                        printf("application: label='%s' ", label.string());
553                        String8 icon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
554                        if (error != "") {
555                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
556                            goto bail;
557                        }
558                        printf("icon='%s'\n", icon.string());
559                        int32_t testOnly = getIntegerAttribute(tree, TEST_ONLY_ATTR, &error, 0);
560                        if (error != "") {
561                            fprintf(stderr, "ERROR getting 'android:testOnly' attribute: %s\n", error.string());
562                            goto bail;
563                        }
564                        if (testOnly != 0) {
565                            printf("testOnly='%d'\n", testOnly);
566                        }
567                    } else if (tag == "uses-sdk") {
568                        int32_t code = getIntegerAttribute(tree, MIN_SDK_VERSION_ATTR, &error);
569                        if (error != "") {
570                            error = "";
571                            String8 name = getResolvedAttribute(&res, tree, MIN_SDK_VERSION_ATTR, &error);
572                            if (error != "") {
573                                fprintf(stderr, "ERROR getting 'android:minSdkVersion' attribute: %s\n",
574                                        error.string());
575                                goto bail;
576                            }
577                            printf("sdkVersion:'%s'\n", name.string());
578                        } else if (code != -1) {
579                            printf("sdkVersion:'%d'\n", code);
580                        }
581                        code = getIntegerAttribute(tree, TARGET_SDK_VERSION_ATTR, &error);
582                        if (error != "") {
583                            error = "";
584                            String8 name = getResolvedAttribute(&res, tree, TARGET_SDK_VERSION_ATTR, &error);
585                            if (error != "") {
586                                fprintf(stderr, "ERROR getting 'android:targetSdkVersion' attribute: %s\n",
587                                        error.string());
588                                goto bail;
589                            }
590                            printf("targetSdkVersion:'%s'\n", name.string());
591                        } else if (code != -1) {
592                            printf("targetSdkVersion:'%d'\n", code);
593                        }
594                    } else if (tag == "uses-configuration") {
595                        int32_t reqTouchScreen = getIntegerAttribute(tree,
596                                REQ_TOUCH_SCREEN_ATTR, NULL, 0);
597                        int32_t reqKeyboardType = getIntegerAttribute(tree,
598                                REQ_KEYBOARD_TYPE_ATTR, NULL, 0);
599                        int32_t reqHardKeyboard = getIntegerAttribute(tree,
600                                REQ_HARD_KEYBOARD_ATTR, NULL, 0);
601                        int32_t reqNavigation = getIntegerAttribute(tree,
602                                REQ_NAVIGATION_ATTR, NULL, 0);
603                        int32_t reqFiveWayNav = getIntegerAttribute(tree,
604                                REQ_FIVE_WAY_NAV_ATTR, NULL, 0);
605                        printf("uses-configuation:");
606                        if (reqTouchScreen != 0) {
607                            printf(" reqTouchScreen='%d'", reqTouchScreen);
608                        }
609                        if (reqKeyboardType != 0) {
610                            printf(" reqKeyboardType='%d'", reqKeyboardType);
611                        }
612                        if (reqHardKeyboard != 0) {
613                            printf(" reqHardKeyboard='%d'", reqHardKeyboard);
614                        }
615                        if (reqNavigation != 0) {
616                            printf(" reqNavigation='%d'", reqNavigation);
617                        }
618                        if (reqFiveWayNav != 0) {
619                            printf(" reqFiveWayNav='%d'", reqFiveWayNav);
620                        }
621                        printf("\n");
622                    } else if (tag == "supports-density") {
623                        int32_t dens = getIntegerAttribute(tree, DENSITY_ATTR, &error);
624                        if (error != "") {
625                            fprintf(stderr, "ERROR getting 'android:density' attribute: %s\n",
626                                    error.string());
627                            goto bail;
628                        }
629                        printf("supports-density:'%d'\n", dens);
630                    }
631                } else if (depth == 3 && withinApplication) {
632                    withinActivity = false;
633                    withinReceiver = false;
634                    if(tag == "activity") {
635                        withinActivity = true;
636                        activityName = getAttribute(tree, NAME_ATTR, &error);
637                        if (error != "") {
638                            fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
639                            goto bail;
640                        }
641
642                        activityLabel = getResolvedAttribute(&res, tree, LABEL_ATTR, &error);
643                        if (error != "") {
644                            fprintf(stderr, "ERROR getting 'android:label' attribute: %s\n", error.string());
645                            goto bail;
646                        }
647
648                        activityIcon = getResolvedAttribute(&res, tree, ICON_ATTR, &error);
649                        if (error != "") {
650                            fprintf(stderr, "ERROR getting 'android:icon' attribute: %s\n", error.string());
651                            goto bail;
652                        }
653                    } else if (tag == "uses-library") {
654                        String8 libraryName = getAttribute(tree, NAME_ATTR, &error);
655                        if (error != "") {
656                            fprintf(stderr, "ERROR getting 'android:name' attribute for uses-library: %s\n", error.string());
657                            goto bail;
658                        }
659                        printf("uses-library:'%s'\n", libraryName.string());
660                    } else if (tag == "receiver") {
661                        withinReceiver = true;
662                        receiverName = getAttribute(tree, NAME_ATTR, &error);
663
664                        if (error != "") {
665                            fprintf(stderr, "ERROR getting 'android:name' attribute for receiver: %s\n", error.string());
666                            goto bail;
667                        }
668                    }
669                } else if (depth == 5) {
670                    if (withinActivity) {
671                        if (tag == "action") {
672                            //printf("LOG: action tag\n");
673                            String8 action = getAttribute(tree, NAME_ATTR, &error);
674                            if (error != "") {
675                                fprintf(stderr, "ERROR getting 'android:name' attribute: %s\n", error.string());
676                                goto bail;
677                            }
678                            if (action == "android.intent.action.MAIN") {
679                                isMainActivity = true;
680                                //printf("LOG: isMainActivity==true\n");
681                            }
682                        } else if (tag == "category") {
683                            String8 category = getAttribute(tree, NAME_ATTR, &error);
684                            if (error != "") {
685                                fprintf(stderr, "ERROR getting 'name' attribute: %s\n", error.string());
686                                goto bail;
687                            }
688                            if (category == "android.intent.category.LAUNCHER") {
689                                isLauncherActivity = true;
690                                //printf("LOG: isLauncherActivity==true\n");
691                            }
692                        }
693                    } else if (withinReceiver) {
694                        if (tag == "action") {
695                            String8 action = getAttribute(tree, NAME_ATTR, &error);
696                            if (error != "") {
697                                fprintf(stderr, "ERROR getting 'android:name' attribute for receiver: %s\n", error.string());
698                                goto bail;
699                            }
700                            if (action == "android.appwidget.action.APPWIDGET_UPDATE") {
701                                const char *rName = getComponentName(pkg, receiverName);
702                                if (rName != NULL) {
703                                    printf("gadget-receiver:'%s/%s'\n", pkg.string(), rName);
704                                }
705                            }
706                        }
707                    }
708                }
709
710                if (depth < 2) {
711                    withinApplication = false;
712                }
713                if (depth < 3) {
714                    //if (withinActivity) printf("LOG: withinActivity==false\n");
715                    withinActivity = false;
716                    withinReceiver = false;
717                }
718
719                if (depth < 5) {
720                    //if (isMainActivity) printf("LOG: isMainActivity==false\n");
721                    //if (isLauncherActivity) printf("LOG: isLauncherActivity==false\n");
722                    isMainActivity = false;
723                    isLauncherActivity = false;
724                }
725
726                if (withinActivity && isMainActivity && isLauncherActivity) {
727                    printf("launchable activity:");
728                    const char *aName = getComponentName(pkg, activityName);
729                    if (aName != NULL) {
730                        printf(" name='%s'", aName);
731                    }
732                    printf("label='%s' icon='%s'\n",
733                           activityLabel.string(),
734                           activityIcon.string());
735                }
736            }
737            printf("locales:");
738            Vector<String8> locales;
739            res.getLocales(&locales);
740            const size_t N = locales.size();
741            for (size_t i=0; i<N; i++) {
742                const char* localeStr =  locales[i].string();
743                if (localeStr == NULL || strlen(localeStr) == 0) {
744                    localeStr = "--_--";
745                }
746                printf(" '%s'", localeStr);
747            }
748            printf("\n");
749            AssetDir* dir = assets.openNonAssetDir(assetsCookie, "lib");
750            if (dir != NULL) {
751                if (dir->getFileCount() > 0) {
752                    printf("native-code:");
753                    for (size_t i=0; i<dir->getFileCount(); i++) {
754                        printf(" '%s'", dir->getFileName(i).string());
755                    }
756                    printf("\n");
757                }
758                delete dir;
759            }
760        } else if (strcmp("configurations", option) == 0) {
761            Vector<ResTable_config> configs;
762            res.getConfigurations(&configs);
763            const size_t N = configs.size();
764            for (size_t i=0; i<N; i++) {
765                printf("%s\n", configs[i].toString().string());
766            }
767        } else {
768            fprintf(stderr, "ERROR: unknown dump option '%s'\n", option);
769            goto bail;
770        }
771    }
772
773    result = NO_ERROR;
774
775bail:
776    if (asset) {
777        delete asset;
778    }
779    return (result != NO_ERROR);
780}
781
782
783/*
784 * Handle the "add" command, which wants to add files to a new or
785 * pre-existing archive.
786 */
787int doAdd(Bundle* bundle)
788{
789    ZipFile* zip = NULL;
790    status_t result = UNKNOWN_ERROR;
791    const char* zipFileName;
792
793    if (bundle->getUpdate()) {
794        /* avoid confusion */
795        fprintf(stderr, "ERROR: can't use '-u' with add\n");
796        goto bail;
797    }
798
799    if (bundle->getFileSpecCount() < 1) {
800        fprintf(stderr, "ERROR: must specify zip file name\n");
801        goto bail;
802    }
803    zipFileName = bundle->getFileSpecEntry(0);
804
805    if (bundle->getFileSpecCount() < 2) {
806        fprintf(stderr, "NOTE: nothing to do\n");
807        goto bail;
808    }
809
810    zip = openReadWrite(zipFileName, true);
811    if (zip == NULL) {
812        fprintf(stderr, "ERROR: failed opening/creating '%s' as Zip file\n", zipFileName);
813        goto bail;
814    }
815
816    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
817        const char* fileName = bundle->getFileSpecEntry(i);
818
819        if (strcasecmp(String8(fileName).getPathExtension().string(), ".gz") == 0) {
820            printf(" '%s'... (from gzip)\n", fileName);
821            result = zip->addGzip(fileName, String8(fileName).getBasePath().string(), NULL);
822        } else {
823            printf(" '%s'...\n", fileName);
824            result = zip->add(fileName, bundle->getCompressionMethod(), NULL);
825        }
826        if (result != NO_ERROR) {
827            fprintf(stderr, "Unable to add '%s' to '%s'", bundle->getFileSpecEntry(i), zipFileName);
828            if (result == NAME_NOT_FOUND)
829                fprintf(stderr, ": file not found\n");
830            else if (result == ALREADY_EXISTS)
831                fprintf(stderr, ": already exists in archive\n");
832            else
833                fprintf(stderr, "\n");
834            goto bail;
835        }
836    }
837
838    result = NO_ERROR;
839
840bail:
841    delete zip;
842    return (result != NO_ERROR);
843}
844
845
846/*
847 * Delete files from an existing archive.
848 */
849int doRemove(Bundle* bundle)
850{
851    ZipFile* zip = NULL;
852    status_t result = UNKNOWN_ERROR;
853    const char* zipFileName;
854
855    if (bundle->getFileSpecCount() < 1) {
856        fprintf(stderr, "ERROR: must specify zip file name\n");
857        goto bail;
858    }
859    zipFileName = bundle->getFileSpecEntry(0);
860
861    if (bundle->getFileSpecCount() < 2) {
862        fprintf(stderr, "NOTE: nothing to do\n");
863        goto bail;
864    }
865
866    zip = openReadWrite(zipFileName, false);
867    if (zip == NULL) {
868        fprintf(stderr, "ERROR: failed opening Zip archive '%s'\n",
869            zipFileName);
870        goto bail;
871    }
872
873    for (int i = 1; i < bundle->getFileSpecCount(); i++) {
874        const char* fileName = bundle->getFileSpecEntry(i);
875        ZipEntry* entry;
876
877        entry = zip->getEntryByName(fileName);
878        if (entry == NULL) {
879            printf(" '%s' NOT FOUND\n", fileName);
880            continue;
881        }
882
883        result = zip->remove(entry);
884
885        if (result != NO_ERROR) {
886            fprintf(stderr, "Unable to delete '%s' from '%s'\n",
887                bundle->getFileSpecEntry(i), zipFileName);
888            goto bail;
889        }
890    }
891
892    /* update the archive */
893    zip->flush();
894
895bail:
896    delete zip;
897    return (result != NO_ERROR);
898}
899
900
901/*
902 * Package up an asset directory and associated application files.
903 */
904int doPackage(Bundle* bundle)
905{
906    const char* outputAPKFile;
907    int retVal = 1;
908    status_t err;
909    sp<AaptAssets> assets;
910    int N;
911
912    // -c zz_ZZ means do pseudolocalization
913    ResourceFilter filter;
914    err = filter.parse(bundle->getConfigurations());
915    if (err != NO_ERROR) {
916        goto bail;
917    }
918    if (filter.containsPseudo()) {
919        bundle->setPseudolocalize(true);
920    }
921
922    N = bundle->getFileSpecCount();
923    if (N < 1 && bundle->getResourceSourceDirs().size() == 0 && bundle->getJarFiles().size() == 0
924            && bundle->getAndroidManifestFile() == NULL && bundle->getAssetSourceDir() == NULL) {
925        fprintf(stderr, "ERROR: no input files\n");
926        goto bail;
927    }
928
929    outputAPKFile = bundle->getOutputAPKFile();
930
931    // Make sure the filenames provided exist and are of the appropriate type.
932    if (outputAPKFile) {
933        FileType type;
934        type = getFileType(outputAPKFile);
935        if (type != kFileTypeNonexistent && type != kFileTypeRegular) {
936            fprintf(stderr,
937                "ERROR: output file '%s' exists but is not regular file\n",
938                outputAPKFile);
939            goto bail;
940        }
941    }
942
943    // Load the assets.
944    assets = new AaptAssets();
945    err = assets->slurpFromArgs(bundle);
946    if (err < 0) {
947        goto bail;
948    }
949
950    if (bundle->getVerbose()) {
951        assets->print();
952    }
953
954    // If they asked for any files that need to be compiled, do so.
955    if (bundle->getResourceSourceDirs().size() || bundle->getAndroidManifestFile()) {
956        err = buildResources(bundle, assets);
957        if (err != 0) {
958            goto bail;
959        }
960    }
961
962    // At this point we've read everything and processed everything.  From here
963    // on out it's just writing output files.
964    if (SourcePos::hasErrors()) {
965        goto bail;
966    }
967
968    // Write out R.java constants
969    if (assets->getPackage() == assets->getSymbolsPrivatePackage()) {
970        err = writeResourceSymbols(bundle, assets, assets->getPackage(), true);
971        if (err < 0) {
972            goto bail;
973        }
974    } else {
975        err = writeResourceSymbols(bundle, assets, assets->getPackage(), false);
976        if (err < 0) {
977            goto bail;
978        }
979        err = writeResourceSymbols(bundle, assets, assets->getSymbolsPrivatePackage(), true);
980        if (err < 0) {
981            goto bail;
982        }
983    }
984
985    // Write the apk
986    if (outputAPKFile) {
987        err = writeAPK(bundle, assets, String8(outputAPKFile));
988        if (err != NO_ERROR) {
989            fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputAPKFile);
990            goto bail;
991        }
992    }
993
994    retVal = 0;
995bail:
996    if (SourcePos::hasErrors()) {
997        SourcePos::printErrors(stderr);
998    }
999    return retVal;
1000}
1001