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