diff options
Diffstat (limited to 'tools/aapt')
-rw-r--r-- | tools/aapt/AaptAssets.cpp | 11 | ||||
-rw-r--r-- | tools/aapt/Android.mk | 7 | ||||
-rw-r--r-- | tools/aapt/CacheUpdater.h | 4 | ||||
-rw-r--r-- | tools/aapt/Command.cpp | 16 | ||||
-rw-r--r-- | tools/aapt/CrunchCache.cpp | 2 | ||||
-rw-r--r-- | tools/aapt/Images.cpp | 266 | ||||
-rw-r--r-- | tools/aapt/Package.cpp | 1 | ||||
-rw-r--r-- | tools/aapt/Resource.cpp | 120 | ||||
-rw-r--r-- | tools/aapt/ResourceIdCache.cpp | 5 | ||||
-rw-r--r-- | tools/aapt/ResourceTable.cpp | 313 | ||||
-rw-r--r-- | tools/aapt/StringPool.cpp | 84 | ||||
-rw-r--r-- | tools/aapt/StringPool.h | 11 | ||||
-rw-r--r-- | tools/aapt/XMLNode.cpp | 167 | ||||
-rw-r--r-- | tools/aapt/ZipEntry.cpp | 89 | ||||
-rw-r--r-- | tools/aapt/ZipEntry.h | 2 | ||||
-rw-r--r-- | tools/aapt/ZipFile.cpp | 2 | ||||
-rw-r--r-- | tools/aapt/qsort_r_compat.c | 90 | ||||
-rw-r--r-- | tools/aapt/qsort_r_compat.h | 39 |
18 files changed, 637 insertions, 592 deletions
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp index 117fc24..2849c84 100644 --- a/tools/aapt/AaptAssets.cpp +++ b/tools/aapt/AaptAssets.cpp @@ -15,7 +15,6 @@ #include <dirent.h> #include <errno.h> -static const char* kDefaultLocale = "default"; static const char* kAssetDir = "assets"; static const char* kResourceDir = "res"; static const char* kValuesDir = "values"; @@ -176,7 +175,7 @@ inline bool isNumber(const String8& string) { void AaptLocaleValue::setLanguage(const char* languageChars) { size_t i = 0; - while ((*languageChars) != '\0') { + while ((*languageChars) != '\0' && i < sizeof(language)/sizeof(language[0])) { language[i++] = tolower(*languageChars); languageChars++; } @@ -184,7 +183,7 @@ void AaptLocaleValue::setLanguage(const char* languageChars) { void AaptLocaleValue::setRegion(const char* regionChars) { size_t i = 0; - while ((*regionChars) != '\0') { + while ((*regionChars) != '\0' && i < sizeof(region)/sizeof(region[0])) { region[i++] = toupper(*regionChars); regionChars++; } @@ -192,7 +191,7 @@ void AaptLocaleValue::setRegion(const char* regionChars) { void AaptLocaleValue::setScript(const char* scriptChars) { size_t i = 0; - while ((*scriptChars) != '\0') { + while ((*scriptChars) != '\0' && i < sizeof(script)/sizeof(script[0])) { if (i == 0) { script[i++] = toupper(*scriptChars); } else { @@ -204,7 +203,7 @@ void AaptLocaleValue::setScript(const char* scriptChars) { void AaptLocaleValue::setVariant(const char* variantChars) { size_t i = 0; - while ((*variantChars) != '\0') { + while ((*variantChars) != '\0' && i < sizeof(variant)/sizeof(variant[0])) { variant[i++] = *variantChars; variantChars++; } @@ -1240,7 +1239,7 @@ bail: } ssize_t -AaptAssets::slurpResourceZip(Bundle* bundle, const char* filename) +AaptAssets::slurpResourceZip(Bundle* /* bundle */, const char* filename) { int count = 0; SortedVector<AaptGroupEntry> entries; diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk index 2cbabe1..0ccf0f5 100644 --- a/tools/aapt/Android.mk +++ b/tools/aapt/Android.mk @@ -46,7 +46,6 @@ aaptSources := \ WorkQueue.cpp \ ZipEntry.cpp \ ZipFile.cpp \ - qsort_r_compat.c aaptTests := \ tests/AaptConfig_test.cpp \ @@ -68,6 +67,7 @@ aaptHostStaticLibs := \ libziparchive-host aaptCFlags := -DAAPT_VERSION=\"$(BUILD_NUMBER)\" +aaptCFLAGS += -Wall -Werror ifeq ($(HOST_OS),linux) aaptHostLdLibs += -lrt -ldl -lpthread @@ -125,6 +125,7 @@ include $(BUILD_HOST_EXECUTABLE) # Build the host tests: libaapt_tests # ========================================================== include $(CLEAR_VARS) +LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk LOCAL_MODULE := libaapt_tests @@ -152,8 +153,6 @@ LOCAL_MODULE := aapt LOCAL_SRC_FILES := $(aaptSources) $(aaptMain) LOCAL_C_INCLUDES += \ $(aaptCIncludes) \ - bionic \ - external/stlport/stlport LOCAL_SHARED_LIBRARIES := \ libandroidfw \ @@ -164,12 +163,12 @@ LOCAL_SHARED_LIBRARIES := \ libz LOCAL_STATIC_LIBRARIES := \ - libstlport_static \ libexpat_static LOCAL_CFLAGS += $(aaptCFlags) LOCAL_CPPFLAGS += -Wno-non-virtual-dtor +include external/stlport/libstlport.mk include $(BUILD_EXECUTABLE) endif # Not SDK_ONLY diff --git a/tools/aapt/CacheUpdater.h b/tools/aapt/CacheUpdater.h index efb2453..cacab03 100644 --- a/tools/aapt/CacheUpdater.h +++ b/tools/aapt/CacheUpdater.h @@ -38,6 +38,8 @@ public: // Process an image from source out to dest virtual void processImage(String8 source, String8 dest) = 0; + + virtual ~CacheUpdater() {} private: }; @@ -107,4 +109,4 @@ private: Bundle* bundle; }; -#endif // CACHE_UPDATER_H
\ No newline at end of file +#endif // CACHE_UPDATER_H diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp index 41d8502..258c7c7 100644 --- a/tools/aapt/Command.cpp +++ b/tools/aapt/Command.cpp @@ -211,14 +211,15 @@ int doList(Bundle* bundle) goto bail; } +#ifdef HAVE_ANDROID_OS + static const bool kHaveAndroidOs = true; +#else + static const bool kHaveAndroidOs = false; +#endif const ResTable& res = assets.getResources(false); - if (&res == NULL) { - printf("\nNo resource table found.\n"); - } else { -#ifndef HAVE_ANDROID_OS + if (!kHaveAndroidOs) { printf("\nResource table:\n"); res.print(false); -#endif } Asset* manifestAsset = assets.openNonAsset("AndroidManifest.xml", @@ -617,10 +618,7 @@ int doDump(Bundle* bundle) assets.setConfiguration(config); const ResTable& res = assets.getResources(false); - if (&res == NULL) { - fprintf(stderr, "ERROR: dump failed because no resource table was found\n"); - return 1; - } else if (res.getError() != NO_ERROR) { + if (res.getError() != NO_ERROR) { fprintf(stderr, "ERROR: dump failed because the resource table is invalid/corrupt.\n"); return 1; } diff --git a/tools/aapt/CrunchCache.cpp b/tools/aapt/CrunchCache.cpp index c4cf6bc..6c39d1d 100644 --- a/tools/aapt/CrunchCache.cpp +++ b/tools/aapt/CrunchCache.cpp @@ -101,4 +101,4 @@ bool CrunchCache::needsUpdating(String8 relativePath) const time_t sourceDate = mSourceFiles.valueFor(mSourcePath.appendPathCopy(relativePath)); time_t destDate = mDestFiles.valueFor(mDestPath.appendPathCopy(relativePath)); return sourceDate > destDate; -}
\ No newline at end of file +} diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp index 56d1650..f9fd824 100644 --- a/tools/aapt/Images.cpp +++ b/tools/aapt/Images.cpp @@ -14,7 +14,8 @@ #include <png.h> #include <zlib.h> -#define NOISY(x) //x +// Change this to true for noisy debug output. +static const bool kIsDebug = false; static void png_write_aapt_file(png_structp png_ptr, png_bytep data, png_size_t length) @@ -28,7 +29,7 @@ png_write_aapt_file(png_structp png_ptr, png_bytep data, png_size_t length) static void -png_flush_aapt_file(png_structp png_ptr) +png_flush_aapt_file(png_structp /* png_ptr */) { } @@ -156,11 +157,13 @@ static void read_png(const char* imageName, png_read_end(read_ptr, read_info); - NOISY(printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n", - imageName, - (int)outImageInfo->width, (int)outImageInfo->height, - bit_depth, color_type, - interlace_type, compression_type)); + if (kIsDebug) { + printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n", + imageName, + (int)outImageInfo->width, (int)outImageInfo->height, + bit_depth, color_type, + interlace_type, compression_type); + } png_get_IHDR(read_ptr, read_info, &outImageInfo->width, &outImageInfo->height, &bit_depth, &color_type, @@ -330,7 +333,7 @@ static status_t get_vertical_ticks( } static status_t get_horizontal_layout_bounds_ticks( - png_bytep row, int width, bool transparent, bool required, + png_bytep row, int width, bool transparent, bool /* required */, int32_t* outLeft, int32_t* outRight, const char** outError) { int i; @@ -368,7 +371,7 @@ static status_t get_horizontal_layout_bounds_ticks( } static status_t get_vertical_layout_bounds_ticks( - png_bytepp rows, int offset, int height, bool transparent, bool required, + png_bytepp rows, int offset, int height, bool transparent, bool /* required */, int32_t* outTop, int32_t* outBottom, const char** outError) { int i; @@ -493,13 +496,15 @@ static void get_outline(image_info* image) */ image->outlineRadius = 3.4142f * diagonalInset; - NOISY(printf("outline insets %d %d %d %d, rad %f, alpha %x\n", - image->outlineInsetsLeft, - image->outlineInsetsTop, - image->outlineInsetsRight, - image->outlineInsetsBottom, - image->outlineRadius, - image->outlineAlpha)); + if (kIsDebug) { + printf("outline insets %d %d %d %d, rad %f, alpha %x\n", + image->outlineInsetsLeft, + image->outlineInsetsTop, + image->outlineInsetsRight, + image->outlineInsetsBottom, + image->outlineRadius, + image->outlineAlpha); + } } @@ -533,41 +538,6 @@ static uint32_t get_color( return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2]; } -static void select_patch( - int which, int front, int back, int size, int* start, int* end) -{ - switch (which) { - case 0: - *start = 0; - *end = front-1; - break; - case 1: - *start = front; - *end = back-1; - break; - case 2: - *start = back; - *end = size-1; - break; - } -} - -static uint32_t get_color(image_info* image, int hpatch, int vpatch) -{ - int left, right, top, bottom; - select_patch( - hpatch, image->xDivs[0], image->xDivs[1], - image->width, &left, &right); - select_patch( - vpatch, image->yDivs[0], image->yDivs[1], - image->height, &top, &bottom); - //printf("Selecting h=%d v=%d: (%d,%d)-(%d,%d)\n", - // hpatch, vpatch, left, top, right, bottom); - const uint32_t c = get_color(image->rows, left, top, right, bottom); - NOISY(printf("Color in (%d,%d)-(%d,%d): #%08x\n", left, top, right, bottom, c)); - return c; -} - static status_t do_9patch(const char* imageName, image_info* image) { image->is9Patch = true; @@ -672,8 +642,10 @@ static status_t do_9patch(const char* imageName, image_info* image) || image->layoutBoundsBottom != 0; if (image->haveLayoutBounds) { - NOISY(printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop, - image->layoutBoundsRight, image->layoutBoundsBottom)); + if (kIsDebug) { + printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop, + image->layoutBoundsRight, image->layoutBoundsBottom); + } } // use opacity of pixels to estimate the round rect outline @@ -695,12 +667,14 @@ static status_t do_9patch(const char* imageName, image_info* image) image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom; } - NOISY(printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName, - xDivs[0], xDivs[1], - yDivs[0], yDivs[1])); - NOISY(printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName, - image->info9Patch.paddingLeft, image->info9Patch.paddingRight, - image->info9Patch.paddingTop, image->info9Patch.paddingBottom)); + if (kIsDebug) { + printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName, + xDivs[0], xDivs[1], + yDivs[0], yDivs[1]); + printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName, + image->info9Patch.paddingLeft, image->info9Patch.paddingRight, + image->info9Patch.paddingTop, image->info9Patch.paddingBottom); + } // Remove frame from image. image->rows = (png_bytepp)malloc((H-2) * sizeof(png_bytep)); @@ -782,7 +756,10 @@ static status_t do_9patch(const char* imageName, image_info* image) } c = get_color(image->rows, left, top, right - 1, bottom - 1); image->colors[colorIndex++] = c; - NOISY(if (c != Res_png_9patch::NO_COLOR) hasColor = true); + if (kIsDebug) { + if (c != Res_png_9patch::NO_COLOR) + hasColor = true; + } left = right; } top = bottom; @@ -885,7 +862,7 @@ static void dump_image(int w, int h, png_bytepp rows, int color_type) break; } if (i == (w - 1)) { - NOISY(printf("\n")); + printf("\n"); } } } @@ -915,8 +892,10 @@ static void analyze_image(const char *imageName, image_info &imageInfo, int gray // 2. Every pixel has A == 255 (opaque) // 3. There are no more than 256 distinct RGBA colors - // NOISY(printf("Initial image data:\n")); - // dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA); + if (kIsDebug) { + printf("Initial image data:\n"); + dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA); + } for (j = 0; j < h; j++) { png_bytep row = imageInfo.rows[j]; @@ -932,15 +911,19 @@ static void analyze_image(const char *imageName, image_info &imageInfo, int gray maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation); maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation); if (maxGrayDeviation > odev) { - NOISY(printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n", - maxGrayDeviation, i, j, rr, gg, bb, aa)); + if (kIsDebug) { + printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n", + maxGrayDeviation, i, j, rr, gg, bb, aa); + } } // Check if image is really grayscale if (isGrayscale) { if (rr != gg || rr != bb) { - NOISY(printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n", - i, j, rr, gg, bb, aa)); + if (kIsDebug) { + printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n", + i, j, rr, gg, bb, aa); + } isGrayscale = false; } } @@ -948,8 +931,10 @@ static void analyze_image(const char *imageName, image_info &imageInfo, int gray // Check if image is really opaque if (isOpaque) { if (aa != 0xff) { - NOISY(printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n", - i, j, rr, gg, bb, aa)); + if (kIsDebug) { + printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n", + i, j, rr, gg, bb, aa); + } isOpaque = false; } } @@ -971,7 +956,9 @@ static void analyze_image(const char *imageName, image_info &imageInfo, int gray *out++ = idx; if (!match) { if (num_colors == 256) { - NOISY(printf("Found 257th color at %d, %d\n", i, j)); + if (kIsDebug) { + printf("Found 257th color at %d, %d\n", i, j); + } isPalette = false; } else { colors[num_colors++] = col; @@ -986,12 +973,14 @@ static void analyze_image(const char *imageName, image_info &imageInfo, int gray int bpp = isOpaque ? 3 : 4; int paletteSize = w * h + bpp * num_colors; - NOISY(printf("isGrayscale = %s\n", isGrayscale ? "true" : "false")); - NOISY(printf("isOpaque = %s\n", isOpaque ? "true" : "false")); - NOISY(printf("isPalette = %s\n", isPalette ? "true" : "false")); - NOISY(printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n", - paletteSize, 2 * w * h, bpp * w * h)); - NOISY(printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance)); + if (kIsDebug) { + printf("isGrayscale = %s\n", isGrayscale ? "true" : "false"); + printf("isOpaque = %s\n", isOpaque ? "true" : "false"); + printf("isPalette = %s\n", isPalette ? "true" : "false"); + printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n", + paletteSize, 2 * w * h, bpp * w * h); + printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance); + } // Choose the best color type for the image. // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel @@ -1068,7 +1057,6 @@ static void write_png(const char* imageName, png_structp write_ptr, png_infop write_info, image_info& imageInfo, int grayscaleTolerance) { - bool optimize = true; png_uint_32 width, height; int color_type; int bit_depth, interlace_type, compression_type; @@ -1094,8 +1082,10 @@ static void write_png(const char* imageName, png_set_compression_level(write_ptr, Z_BEST_COMPRESSION); - NOISY(printf("Writing image %s: w = %d, h = %d\n", imageName, - (int) imageInfo.width, (int) imageInfo.height)); + if (kIsDebug) { + printf("Writing image %s: w = %d, h = %d\n", imageName, + (int) imageInfo.width, (int) imageInfo.height); + } png_color rgbPalette[256]; png_byte alphaPalette[256]; @@ -1112,24 +1102,26 @@ static void write_png(const char* imageName, color_type = PNG_COLOR_TYPE_RGB_ALPHA; } - switch (color_type) { - case PNG_COLOR_TYPE_PALETTE: - NOISY(printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n", - imageName, paletteEntries, - hasTransparency ? " (with alpha)" : "")); - break; - case PNG_COLOR_TYPE_GRAY: - NOISY(printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName)); - break; - case PNG_COLOR_TYPE_GRAY_ALPHA: - NOISY(printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName)); - break; - case PNG_COLOR_TYPE_RGB: - NOISY(printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName)); - break; - case PNG_COLOR_TYPE_RGB_ALPHA: - NOISY(printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName)); - break; + if (kIsDebug) { + switch (color_type) { + case PNG_COLOR_TYPE_PALETTE: + printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n", + imageName, paletteEntries, + hasTransparency ? " (with alpha)" : ""); + break; + case PNG_COLOR_TYPE_GRAY: + printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName); + break; + case PNG_COLOR_TYPE_GRAY_ALPHA: + printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName); + break; + case PNG_COLOR_TYPE_RGB: + printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName); + break; + case PNG_COLOR_TYPE_RGB_ALPHA: + printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName); + break; + } } png_set_IHDR(write_ptr, write_info, imageInfo.width, imageInfo.height, @@ -1158,7 +1150,9 @@ static void write_png(const char* imageName, : (png_byte*)"npOl\0npTc"; // base 9 patch data - NOISY(printf("Adding 9-patch info...\n")); + if (kIsDebug) { + printf("Adding 9-patch info...\n"); + } strcpy((char*)unknowns[p_index].name, "npTc"); unknowns[p_index].data = (png_byte*)imageInfo.serialize9patch(); unknowns[p_index].size = imageInfo.info9Patch.serializedSize(); @@ -1214,8 +1208,10 @@ static void write_png(const char* imageName, } png_write_image(write_ptr, rows); -// NOISY(printf("Final image data:\n")); -// dump_image(imageInfo.width, imageInfo.height, rows, color_type); + if (kIsDebug) { + printf("Final image data:\n"); + dump_image(imageInfo.width, imageInfo.height, rows, color_type); + } png_write_end(write_ptr, write_info); @@ -1231,13 +1227,50 @@ static void write_png(const char* imageName, &bit_depth, &color_type, &interlace_type, &compression_type, NULL); - NOISY(printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n", - (int)width, (int)height, bit_depth, color_type, interlace_type, - compression_type)); + if (kIsDebug) { + printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n", + (int)width, (int)height, bit_depth, color_type, interlace_type, + compression_type); + } } -status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets, - const sp<AaptFile>& file, String8* outNewLeafName) +static bool read_png_protected(png_structp read_ptr, String8& printableName, png_infop read_info, + const sp<AaptFile>& file, FILE* fp, image_info* imageInfo) { + if (setjmp(png_jmpbuf(read_ptr))) { + return false; + } + + png_init_io(read_ptr, fp); + + read_png(printableName.string(), read_ptr, read_info, imageInfo); + + const size_t nameLen = file->getPath().length(); + if (nameLen > 6) { + const char* name = file->getPath().string(); + if (name[nameLen-5] == '9' && name[nameLen-6] == '.') { + if (do_9patch(printableName.string(), imageInfo) != NO_ERROR) { + return false; + } + } + } + + return true; +} + +static bool write_png_protected(png_structp write_ptr, String8& printableName, png_infop write_info, + image_info* imageInfo, const Bundle* bundle) { + if (setjmp(png_jmpbuf(write_ptr))) { + return false; + } + + write_png(printableName.string(), write_ptr, write_info, *imageInfo, + bundle->getGrayscaleTolerance()); + + return true; +} + +status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& /* assets */, + const sp<AaptFile>& file, String8* /* outNewLeafName */) { String8 ext(file->getPath().getPathExtension()); @@ -1267,8 +1300,6 @@ status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets, status_t error = UNKNOWN_ERROR; - const size_t nameLen = file->getPath().length(); - fp = fopen(file->getSourceFile().string(), "rb"); if (fp == NULL) { fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string()); @@ -1286,23 +1317,10 @@ status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets, goto bail; } - if (setjmp(png_jmpbuf(read_ptr))) { + if (!read_png_protected(read_ptr, printableName, read_info, file, fp, &imageInfo)) { goto bail; } - png_init_io(read_ptr, fp); - - read_png(printableName.string(), read_ptr, read_info, &imageInfo); - - if (nameLen > 6) { - const char* name = file->getPath().string(); - if (name[nameLen-5] == '9' && name[nameLen-6] == '.') { - if (do_9patch(printableName.string(), &imageInfo) != NO_ERROR) { - goto bail; - } - } - } - write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL, (png_error_ptr)NULL); if (!write_ptr) @@ -1319,14 +1337,10 @@ status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets, png_set_write_fn(write_ptr, (void*)file.get(), png_write_aapt_file, png_flush_aapt_file); - if (setjmp(png_jmpbuf(write_ptr))) - { + if (!write_png_protected(write_ptr, printableName, write_info, &imageInfo, bundle)) { goto bail; } - write_png(printableName.string(), write_ptr, write_info, imageInfo, - bundle->getGrayscaleTolerance()); - error = NO_ERROR; if (bundle->getVerbose()) { diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp index dc16e35..cb244ec 100644 --- a/tools/aapt/Package.cpp +++ b/tools/aapt/Package.cpp @@ -402,7 +402,6 @@ bool endsWith(const char* haystack, const char* needle) ssize_t processJarFile(ZipFile* jar, ZipFile* out) { - status_t err; size_t N = jar->getNumEntries(); size_t count = 0; for (size_t i=0; i<N; i++) { diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp index a4c9dab..0c0e639 100644 --- a/tools/aapt/Resource.cpp +++ b/tools/aapt/Resource.cpp @@ -16,15 +16,19 @@ #include "WorkQueue.h" #include "XMLNode.h" +// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary. #if HAVE_PRINTF_ZD # define ZD "%zd" # define ZD_TYPE ssize_t +# define STATUST(x) x #else # define ZD "%ld" # define ZD_TYPE long +# define STATUST(x) (status_t)x #endif -#define NOISY(x) // x +// Set to true for noisy debug output. +static const bool kIsDebug = false; // Number of threads to use for preprocessing images. static const size_t MAX_THREADS = 4; @@ -125,15 +129,17 @@ public: String8 leaf(group->getLeaf()); mLeafName = String8(leaf); mParams = file->getGroupEntry().toParams(); - NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n", - group->getPath().string(), mParams.mcc, mParams.mnc, - mParams.language[0] ? mParams.language[0] : '-', - mParams.language[1] ? mParams.language[1] : '-', - mParams.country[0] ? mParams.country[0] : '-', - mParams.country[1] ? mParams.country[1] : '-', - mParams.orientation, mParams.uiMode, - mParams.density, mParams.touchscreen, mParams.keyboard, - mParams.inputFlags, mParams.navigation)); + if (kIsDebug) { + printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n", + group->getPath().string(), mParams.mcc, mParams.mnc, + mParams.language[0] ? mParams.language[0] : '-', + mParams.language[1] ? mParams.language[1] : '-', + mParams.country[0] ? mParams.country[0] : '-', + mParams.country[1] ? mParams.country[1] : '-', + mParams.orientation, mParams.uiMode, + mParams.density, mParams.touchscreen, mParams.keyboard, + mParams.inputFlags, mParams.navigation); + } mPath = "res"; mPath.appendPath(file->getGroupEntry().toDirName(mResType)); mPath.appendPath(leaf); @@ -144,7 +150,9 @@ public: return UNKNOWN_ERROR; } - NOISY(printf("file name=%s\n", mBaseName.string())); + if (kIsDebug) { + printf("file name=%s\n", mBaseName.string()); + } return NO_ERROR; } @@ -261,7 +269,7 @@ static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets, ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "minSdkVersion"); if (minSdkIndex >= 0) { - const uint16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len); + const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len); const char* minSdk8 = strdup(String8(minSdk16).string()); bundle->setManifestMinSdkVersion(minSdk8); } @@ -317,7 +325,7 @@ static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets, assets->addResource(it.getLeafName(), resPath, it.getFile(), type8); } - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } class PreProcessImageWorkUnit : public WorkQueue::WorkUnit { @@ -367,7 +375,7 @@ static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& ass hasErrors = true; } } - return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR; + return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } static void collect_files(const sp<AaptDir>& dir, @@ -392,27 +400,35 @@ static void collect_files(const sp<AaptDir>& dir, if (index < 0) { sp<ResourceTypeSet> set = new ResourceTypeSet(); - NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n", - leafName.string(), group->getPath().string(), group.get())); + if (kIsDebug) { + printf("Creating new resource type set for leaf %s with group %s (%p)\n", + leafName.string(), group->getPath().string(), group.get()); + } set->add(leafName, group); resources->add(resType, set); } else { sp<ResourceTypeSet> set = resources->valueAt(index); index = set->indexOfKey(leafName); if (index < 0) { - NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n", - leafName.string(), group->getPath().string(), group.get())); + if (kIsDebug) { + printf("Adding to resource type set for leaf %s group %s (%p)\n", + leafName.string(), group->getPath().string(), group.get()); + } set->add(leafName, group); } else { sp<AaptGroup> existingGroup = set->valueAt(index); - NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n", - leafName.string(), group->getPath().string(), group.get())); + if (kIsDebug) { + printf("Extending to resource type set for leaf %s group %s (%p)\n", + leafName.string(), group->getPath().string(), group.get()); + } for (size_t j=0; j<files.size(); j++) { - NOISY(printf("Adding file %s in group %s resType %s\n", - files.valueAt(j)->getSourceFile().string(), - files.keyAt(j).toDirName(String8()).string(), - resType.string())); - status_t err = existingGroup->addFile(files.valueAt(j)); + if (kIsDebug) { + printf("Adding file %s in group %s resType %s\n", + files.valueAt(j)->getSourceFile().string(), + files.keyAt(j).toDirName(String8()).string(), + resType.string()); + } + existingGroup->addFile(files.valueAt(j)); } } } @@ -427,12 +443,16 @@ static void collect_files(const sp<AaptAssets>& ass, for (int i=0; i<N; i++) { sp<AaptDir> d = dirs.itemAt(i); - NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(), - d->getLeaf().string())); + if (kIsDebug) { + printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(), + d->getLeaf().string()); + } collect_files(d, resources); // don't try to include the res dir - NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string())); + if (kIsDebug) { + printf("Removing dir leaf %s\n", d->getLeaf().string()); + } ass->removeDir(d->getLeaf()); } } @@ -450,7 +470,7 @@ static int validateAttr(const String8& path, const ResTable& table, size_t len; ssize_t index = parser.indexOfAttribute(ns, attr); - const uint16_t* str; + const char16_t* str; Res_value value; if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) { const ResStringPool* pool = &parser.getStrings(); @@ -690,9 +710,11 @@ bool addTagAttribute(const sp<XMLNode>& node, const char* ns8, XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr); if (existingEntry != NULL) { if (replaceExisting) { - NOISY(printf("Info: AndroidManifest.xml already defines %s (in %s);" - " overwriting existing value from manifest.\n", - String8(attr).string(), String8(ns).string())); + if (kIsDebug) { + printf("Info: AndroidManifest.xml already defines %s (in %s);" + " overwriting existing value from manifest.\n", + String8(attr).string(), String8(ns).string()); + } existingEntry->string = String16(value); return true; } @@ -751,7 +773,9 @@ static void fullyQualifyClassName(const String8& package, sp<XMLNode> node, } else { className += name; } - NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string())); + if (kIsDebug) { + printf("Qualifying class '%s' to '%s'", name.string(), className.string()); + } attr->string.setTo(String16(className)); } } @@ -855,7 +879,10 @@ status_t massageManifest(Bundle* bundle, sp<XMLNode> root) } String8 origPackage(attr->string); attr->string.setTo(String16(manifestPackageNameOverride)); - NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride)); + if (kIsDebug) { + printf("Overriding package '%s' to be '%s'\n", origPackage.string(), + manifestPackageNameOverride); + } // Make class names fully qualified sp<XMLNode> application = root->getChildElement(String16(), String16("application")); @@ -1112,8 +1139,9 @@ status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuil return err; } - NOISY(printf("Creating resources for package %s\n", - assets->getPackage().string())); + if (kIsDebug) { + printf("Creating resources for package %s\n", assets->getPackage().string()); + } ResourceTable::PackageType packageType = ResourceTable::App; if (bundle->getBuildSharedLibrary()) { @@ -1130,7 +1158,9 @@ status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuil return err; } - NOISY(printf("Found %d included resource packages\n", (int)table.size())); + if (kIsDebug) { + printf("Found %d included resource packages\n", (int)table.size()); + } // Standard flags for compiled XML and optional UTF-8 encoding int xmlFlags = XML_COMPILE_STANDARD_RESOURCE; @@ -1710,7 +1740,7 @@ status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuil } size_t len; ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name"); - const uint16_t* id = block.getAttributeStringValue(index, &len); + const char16_t* id = block.getAttributeStringValue(index, &len); if (id == NULL) { fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n", manifestPath.string(), block.getLineNumber(), @@ -1753,7 +1783,7 @@ status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets, sp<ApkBuil hasErrors = true; } syms->addStringSymbol(String8(e), idStr, srcPos); - const uint16_t* cmt = block.getComment(&len); + const char16_t* cmt = block.getComment(&len); if (cmt != NULL && *cmt != 0) { //printf("Comment of %s: %s\n", String8(e).string(), // String8(cmt).string()); @@ -1970,7 +2000,7 @@ static String16 getAttributeComment(const sp<AaptAssets>& assets, static status_t writeResourceLoadedCallbackForLayoutClasses( FILE* fp, const sp<AaptAssets>& assets, - const sp<AaptSymbols>& symbols, int indent, bool includePrivate) + const sp<AaptSymbols>& symbols, int indent, bool /* includePrivate */) { String16 attr16("attr"); String16 package16(assets->getPackage()); @@ -2274,7 +2304,7 @@ static status_t writeLayoutClasses( indent--; fprintf(fp, "%s};\n", getIndentSpace(indent)); - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } static status_t writeTextLayoutClasses( @@ -2360,7 +2390,7 @@ static status_t writeTextLayoutClasses( package16.string(), package16.size(), &typeSpecFlags); //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(), // String8(attr16).string(), String8(name16).string(), typeSpecFlags); - const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; + //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0; fprintf(fp, "int styleable %s_%s %d\n", @@ -2370,7 +2400,7 @@ static status_t writeTextLayoutClasses( } } - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } static status_t writeSymbolClass( @@ -2701,7 +2731,7 @@ addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName, void addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName, - const char* pkg, const String8& srcName, int line) + const char* /* pkg */, const String8& srcName, int line) { String8 rule("-keepclassmembers class * { *** "); rule += memberName; @@ -3029,7 +3059,7 @@ status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp) } status_t -writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw) +writeDependencyPreReqs(Bundle* /* bundle */, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw) { status_t deps = -1; deps += writePathsToFile(assets->getFullResPaths(), fp); diff --git a/tools/aapt/ResourceIdCache.cpp b/tools/aapt/ResourceIdCache.cpp index d60a07f..d7b2d10 100644 --- a/tools/aapt/ResourceIdCache.cpp +++ b/tools/aapt/ResourceIdCache.cpp @@ -9,7 +9,6 @@ #include <utils/Log.h> #include "ResourceIdCache.h" #include <map> -using namespace std; static size_t mHits = 0; @@ -29,7 +28,7 @@ struct CacheEntry { CacheEntry(const android::String16& name, uint32_t resId) : hashedName(name), id(resId) { } }; -static map< uint32_t, CacheEntry > mIdMap; +static std::map< uint32_t, CacheEntry > mIdMap; // djb2; reasonable choice for strings when collisions aren't particularly important @@ -63,7 +62,7 @@ uint32_t ResourceIdCache::lookup(const android::String16& package, bool onlyPublic) { const String16 hashedName = makeHashableName(package, type, name, onlyPublic); const uint32_t hashcode = hash(hashedName); - map<uint32_t, CacheEntry>::iterator item = mIdMap.find(hashcode); + std::map<uint32_t, CacheEntry>::iterator item = mIdMap.find(hashcode); if (item == mIdMap.end()) { // cache miss mMisses++; diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp index 77d3beb..4b9981d 100644 --- a/tools/aapt/ResourceTable.cpp +++ b/tools/aapt/ResourceTable.cpp @@ -15,7 +15,24 @@ #include <utils/TypeHelpers.h> #include <stdarg.h> -#define NOISY(x) //x +// SSIZE: mingw does not have signed size_t == ssize_t. +// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary. +#if HAVE_PRINTF_ZD +# define SSIZE(x) x +# define STATUST(x) x +#else +# define SSIZE(x) (signed size_t)x +# define STATUST(x) (status_t)x +#endif + +// Set to true for noisy debug output. +static const bool kIsDebug = false; + +#if PRINT_STRING_METRICS +static const bool kPrintStringMetrics = true; +#else +static const bool kPrintStringMetrics = false; +#endif status_t compileXmlFile(const Bundle* bundle, const sp<AaptAssets>& assets, @@ -87,9 +104,11 @@ status_t compileXmlFile(const Bundle* bundle, if (table->modifyForCompat(bundle, resourceName, target, root) != NO_ERROR) { return UNKNOWN_ERROR; } - - NOISY(printf("Input XML Resource:\n")); - NOISY(root->print()); + + if (kIsDebug) { + printf("Input XML Resource:\n"); + root->print(); + } err = root->flatten(target, (options&XML_COMPILE_STRIP_COMMENTS) != 0, (options&XML_COMPILE_STRIP_RAW_VALUES) != 0); @@ -97,19 +116,18 @@ status_t compileXmlFile(const Bundle* bundle, return err; } - NOISY(printf("Output XML Resource:\n")); - NOISY(ResXMLTree tree; + if (kIsDebug) { + printf("Output XML Resource:\n"); + ResXMLTree tree; tree.setTo(target->getData(), target->getSize()); - printXMLBlock(&tree)); + printXMLBlock(&tree); + } target->setCompressionMethod(ZipEntry::kCompressDeflated); return err; } -#undef NOISY -#define NOISY(x) //x - struct flag_entry { const char16_t* name; @@ -399,7 +417,7 @@ static status_t compileAttribute(const sp<AaptFile>& in, ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization"); if (l10nIdx >= 0) { - const uint16_t* str = block.getAttributeStringValue(l10nIdx, &len); + const char16_t* str = block.getAttributeStringValue(l10nIdx, &len); bool error; uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error); if (error) { @@ -578,7 +596,7 @@ status_t parseAndAddBag(Bundle* bundle, const String16& itemIdent, int32_t curFormat, bool isFormatted, - const String16& product, + const String16& /* product */, PseudolocalizationMethod pseudolocalize, const bool overwrite, ResourceTable* outTable) @@ -594,16 +612,18 @@ status_t parseAndAddBag(Bundle* bundle, if (err != NO_ERROR) { return err; } - - NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d " - " pid=%s, bag=%s, id=%s: %s\n", - config.language[0], config.language[1], - config.country[0], config.country[1], - config.orientation, config.density, - String8(parentIdent).string(), - String8(ident).string(), - String8(itemIdent).string(), - String8(str).string())); + + if (kIsDebug) { + printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d " + " pid=%s, bag=%s, id=%s: %s\n", + config.language[0], config.language[1], + config.country[0], config.country[1], + config.orientation, config.density, + String8(parentIdent).string(), + String8(ident).string(), + String8(itemIdent).string(), + String8(str).string()); + } err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()), myPackage, curType, ident, parentIdent, itemIdent, str, @@ -739,11 +759,13 @@ status_t parseAndAddEntry(Bundle* bundle, } } - NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n", - config.language[0], config.language[1], - config.country[0], config.country[1], - config.orientation, config.density, - String8(ident).string(), String8(str).string())); + if (kIsDebug) { + printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n", + config.language[0], config.language[1], + config.country[0], config.country[1], + config.orientation, config.density, + String8(ident).string(), String8(str).string()); + } err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()), myPackage, curType, ident, str, &spans, &config, @@ -1325,7 +1347,7 @@ status_t compileResourceFile(Bundle* bundle, size_t n = block.getAttributeCount(); for (size_t i = 0; i < n; i++) { size_t length; - const uint16_t* attr = block.getAttributeName(i, &length); + const char16_t* attr = block.getAttributeName(i, &length); if (strcmp16(attr, name16.string()) == 0) { name.setTo(block.getAttributeStringValue(i, &length)); } else if (strcmp16(attr, translatable16.string()) == 0) { @@ -1441,14 +1463,14 @@ status_t compileResourceFile(Bundle* bundle, // translatable. for (size_t i = 0; i < n; i++) { size_t length; - const uint16_t* attr = block.getAttributeName(i, &length); + const char16_t* attr = block.getAttributeName(i, &length); if (strcmp16(attr, formatted16.string()) == 0) { - const uint16_t* value = block.getAttributeStringValue(i, &length); + const char16_t* value = block.getAttributeStringValue(i, &length); if (strcmp16(value, false16.string()) == 0) { curIsFormatted = false; } } else if (strcmp16(attr, translatable16.string()) == 0) { - const uint16_t* value = block.getAttributeStringValue(i, &length); + const char16_t* value = block.getAttributeStringValue(i, &length); if (strcmp16(value, false16.string()) == 0) { isTranslatable = false; } @@ -1712,7 +1734,7 @@ status_t compileResourceFile(Bundle* bundle, } } - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage, ResourceTable::PackageType type) @@ -1851,7 +1873,7 @@ status_t ResourceTable::startBag(const SourcePos& sourcePos, const String16& bagParent, const ResTable_config* params, bool overlay, - bool replace, bool isId) + bool replace, bool /* isId */) { status_t result = NO_ERROR; @@ -2150,22 +2172,25 @@ uint32_t ResourceTable::getResId(const String16& ref, ref.string(), ref.size(), &package, &type, &name, defType, defPackage ? defPackage:&mAssetsPackage, outErrorMsg, &refOnlyPublic)) { - NOISY(printf("Expanding resource: ref=%s\n", - String8(ref).string())); - NOISY(printf("Expanding resource: defType=%s\n", - defType ? String8(*defType).string() : "NULL")); - NOISY(printf("Expanding resource: defPackage=%s\n", - defPackage ? String8(*defPackage).string() : "NULL")); - NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string())); - NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n", - String8(package).string(), String8(type).string(), - String8(name).string())); + if (kIsDebug) { + printf("Expanding resource: ref=%s\n", String8(ref).string()); + printf("Expanding resource: defType=%s\n", + defType ? String8(*defType).string() : "NULL"); + printf("Expanding resource: defPackage=%s\n", + defPackage ? String8(*defPackage).string() : "NULL"); + printf("Expanding resource: ref=%s\n", String8(ref).string()); + printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n", + String8(package).string(), String8(type).string(), + String8(name).string()); + } return 0; } uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic); - NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n", - String8(package).string(), String8(type).string(), - String8(name).string(), res)); + if (kIsDebug) { + printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n", + String8(package).string(), String8(type).string(), + String8(name).string(), res); + } if (res == 0) { if (outErrorMsg) *outErrorMsg = "No resource found that matches the given name"; @@ -2232,9 +2257,11 @@ bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool, } else { configStr = "(null)"; } - NOISY(printf("Adding to pool string style #%d config %s: %s\n", - style != NULL ? style->size() : 0, - configStr.string(), String8(finalStr).string())); + if (kIsDebug) { + printf("Adding to pool string style #%zu config %s: %s\n", + style != NULL ? style->size() : 0U, + configStr.string(), String8(finalStr).string()); + } if (style != NULL && style->size() > 0) { outValue->data = pool->add(finalStr, *style, configTypeName, config); } else { @@ -2878,9 +2905,9 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& const size_t typeStringsStart = data->getSize(); sp<AaptFile> strFile = p->getTypeStringsData(); ssize_t amt = data->writeData(strFile->getData(), strFile->getSize()); - #if PRINT_STRING_METRICS - fprintf(stderr, "**** type strings: %d\n", amt); - #endif + if (kPrintStringMetrics) { + fprintf(stderr, "**** type strings: %zd\n", SSIZE(amt)); + } strAmt += amt; if (amt < 0) { return amt; @@ -2888,9 +2915,9 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& const size_t keyStringsStart = data->getSize(); strFile = p->getKeyStringsData(); amt = data->writeData(strFile->getData(), strFile->getSize()); - #if PRINT_STRING_METRICS - fprintf(stderr, "**** key strings: %d\n", amt); - #endif + if (kPrintStringMetrics) { + fprintf(stderr, "**** key strings: %zd\n", SSIZE(amt)); + } strAmt += amt; if (amt < 0) { return amt; @@ -2989,28 +3016,30 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& for (size_t ci=0; ci<NC; ci++) { ConfigDescription config = t->getUniqueConfigs().itemAt(ci); - NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c " - "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " - "sw%ddp w%ddp h%ddp dir:%d\n", - ti+1, - config.mcc, config.mnc, - config.language[0] ? config.language[0] : '-', - config.language[1] ? config.language[1] : '-', - config.country[0] ? config.country[0] : '-', - config.country[1] ? config.country[1] : '-', - config.orientation, - config.uiMode, - config.touchscreen, - config.density, - config.keyboard, - config.inputFlags, - config.navigation, - config.screenWidth, - config.screenHeight, - config.smallestScreenWidthDp, - config.screenWidthDp, - config.screenHeightDp, - config.layoutDirection)); + if (kIsDebug) { + printf("Writing config %zu config: imsi:%d/%d lang:%c%c cnt:%c%c " + "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " + "sw%ddp w%ddp h%ddp layout:%d\n", + ti + 1, + config.mcc, config.mnc, + config.language[0] ? config.language[0] : '-', + config.language[1] ? config.language[1] : '-', + config.country[0] ? config.country[0] : '-', + config.country[1] ? config.country[1] : '-', + config.orientation, + config.uiMode, + config.touchscreen, + config.density, + config.keyboard, + config.inputFlags, + config.navigation, + config.screenWidth, + config.screenHeight, + config.smallestScreenWidthDp, + config.screenWidthDp, + config.screenHeightDp, + config.screenLayout); + } if (filterable && !filter->match(config)) { continue; @@ -3032,28 +3061,30 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& tHeader->entryCount = htodl(N); tHeader->entriesStart = htodl(typeSize); tHeader->config = config; - NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c " - "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " - "sw%ddp w%ddp h%ddp dir:%d\n", - ti+1, - tHeader->config.mcc, tHeader->config.mnc, - tHeader->config.language[0] ? tHeader->config.language[0] : '-', - tHeader->config.language[1] ? tHeader->config.language[1] : '-', - tHeader->config.country[0] ? tHeader->config.country[0] : '-', - tHeader->config.country[1] ? tHeader->config.country[1] : '-', - tHeader->config.orientation, - tHeader->config.uiMode, - tHeader->config.touchscreen, - tHeader->config.density, - tHeader->config.keyboard, - tHeader->config.inputFlags, - tHeader->config.navigation, - tHeader->config.screenWidth, - tHeader->config.screenHeight, - tHeader->config.smallestScreenWidthDp, - tHeader->config.screenWidthDp, - tHeader->config.screenHeightDp, - tHeader->config.layoutDirection)); + if (kIsDebug) { + printf("Writing type %zu config: imsi:%d/%d lang:%c%c cnt:%c%c " + "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " + "sw%ddp w%ddp h%ddp layout:%d\n", + ti + 1, + tHeader->config.mcc, tHeader->config.mnc, + tHeader->config.language[0] ? tHeader->config.language[0] : '-', + tHeader->config.language[1] ? tHeader->config.language[1] : '-', + tHeader->config.country[0] ? tHeader->config.country[0] : '-', + tHeader->config.country[1] ? tHeader->config.country[1] : '-', + tHeader->config.orientation, + tHeader->config.uiMode, + tHeader->config.touchscreen, + tHeader->config.density, + tHeader->config.keyboard, + tHeader->config.inputFlags, + tHeader->config.navigation, + tHeader->config.screenWidth, + tHeader->config.screenHeight, + tHeader->config.smallestScreenWidthDp, + tHeader->config.screenWidthDp, + tHeader->config.screenHeightDp, + tHeader->config.screenLayout); + } tHeader->config.swapHtoD(); // Build the entries inside of this type. @@ -3143,10 +3174,10 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& ssize_t amt = (dest->getSize()-strStart); strAmt += amt; - #if PRINT_STRING_METRICS - fprintf(stderr, "**** value strings: %d\n", amt); - fprintf(stderr, "**** total strings: %d\n", strAmt); - #endif + if (kPrintStringMetrics) { + fprintf(stderr, "**** value strings: %zd\n", SSIZE(amt)); + fprintf(stderr, "**** total strings: %zd\n", SSIZE(strAmt)); + } for (pi=0; pi<flatPackages.size(); pi++) { err = dest->writeData(flatPackages[pi]->getData(), @@ -3161,13 +3192,10 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& (((uint8_t*)dest->getData()) + dataStart); header->header.size = htodl(dest->getSize() - dataStart); - NOISY(aout << "Resource table:" - << HexDump(dest->getData(), dest->getSize()) << endl); - - #if PRINT_STRING_METRICS - fprintf(stderr, "**** total resource table size: %d / %d%% strings\n", - dest->getSize(), (strAmt*100)/dest->getSize()); - #endif + if (kPrintStringMetrics) { + fprintf(stderr, "**** total resource table size: %zu / %zu%% strings\n", + dest->getSize(), (size_t)(strAmt*100)/dest->getSize()); + } return NO_ERROR; } @@ -3175,7 +3203,9 @@ status_t ResourceTable::flatten(Bundle* bundle, const sp<const ResourceFilter>& status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vector<sp<Package> >& libs) { // Write out the library table if necessary if (libs.size() > 0) { - NOISY(fprintf(stderr, "Writing library reference table\n")); + if (kIsDebug) { + fprintf(stderr, "Writing library reference table\n"); + } const size_t libStart = dest->getSize(); const size_t count = libs.size(); @@ -3192,9 +3222,11 @@ status_t ResourceTable::flattenLibraryTable(const sp<AaptFile>& dest, const Vect for (size_t i = 0; i < count; i++) { const size_t entryStart = dest->getSize(); sp<Package> libPackage = libs[i]; - NOISY(fprintf(stderr, " Entry %s -> 0x%02x\n", + if (kIsDebug) { + fprintf(stderr, " Entry %s -> 0x%02x\n", String8(libPackage->getName()).string(), - (uint8_t)libPackage->getAssignedId())); + (uint8_t)libPackage->getAssignedId()); + } ResTable_lib_entry* entry = (ResTable_lib_entry*) dest->editDataInRange( entryStart, sizeof(ResTable_lib_entry)); @@ -3442,9 +3474,11 @@ status_t ResourceTable::Entry::generateAttributes(ResourceTable* table, if (it.isId) { if (!table->hasBagOrEntry(key, &id16, &package)) { String16 value("false"); - NOISY(fprintf(stderr, "Generating %s:id/%s\n", - String8(package).string(), - String8(key).string())); + if (kIsDebug) { + fprintf(stderr, "Generating %s:id/%s\n", + String8(package).string(), + String8(key).string()); + } status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package, id16, key, value); if (err != NO_ERROR) { @@ -3477,7 +3511,7 @@ status_t ResourceTable::Entry::generateAttributes(ResourceTable* table, } status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table, - const String16& package) + const String16& /* package */) { bool hasErrors = false; @@ -3510,7 +3544,7 @@ status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table, } } } - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table, @@ -3569,22 +3603,20 @@ status_t ResourceTable::Entry::remapStringValue(StringPool* strings) return NO_ERROR; } -ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic) +ssize_t ResourceTable::Entry::flatten(Bundle* /* bundle */, const sp<AaptFile>& data, bool isPublic) { size_t amt = 0; ResTable_entry header; memset(&header, 0, sizeof(header)); header.size = htods(sizeof(header)); - const type ty = this != NULL ? mType : TYPE_ITEM; - if (this != NULL) { - if (ty == TYPE_BAG) { - header.flags |= htods(header.FLAG_COMPLEX); - } - if (isPublic) { - header.flags |= htods(header.FLAG_PUBLIC); - } - header.key.index = htodl(mNameIndex); + const type ty = mType; + if (ty == TYPE_BAG) { + header.flags |= htods(header.FLAG_COMPLEX); } + if (isPublic) { + header.flags |= htods(header.FLAG_PUBLIC); + } + header.key.index = htodl(mNameIndex); if (ty != TYPE_BAG) { status_t err = data->writeData(&header, sizeof(header)); if (err != NO_ERROR) { @@ -3759,10 +3791,11 @@ sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry, sp<Entry> e = c->getEntries().valueFor(cdesc); if (e == NULL) { - if (config != NULL) { - NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c " + if (kIsDebug) { + if (config != NULL) { + printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c " "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d " - "sw%ddp w%ddp h%ddp dir:%d\n", + "sw%ddp w%ddp h%ddp layout:%d\n", sourcePos.file.string(), sourcePos.line, config->mcc, config->mnc, config->language[0] ? config->language[0] : '-', @@ -3780,10 +3813,11 @@ sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry, config->smallestScreenWidthDp, config->screenWidthDp, config->screenHeightDp, - config->layoutDirection)); - } else { - NOISY(printf("New entry at %s:%d: NULL config\n", - sourcePos.file.string(), sourcePos.line)); + config->screenLayout); + } else { + printf("New entry at %s:%d: NULL config\n", + sourcePos.file.string(), sourcePos.line); + } } e = new Entry(entry, sourcePos); c->addEntry(cdesc, e); @@ -3889,7 +3923,7 @@ status_t ResourceTable::Type::applyPublicEntryOrder() j++; } - return hasError ? UNKNOWN_ERROR : NO_ERROR; + return hasError ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } ResourceTable::Package::Package(const String16& name, size_t packageId) @@ -3953,9 +3987,6 @@ status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data, return UNKNOWN_ERROR; } - NOISY(aout << "Setting restable string pool: " - << HexDump(data->getData(), data->getSize()) << endl); - status_t err = strings->setTo(data->getData(), data->getSize()); if (err == NO_ERROR) { const size_t N = strings->size(); @@ -4179,7 +4210,7 @@ bool ResourceTable::getItemValue( } item->evaluating = true; res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId); - NOISY( + if (kIsDebug) { if (res) { printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n", resID, attrID, String8(getEntry(resID)->getName()).string(), @@ -4188,7 +4219,7 @@ bool ResourceTable::getItemValue( printf("getItemValue of #%08x[#%08x]: failed\n", resID, attrID); } - ); + } item->evaluating = false; } return res; diff --git a/tools/aapt/StringPool.cpp b/tools/aapt/StringPool.cpp index 06769e4..e3ec0ae 100644 --- a/tools/aapt/StringPool.cpp +++ b/tools/aapt/StringPool.cpp @@ -3,25 +3,30 @@ // // Build resource files from raw assets. // - #include "StringPool.h" -#include "ResourceTable.h" #include <utils/ByteOrder.h> #include <utils/SortedVector.h> -#include "qsort_r_compat.h" +#include <algorithm> + +#include "ResourceTable.h" + +// SSIZE: mingw does not have signed size_t == ssize_t. #if HAVE_PRINTF_ZD # define ZD "%zd" # define ZD_TYPE ssize_t +# define SSIZE(x) x #else # define ZD "%ld" # define ZD_TYPE long +# define SSIZE(x) (signed size_t)x #endif -#define NOISY(x) //x +// Set to true for noisy debug output. +static const bool kIsDebug = false; -void strcpy16_htod(uint16_t* dst, const uint16_t* src) +void strcpy16_htod(char16_t* dst, const char16_t* src) { while (*src) { char16_t s = htods(*src); @@ -140,8 +145,10 @@ ssize_t StringPool::add(const String16& value, if (configTypeName != NULL) { entry& ent = mEntries.editItemAt(eidx); - NOISY(printf("*** adding config type name %s, was %s\n", - configTypeName->string(), ent.configTypeName.string())); + if (kIsDebug) { + printf("*** adding config type name %s, was %s\n", + configTypeName->string(), ent.configTypeName.string()); + } if (ent.configTypeName.size() <= 0) { ent.configTypeName = *configTypeName; } else if (ent.configTypeName != *configTypeName) { @@ -157,14 +164,18 @@ ssize_t StringPool::add(const String16& value, int cmp = ent.configs.itemAt(addPos).compareLogical(*config); if (cmp >= 0) { if (cmp > 0) { - NOISY(printf("*** inserting config: %s\n", config->toString().string())); + if (kIsDebug) { + printf("*** inserting config: %s\n", config->toString().string()); + } ent.configs.insertAt(*config, addPos); } break; } } if (addPos >= ent.configs.size()) { - NOISY(printf("*** adding config: %s\n", config->toString().string())); + if (kIsDebug) { + printf("*** adding config: %s\n", config->toString().string()); + } ent.configs.add(*config); } } @@ -181,9 +192,11 @@ ssize_t StringPool::add(const String16& value, ent.indices.add(pos); } - NOISY(printf("Adding string %s to pool: pos=%d eidx=%d vidx=%d\n", - String8(value).string(), pos, eidx, vidx)); - + if (kIsDebug) { + printf("Adding string %s to pool: pos=%zd eidx=%zd vidx=%zd\n", + String8(value).string(), SSIZE(pos), SSIZE(eidx), SSIZE(vidx)); + } + return pos; } @@ -222,12 +235,15 @@ status_t StringPool::addStyleSpan(size_t idx, const entry_style_span& span) return NO_ERROR; } -int StringPool::config_sort(void* state, const void* lhs, const void* rhs) +StringPool::ConfigSorter::ConfigSorter(const StringPool& pool) : pool(pool) +{ +} + +bool StringPool::ConfigSorter::operator()(size_t l, size_t r) { - StringPool* pool = (StringPool*)state; - const entry& lhe = pool->mEntries[pool->mEntryArray[*static_cast<const size_t*>(lhs)]]; - const entry& rhe = pool->mEntries[pool->mEntryArray[*static_cast<const size_t*>(rhs)]]; - return lhe.compare(rhe); + const StringPool::entry& lhe = pool.mEntries[pool.mEntryArray[l]]; + const StringPool::entry& rhe = pool.mEntries[pool.mEntryArray[r]]; + return lhe.compare(rhe) < 0; } void StringPool::sortByConfig() @@ -247,12 +263,14 @@ void StringPool::sortByConfig() } // Sort the array. - NOISY(printf("SORTING STRINGS BY CONFIGURATION...\n")); - // Vector::sort uses insertion sort, which is very slow for this data set. - // Use quicksort instead because we don't need a stable sort here. - qsort_r_compat(newPosToOriginalPos.editArray(), N, sizeof(size_t), this, config_sort); - //newPosToOriginalPos.sort(config_sort, this); - NOISY(printf("DONE SORTING STRINGS BY CONFIGURATION.\n")); + if (kIsDebug) { + printf("SORTING STRINGS BY CONFIGURATION...\n"); + } + ConfigSorter sorter(*this); + std::sort(newPosToOriginalPos.begin(), newPosToOriginalPos.end(), sorter); + if (kIsDebug) { + printf("DONE SORTING STRINGS BY CONFIGURATION.\n"); + } // Create the reverse mapping from the original position in the array // to the new position where it appears in the sorted array. This is @@ -455,9 +473,9 @@ status_t StringPool::writeStringBlock(const sp<AaptFile>& pool) strncpy((char*)strings, encStr, encSize+1); } else { - uint16_t* strings = (uint16_t*)dat; + char16_t* strings = (char16_t*)dat; - ENCODE_LENGTH(strings, sizeof(uint16_t), strSize) + ENCODE_LENGTH(strings, sizeof(char16_t), strSize) strcpy16_htod(strings, ent.value); } @@ -549,9 +567,13 @@ status_t StringPool::writeStringBlock(const sp<AaptFile>& pool) for (i=0; i<ENTRIES; i++) { entry& ent = mEntries.editItemAt(mEntryArray[i]); *index++ = htodl(ent.offset); - NOISY(printf("Writing entry #%d: \"%s\" ent=%d off=%d\n", i, - String8(ent.value).string(), - mEntryArray[i], ent.offset)); + if (kIsDebug) { + printf("Writing entry #%zu: \"%s\" ent=%zu off=%zu\n", + i, + String8(ent.value).string(), + mEntryArray[i], + ent.offset); + } } // Write style index array. @@ -567,8 +589,10 @@ ssize_t StringPool::offsetForString(const String16& val) const { const Vector<size_t>* indices = offsetsForString(val); ssize_t res = indices != NULL && indices->size() > 0 ? indices->itemAt(0) : -1; - NOISY(printf("Offset for string %s: %d (%s)\n", String8(val).string(), res, - res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8())); + if (kIsDebug) { + printf("Offset for string %s: %zd (%s)\n", String8(val).string(), SSIZE(res), + res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8()); + } return res; } diff --git a/tools/aapt/StringPool.h b/tools/aapt/StringPool.h index 1b3abfd..0b26538 100644 --- a/tools/aapt/StringPool.h +++ b/tools/aapt/StringPool.h @@ -26,7 +26,7 @@ using namespace android; #define PRINT_STRING_METRICS 0 -void strcpy16_htod(uint16_t* dst, const uint16_t* src); +void strcpy16_htod(char16_t* dst, const char16_t* src); void printStringPool(const ResStringPool* pool); @@ -138,7 +138,14 @@ public: const Vector<size_t>* offsetsForString(const String16& val) const; private: - static int config_sort(void* state, const void* lhs, const void* rhs); + class ConfigSorter + { + public: + explicit ConfigSorter(const StringPool&); + bool operator()(size_t l, size_t r); + private: + const StringPool& pool; + }; const bool mUTF8; diff --git a/tools/aapt/XMLNode.cpp b/tools/aapt/XMLNode.cpp index 51a4154..b38b2ed 100644 --- a/tools/aapt/XMLNode.cpp +++ b/tools/aapt/XMLNode.cpp @@ -16,8 +16,26 @@ #define O_BINARY 0 #endif -#define NOISY(x) //x -#define NOISY_PARSE(x) //x +// SSIZE: mingw does not have signed size_t == ssize_t. +// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary. +#if HAVE_PRINTF_ZD +# define SSIZE(x) x +# define STATUST(x) x +#else +# define SSIZE(x) (signed size_t)x +# define STATUST(x) (status_t)x +#endif + +// Set to true for noisy debug output. +static const bool kIsDebug = false; +// Set to true for noisy debug output of parsing. +static const bool kIsDebugParse = false; + +#if PRINT_STRING_METRICS +static const bool kPrintStringMetrics = true; +#else +static const bool kPrintStringMetrics = false; +#endif const char* const RESOURCES_ROOT_NAMESPACE = "http://schemas.android.com/apk/res/"; const char* const RESOURCES_ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android"; @@ -56,7 +74,10 @@ String16 getNamespaceResourcePackage(String16 appPackage, String16 namespaceUri, size_t prefixSize; bool isPublic = true; if(namespaceUri.startsWith(RESOURCES_PREFIX_AUTO_PACKAGE)) { - NOISY(printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(), String8(appPackage).string())); + if (kIsDebug) { + printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(), + String8(appPackage).string()); + } isPublic = true; return appPackage; } else if (namespaceUri.startsWith(RESOURCES_PREFIX)) { @@ -180,7 +201,7 @@ status_t hasSubstitutionErrors(const char* fileName, return NO_ERROR; } -status_t parseStyledString(Bundle* bundle, +status_t parseStyledString(Bundle* /* bundle */, const char* fileName, ResXMLTree* inXml, const String16& endTag, @@ -234,9 +255,9 @@ status_t parseStyledString(Bundle* bundle, const String8 element8(element16); size_t nslen; - const uint16_t* ns = inXml->getElementNamespace(&nslen); + const char16_t* ns = inXml->getElementNamespace(&nslen); if (ns == NULL) { - ns = (const uint16_t*)"\0\0"; + ns = (const char16_t*)"\0\0"; nslen = 0; } const String8 nspace(String16(ns, nslen)); @@ -291,9 +312,9 @@ moveon: } else if (code == ResXMLTree::END_TAG) { size_t nslen; - const uint16_t* ns = inXml->getElementNamespace(&nslen); + const char16_t* ns = inXml->getElementNamespace(&nslen); if (ns == NULL) { - ns = (const uint16_t*)"\0\0"; + ns = (const char16_t*)"\0\0"; nslen = 0; } const String8 nspace(String16(ns, nslen)); @@ -422,7 +443,7 @@ static String8 make_prefix(int depth) } static String8 build_namespace(const Vector<namespace_entry>& namespaces, - const uint16_t* ns) + const char16_t* ns) { String8 str; if (ns != NULL) { @@ -453,9 +474,9 @@ void printXMLBlock(ResXMLTree* block) int i; if (code == ResXMLTree::START_TAG) { size_t len; - const uint16_t* ns16 = block->getElementNamespace(&len); + const char16_t* ns16 = block->getElementNamespace(&len); String8 elemNs = build_namespace(namespaces, ns16); - const uint16_t* com16 = block->getComment(&len); + const char16_t* com16 = block->getComment(&len); if (com16) { printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string()); } @@ -503,7 +524,7 @@ void printXMLBlock(ResXMLTree* block) } else if (code == ResXMLTree::START_NAMESPACE) { namespace_entry ns; size_t len; - const uint16_t* prefix16 = block->getNamespacePrefix(&len); + const char16_t* prefix16 = block->getNamespacePrefix(&len); if (prefix16) { ns.prefix = String8(prefix16); } else { @@ -518,7 +539,7 @@ void printXMLBlock(ResXMLTree* block) depth--; const namespace_entry& ns = namespaces.top(); size_t len; - const uint16_t* prefix16 = block->getNamespacePrefix(&len); + const char16_t* prefix16 = block->getNamespacePrefix(&len); String8 pr; if (prefix16) { pr = String8(prefix16); @@ -557,8 +578,10 @@ status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree, } root->removeWhitespace(stripAll, cDataTags); - NOISY(printf("Input XML from %s:\n", (const char*)file->getPrintableSource())); - NOISY(root->print()); + if (kIsDebug) { + printf("Input XML from %s:\n", (const char*)file->getPrintableSource()); + root->print(); + } sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8()); status_t err = root->flatten(rsc, !keepComments, false); if (err != NO_ERROR) { @@ -569,8 +592,10 @@ status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree, return err; } - NOISY(printf("Output XML:\n")); - NOISY(printXMLBlock(outTree)); + if (kIsDebug) { + printf("Output XML:\n"); + printXMLBlock(outTree); + } return NO_ERROR; } @@ -850,11 +875,13 @@ void XMLNode::setAttributeResID(size_t attrIdx, uint32_t resId) } else { mAttributeOrder.removeItem(e.index); } - NOISY(printf("Elem %s %s=\"%s\": set res id = 0x%08x\n", - String8(getElementName()).string(), - String8(mAttributes.itemAt(attrIdx).name).string(), - String8(mAttributes.itemAt(attrIdx).string).string(), - resId)); + if (kIsDebug) { + printf("Elem %s %s=\"%s\": set res id = 0x%08x\n", + String8(getElementName()).string(), + String8(mAttributes.itemAt(attrIdx).name).string(), + String8(mAttributes.itemAt(attrIdx).string).string(), + resId); + } mAttributes.editItemAt(attrIdx).nameResId = resId; mAttributeOrder.add(resId, attrIdx); } @@ -965,9 +992,11 @@ status_t XMLNode::parseValues(const sp<AaptAssets>& assets, e.nameResId, NULL, &defPackage, table, &ac)) { hasErrors = true; } - NOISY(printf("Attr %s: type=0x%x, str=%s\n", - String8(e.name).string(), e.value.dataType, - String8(e.string).string())); + if (kIsDebug) { + printf("Attr %s: type=0x%x, str=%s\n", + String8(e.name).string(), e.value.dataType, + String8(e.string).string()); + } } } const size_t N = mChildren.size(); @@ -977,7 +1006,7 @@ status_t XMLNode::parseValues(const sp<AaptAssets>& assets, hasErrors = true; } } - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets, @@ -992,15 +1021,17 @@ status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets, for (size_t i=0; i<N; i++) { const attribute_entry& e = mAttributes.itemAt(i); if (e.ns.size() <= 0) continue; - bool nsIsPublic; + bool nsIsPublic = true; String16 pkg(getNamespaceResourcePackage(String16(assets->getPackage()), e.ns, &nsIsPublic)); - NOISY(printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n", - String8(getElementName()).string(), - String8(e.name).string(), - String8(e.string).string(), - String8(e.ns).string(), - (nsIsPublic) ? "public" : "private", - String8(pkg).string())); + if (kIsDebug) { + printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n", + String8(getElementName()).string(), + String8(e.name).string(), + String8(e.string).string(), + String8(e.ns).string(), + (nsIsPublic) ? "public" : "private", + String8(pkg).string()); + } if (pkg.size() <= 0) continue; uint32_t res = table != NULL ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic) @@ -1009,8 +1040,10 @@ status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets, attr.string(), attr.size(), pkg.string(), pkg.size()); if (res != 0) { - NOISY(printf("XML attribute name %s: resid=0x%08x\n", - String8(e.name).string(), res)); + if (kIsDebug) { + printf("XML attribute name %s: resid=0x%08x\n", + String8(e.name).string(), res); + } setAttributeResID(i, res); } else { SourcePos(mFilename, getStartLineNumber()).error( @@ -1028,7 +1061,7 @@ status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets, } } - return hasErrors ? UNKNOWN_ERROR : NO_ERROR; + return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR; } sp<XMLNode> XMLNode::clone() const { @@ -1070,18 +1103,7 @@ status_t XMLNode::flatten(const sp<AaptFile>& dest, // Next collect all remainibng strings. collect_strings(&strings, &resids, stripComments, stripRawValues); -#if 0 // No longer compiles - NOISY(printf("Found strings:\n"); - const size_t N = strings.size(); - for (size_t i=0; i<N; i++) { - printf("%s\n", String8(strings.entryAt(i).string).string()); - } - ); -#endif - sp<AaptFile> stringPool = strings.createStringBlock(); - NOISY(aout << "String pool:" - << HexDump(stringPool->getData(), stringPool->getSize()) << endl); ResXMLTree_header header; memset(&header, 0, sizeof(header)); @@ -1112,17 +1134,13 @@ status_t XMLNode::flatten(const sp<AaptFile>& dest, void* data = dest->editData(); ResXMLTree_header* hd = (ResXMLTree_header*)(((uint8_t*)data)+basePos); - size_t size = dest->getSize()-basePos; hd->header.size = htodl(dest->getSize()-basePos); - NOISY(aout << "XML resource:" - << HexDump(dest->getData(), dest->getSize()) << endl); - - #if PRINT_STRING_METRICS - fprintf(stderr, "**** total xml size: %d / %d%% strings (in %s)\n", - dest->getSize(), (stringPool->getSize()*100)/dest->getSize(), - dest->getPath().string()); - #endif + if (kPrintStringMetrics) { + fprintf(stderr, "**** total xml size: %zu / %zu%% strings (in %s)\n", + dest->getSize(), (stringPool->getSize()*100)/dest->getSize(), + dest->getPath().string()); + } return NO_ERROR; } @@ -1195,7 +1213,9 @@ static void splitName(const char* name, String16* outNs, String16* outName) void XMLCALL XMLNode::startNamespace(void *userData, const char *prefix, const char *uri) { - NOISY_PARSE(printf("Start Namespace: %s %s\n", prefix, uri)); + if (kIsDebugParse) { + printf("Start Namespace: %s %s\n", prefix, uri); + } ParseState* st = (ParseState*)userData; sp<XMLNode> node = XMLNode::newNamespace(st->filename, String16(prefix != NULL ? prefix : ""), String16(uri)); @@ -1211,7 +1231,9 @@ XMLNode::startNamespace(void *userData, const char *prefix, const char *uri) void XMLCALL XMLNode::startElement(void *userData, const char *name, const char **atts) { - NOISY_PARSE(printf("Start Element: %s\n", name)); + if (kIsDebugParse) { + printf("Start Element: %s\n", name); + } ParseState* st = (ParseState*)userData; String16 ns16, name16; splitName(name, &ns16, &name16); @@ -1237,7 +1259,9 @@ XMLNode::startElement(void *userData, const char *name, const char **atts) void XMLCALL XMLNode::characterData(void *userData, const XML_Char *s, int len) { - NOISY_PARSE(printf("CDATA: \"%s\"\n", String8(s, len).string())); + if (kIsDebugParse) { + printf("CDATA: \"%s\"\n", String8(s, len).string()); + } ParseState* st = (ParseState*)userData; sp<XMLNode> node = NULL; if (st->stack.size() == 0) { @@ -1264,7 +1288,9 @@ XMLNode::characterData(void *userData, const XML_Char *s, int len) void XMLCALL XMLNode::endElement(void *userData, const char *name) { - NOISY_PARSE(printf("End Element: %s\n", name)); + if (kIsDebugParse) { + printf("End Element: %s\n", name); + } ParseState* st = (ParseState*)userData; sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1); node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser)); @@ -1284,7 +1310,9 @@ void XMLCALL XMLNode::endNamespace(void *userData, const char *prefix) { const char* nonNullPrefix = prefix != NULL ? prefix : ""; - NOISY_PARSE(printf("End Namespace: %s\n", prefix)); + if (kIsDebugParse) { + printf("End Namespace: %s\n", prefix); + } ParseState* st = (ParseState*)userData; sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1); node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser)); @@ -1296,7 +1324,9 @@ XMLNode::endNamespace(void *userData, const char *prefix) void XMLCALL XMLNode::commentData(void *userData, const char *comment) { - NOISY_PARSE(printf("Comment: %s\n", comment)); + if (kIsDebugParse) { + printf("Comment: %s\n", comment); + } ParseState* st = (ParseState*)userData; if (st->pendingComment.size() > 0) { st->pendingComment.append(String16("\n")); @@ -1393,8 +1423,10 @@ status_t XMLNode::collect_attr_strings(StringPool* outPool, } if (idx < 0) { idx = outPool->add(attr.name); - NOISY(printf("Adding attr %s (resid 0x%08x) to pool: idx=%d\n", - String8(attr.name).string(), id, idx)); + if (kIsDebug) { + printf("Adding attr %s (resid 0x%08x) to pool: idx=%zd\n", + String8(attr.name).string(), id, SSIZE(idx)); + } if (id != 0) { while ((ssize_t)outResIds->size() <= idx) { outResIds->add(0); @@ -1403,8 +1435,9 @@ status_t XMLNode::collect_attr_strings(StringPool* outPool, } } attr.namePoolIdx = idx; - NOISY(printf("String %s offset=0x%08x\n", - String8(attr.name).string(), idx)); + if (kIsDebug) { + printf("String %s offset=0x%08zd\n", String8(attr.name).string(), SSIZE(idx)); + } } } diff --git a/tools/aapt/ZipEntry.cpp b/tools/aapt/ZipEntry.cpp index b575988..f97f604 100644 --- a/tools/aapt/ZipEntry.cpp +++ b/tools/aapt/ZipEntry.cpp @@ -141,33 +141,15 @@ void ZipEntry::initNew(const char* fileName, const char* comment) * * Initializes the CDE and the LFH. */ -status_t ZipEntry::initFromExternal(const ZipFile* pZipFile, +status_t ZipEntry::initFromExternal(const ZipFile* /* pZipFile */, const ZipEntry* pEntry) { - /* - * Copy everything in the CDE over, then fix up the hairy bits. - */ - memcpy(&mCDE, &pEntry->mCDE, sizeof(mCDE)); - - if (mCDE.mFileNameLength > 0) { - mCDE.mFileName = new unsigned char[mCDE.mFileNameLength+1]; - if (mCDE.mFileName == NULL) - return NO_MEMORY; - strcpy((char*) mCDE.mFileName, (char*)pEntry->mCDE.mFileName); - } - if (mCDE.mFileCommentLength > 0) { - mCDE.mFileComment = new unsigned char[mCDE.mFileCommentLength+1]; - if (mCDE.mFileComment == NULL) - return NO_MEMORY; - strcpy((char*) mCDE.mFileComment, (char*)pEntry->mCDE.mFileComment); - } - if (mCDE.mExtraFieldLength > 0) { - /* we null-terminate this, though it may not be a string */ - mCDE.mExtraField = new unsigned char[mCDE.mExtraFieldLength+1]; - if (mCDE.mExtraField == NULL) - return NO_MEMORY; - memcpy(mCDE.mExtraField, pEntry->mCDE.mExtraField, - mCDE.mExtraFieldLength+1); + mCDE = pEntry->mCDE; + // Check whether we got all the memory needed. + if ((mCDE.mFileNameLength > 0 && mCDE.mFileName == NULL) || + (mCDE.mFileCommentLength > 0 && mCDE.mFileComment == NULL) || + (mCDE.mExtraFieldLength > 0 && mCDE.mExtraField == NULL)) { + return NO_MEMORY; } /* construct the LFH from the CDE */ @@ -694,3 +676,60 @@ void ZipEntry::CentralDirEntry::dump(void) const ALOGD(" comment: '%s'\n", mFileComment); } +/* + * Copy-assignment operator for CentralDirEntry. + */ +ZipEntry::CentralDirEntry& ZipEntry::CentralDirEntry::operator=(const ZipEntry::CentralDirEntry& src) { + if (this == &src) { + return *this; + } + + // Free up old data. + delete[] mFileName; + delete[] mExtraField; + delete[] mFileComment; + + // Copy scalars. + mVersionMadeBy = src.mVersionMadeBy; + mVersionToExtract = src.mVersionToExtract; + mGPBitFlag = src.mGPBitFlag; + mCompressionMethod = src.mCompressionMethod; + mLastModFileTime = src.mLastModFileTime; + mLastModFileDate = src.mLastModFileDate; + mCRC32 = src.mCRC32; + mCompressedSize = src.mCompressedSize; + mUncompressedSize = src.mUncompressedSize; + mFileNameLength = src.mFileNameLength; + mExtraFieldLength = src.mExtraFieldLength; + mFileCommentLength = src.mFileCommentLength; + mDiskNumberStart = src.mDiskNumberStart; + mInternalAttrs = src.mInternalAttrs; + mExternalAttrs = src.mExternalAttrs; + mLocalHeaderRelOffset = src.mLocalHeaderRelOffset; + + // Copy strings, if necessary. + if (mFileNameLength > 0) { + mFileName = new unsigned char[mFileNameLength + 1]; + if (mFileName != NULL) + strcpy((char*)mFileName, (char*)src.mFileName); + } else { + mFileName = NULL; + } + if (mFileCommentLength > 0) { + mFileComment = new unsigned char[mFileCommentLength + 1]; + if (mFileComment != NULL) + strcpy((char*)mFileComment, (char*)src.mFileComment); + } else { + mFileComment = NULL; + } + if (mExtraFieldLength > 0) { + /* we null-terminate this, though it may not be a string */ + mExtraField = new unsigned char[mExtraFieldLength + 1]; + if (mExtraField != NULL) + memcpy(mExtraField, src.mExtraField, mExtraFieldLength + 1); + } else { + mExtraField = NULL; + } + + return *this; +} diff --git a/tools/aapt/ZipEntry.h b/tools/aapt/ZipEntry.h index c2f3227..287a540 100644 --- a/tools/aapt/ZipEntry.h +++ b/tools/aapt/ZipEntry.h @@ -298,6 +298,8 @@ private: status_t read(FILE* fp); status_t write(FILE* fp); + CentralDirEntry& operator=(const CentralDirEntry& src); + // unsigned long mSignature; unsigned short mVersionMadeBy; unsigned short mVersionToExtract; diff --git a/tools/aapt/ZipFile.cpp b/tools/aapt/ZipFile.cpp index 8057068..36f4e73 100644 --- a/tools/aapt/ZipFile.cpp +++ b/tools/aapt/ZipFile.cpp @@ -676,8 +676,6 @@ status_t ZipFile::copyFpToFp(FILE* dstFp, FILE* srcFp, unsigned long* pCRC32) status_t ZipFile::copyDataToFp(FILE* dstFp, const void* data, size_t size, unsigned long* pCRC32) { - size_t count; - *pCRC32 = crc32(0L, Z_NULL, 0); if (size > 0) { *pCRC32 = crc32(*pCRC32, (const unsigned char*)data, size); diff --git a/tools/aapt/qsort_r_compat.c b/tools/aapt/qsort_r_compat.c deleted file mode 100644 index 2a8dbe8..0000000 --- a/tools/aapt/qsort_r_compat.c +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include <stdlib.h> -#include "qsort_r_compat.h" - -/* - * Note: This code is only used on the host, and is primarily here for - * Mac OS compatibility. Apparently, glibc and Apple's libc disagree on - * the parameter order for qsort_r. - */ - -#if HAVE_BSD_QSORT_R - -/* - * BSD qsort_r parameter order is as we have defined here. - */ - -void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk, - int (*compar)(void*, const void* , const void*)) { - qsort_r(base, nel, width, thunk, compar); -} - -#elif HAVE_GNU_QSORT_R - -/* - * GNU qsort_r parameter order places the thunk parameter last. - */ - -struct compar_data { - void* thunk; - int (*compar)(void*, const void* , const void*); -}; - -static int compar_wrapper(const void* a, const void* b, void* data) { - struct compar_data* compar_data = (struct compar_data*)data; - return compar_data->compar(compar_data->thunk, a, b); -} - -void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk, - int (*compar)(void*, const void* , const void*)) { - struct compar_data compar_data; - compar_data.thunk = thunk; - compar_data.compar = compar; - qsort_r(base, nel, width, compar_wrapper, &compar_data); -} - -#else - -/* - * Emulate qsort_r using thread local storage to access the thunk data. - */ - -#include <cutils/threads.h> - -static thread_store_t compar_data_key = THREAD_STORE_INITIALIZER; - -struct compar_data { - void* thunk; - int (*compar)(void*, const void* , const void*); -}; - -static int compar_wrapper(const void* a, const void* b) { - struct compar_data* compar_data = (struct compar_data*)thread_store_get(&compar_data_key); - return compar_data->compar(compar_data->thunk, a, b); -} - -void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk, - int (*compar)(void*, const void* , const void*)) { - struct compar_data compar_data; - compar_data.thunk = thunk; - compar_data.compar = compar; - thread_store_set(&compar_data_key, &compar_data, NULL); - qsort(base, nel, width, compar_wrapper); -} - -#endif diff --git a/tools/aapt/qsort_r_compat.h b/tools/aapt/qsort_r_compat.h deleted file mode 100644 index e14f999..0000000 --- a/tools/aapt/qsort_r_compat.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Provides a portable version of qsort_r, called qsort_r_compat, which is a - * reentrant variant of qsort that passes a user data pointer to its comparator. - * This implementation follows the BSD parameter convention. - */ - -#ifndef ___QSORT_R_COMPAT_H -#define ___QSORT_R_COMPAT_H - -#include <stdlib.h> - -#ifdef __cplusplus -extern "C" { -#endif - -void qsort_r_compat(void* base, size_t nel, size_t width, void* thunk, - int (*compar)(void*, const void* , const void* )); - -#ifdef __cplusplus -} -#endif - -#endif // ___QSORT_R_COMPAT_H |