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