Package.cpp revision b711f3f7ee0544685ef26a1a4b4755d5a6233dba
1// 2// Copyright 2006 The Android Open Source Project 3// 4// Package assets into Zip files. 5// 6#include "Main.h" 7#include "AaptAssets.h" 8#include "ResourceTable.h" 9 10#include <utils/Log.h> 11#include <utils/threads.h> 12#include <utils/List.h> 13#include <utils/Errors.h> 14 15#include <sys/types.h> 16#include <dirent.h> 17#include <ctype.h> 18#include <errno.h> 19 20using namespace android; 21 22static const char* kExcludeExtension = ".EXCLUDE"; 23 24/* these formats are already compressed, or don't compress well */ 25static const char* kNoCompressExt[] = { 26 ".jpg", ".jpeg", ".png", ".gif", 27 ".wav", ".mp2", ".mp3", ".ogg", ".aac", 28 ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", 29 ".rtttl", ".imy", ".xmf", ".mp4", ".m4a", 30 ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", 31 ".amr", ".awb", ".wma", ".wmv" 32}; 33 34/* fwd decls, so I can write this downward */ 35ssize_t processAssets(Bundle* bundle, ZipFile* zip, const sp<AaptAssets>& assets); 36ssize_t processAssets(Bundle* bundle, ZipFile* zip, 37 const sp<AaptDir>& dir, const AaptGroupEntry& ge); 38bool processFile(Bundle* bundle, ZipFile* zip, 39 const sp<AaptGroup>& group, const sp<AaptFile>& file); 40bool okayToCompress(Bundle* bundle, const String8& pathName); 41ssize_t processJarFiles(Bundle* bundle, ZipFile* zip); 42 43/* 44 * The directory hierarchy looks like this: 45 * "outputDir" and "assetRoot" are existing directories. 46 * 47 * On success, "bundle->numPackages" will be the number of Zip packages 48 * we created. 49 */ 50status_t writeAPK(Bundle* bundle, const sp<AaptAssets>& assets, 51 const String8& outputFile) 52{ 53 #if BENCHMARK 54 fprintf(stdout, "BENCHMARK: Starting APK Bundling \n"); 55 long startAPKTime = clock(); 56 #endif /* BENCHMARK */ 57 58 status_t result = NO_ERROR; 59 ZipFile* zip = NULL; 60 int count; 61 62 //bundle->setPackageCount(0); 63 64 /* 65 * Prep the Zip archive. 66 * 67 * If the file already exists, fail unless "update" or "force" is set. 68 * If "update" is set, update the contents of the existing archive. 69 * Else, if "force" is set, remove the existing archive. 70 */ 71 FileType fileType = getFileType(outputFile.string()); 72 if (fileType == kFileTypeNonexistent) { 73 // okay, create it below 74 } else if (fileType == kFileTypeRegular) { 75 if (bundle->getUpdate()) { 76 // okay, open it below 77 } else if (bundle->getForce()) { 78 if (unlink(outputFile.string()) != 0) { 79 fprintf(stderr, "ERROR: unable to remove '%s': %s\n", outputFile.string(), 80 strerror(errno)); 81 goto bail; 82 } 83 } else { 84 fprintf(stderr, "ERROR: '%s' exists (use '-f' to force overwrite)\n", 85 outputFile.string()); 86 goto bail; 87 } 88 } else { 89 fprintf(stderr, "ERROR: '%s' exists and is not a regular file\n", outputFile.string()); 90 goto bail; 91 } 92 93 if (bundle->getVerbose()) { 94 printf("%s '%s'\n", (fileType == kFileTypeNonexistent) ? "Creating" : "Opening", 95 outputFile.string()); 96 } 97 98 status_t status; 99 zip = new ZipFile; 100 status = zip->open(outputFile.string(), ZipFile::kOpenReadWrite | ZipFile::kOpenCreate); 101 if (status != NO_ERROR) { 102 fprintf(stderr, "ERROR: unable to open '%s' as Zip file for writing\n", 103 outputFile.string()); 104 goto bail; 105 } 106 107 if (bundle->getVerbose()) { 108 printf("Writing all files...\n"); 109 } 110 111 count = processAssets(bundle, zip, assets); 112 if (count < 0) { 113 fprintf(stderr, "ERROR: unable to process assets while packaging '%s'\n", 114 outputFile.string()); 115 result = count; 116 goto bail; 117 } 118 119 if (bundle->getVerbose()) { 120 printf("Generated %d file%s\n", count, (count==1) ? "" : "s"); 121 } 122 123 count = processJarFiles(bundle, zip); 124 if (count < 0) { 125 fprintf(stderr, "ERROR: unable to process jar files while packaging '%s'\n", 126 outputFile.string()); 127 result = count; 128 goto bail; 129 } 130 131 if (bundle->getVerbose()) 132 printf("Included %d file%s from jar/zip files.\n", count, (count==1) ? "" : "s"); 133 134 result = NO_ERROR; 135 136 /* 137 * Check for cruft. We set the "marked" flag on all entries we created 138 * or decided not to update. If the entry isn't already slated for 139 * deletion, remove it now. 140 */ 141 { 142 if (bundle->getVerbose()) 143 printf("Checking for deleted files\n"); 144 int i, removed = 0; 145 for (i = 0; i < zip->getNumEntries(); i++) { 146 ZipEntry* entry = zip->getEntryByIndex(i); 147 148 if (!entry->getMarked() && entry->getDeleted()) { 149 if (bundle->getVerbose()) { 150 printf(" (removing crufty '%s')\n", 151 entry->getFileName()); 152 } 153 zip->remove(entry); 154 removed++; 155 } 156 } 157 if (bundle->getVerbose() && removed > 0) 158 printf("Removed %d file%s\n", removed, (removed==1) ? "" : "s"); 159 } 160 161 /* tell Zip lib to process deletions and other pending changes */ 162 result = zip->flush(); 163 if (result != NO_ERROR) { 164 fprintf(stderr, "ERROR: Zip flush failed, archive may be hosed\n"); 165 goto bail; 166 } 167 168 /* anything here? */ 169 if (zip->getNumEntries() == 0) { 170 if (bundle->getVerbose()) { 171 printf("Archive is empty -- removing %s\n", outputFile.getPathLeaf().string()); 172 } 173 delete zip; // close the file so we can remove it in Win32 174 zip = NULL; 175 if (unlink(outputFile.string()) != 0) { 176 fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string()); 177 } 178 } 179 180 // If we've been asked to generate a dependency file for the .ap_ package, 181 // do so here 182 if (bundle->getGenDependencies()) { 183 // The dependency file gets output to the same directory 184 // as the specified output file with an additional .d extension. 185 // e.g. bin/resources.ap_.d 186 String8 dependencyFile = outputFile; 187 dependencyFile.append(".d"); 188 189 FILE* fp = fopen(dependencyFile.string(), "a"); 190 // Add this file to the dependency file 191 fprintf(fp, "%s \\\n", outputFile.string()); 192 fclose(fp); 193 } 194 195 assert(result == NO_ERROR); 196 197bail: 198 delete zip; // must close before remove in Win32 199 if (result != NO_ERROR) { 200 if (bundle->getVerbose()) { 201 printf("Removing %s due to earlier failures\n", outputFile.string()); 202 } 203 if (unlink(outputFile.string()) != 0) { 204 fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string()); 205 } 206 } 207 208 if (result == NO_ERROR && bundle->getVerbose()) 209 printf("Done!\n"); 210 211 #if BENCHMARK 212 fprintf(stdout, "BENCHMARK: End APK Bundling. Time Elapsed: %f ms \n",(clock() - startAPKTime)/1000.0); 213 #endif /* BENCHMARK */ 214 return result; 215} 216 217ssize_t processAssets(Bundle* bundle, ZipFile* zip, 218 const sp<AaptAssets>& assets) 219{ 220 ResourceFilter filter; 221 status_t status = filter.parse(bundle->getConfigurations()); 222 if (status != NO_ERROR) { 223 return -1; 224 } 225 226 ssize_t count = 0; 227 228 const size_t N = assets->getGroupEntries().size(); 229 for (size_t i=0; i<N; i++) { 230 const AaptGroupEntry& ge = assets->getGroupEntries()[i]; 231 if (!filter.match(ge.toParams())) { 232 continue; 233 } 234 ssize_t res = processAssets(bundle, zip, assets, ge); 235 if (res < 0) { 236 return res; 237 } 238 count += res; 239 } 240 241 return count; 242} 243 244ssize_t processAssets(Bundle* bundle, ZipFile* zip, 245 const sp<AaptDir>& dir, const AaptGroupEntry& ge) 246{ 247 ssize_t count = 0; 248 249 const size_t ND = dir->getDirs().size(); 250 size_t i; 251 for (i=0; i<ND; i++) { 252 ssize_t res = processAssets(bundle, zip, dir->getDirs().valueAt(i), ge); 253 if (res < 0) { 254 return res; 255 } 256 count += res; 257 } 258 259 const size_t NF = dir->getFiles().size(); 260 for (i=0; i<NF; i++) { 261 sp<AaptGroup> gp = dir->getFiles().valueAt(i); 262 ssize_t fi = gp->getFiles().indexOfKey(ge); 263 if (fi >= 0) { 264 sp<AaptFile> fl = gp->getFiles().valueAt(fi); 265 if (!processFile(bundle, zip, gp, fl)) { 266 return UNKNOWN_ERROR; 267 } 268 count++; 269 } 270 } 271 272 return count; 273} 274 275/* 276 * Process a regular file, adding it to the archive if appropriate. 277 * 278 * If we're in "update" mode, and the file already exists in the archive, 279 * delete the existing entry before adding the new one. 280 */ 281bool processFile(Bundle* bundle, ZipFile* zip, 282 const sp<AaptGroup>& group, const sp<AaptFile>& file) 283{ 284 const bool hasData = file->hasData(); 285 286 String8 storageName(group->getPath()); 287 storageName.convertToResPath(); 288 ZipEntry* entry; 289 bool fromGzip = false; 290 status_t result; 291 292 /* 293 * See if the filename ends in ".EXCLUDE". We can't use 294 * String8::getPathExtension() because the length of what it considers 295 * to be an extension is capped. 296 * 297 * The Asset Manager doesn't check for ".EXCLUDE" in Zip archives, 298 * so there's no value in adding them (and it makes life easier on 299 * the AssetManager lib if we don't). 300 * 301 * NOTE: this restriction has been removed. If you're in this code, you 302 * should clean this up, but I'm in here getting rid of Path Name, and I 303 * don't want to make other potentially breaking changes --joeo 304 */ 305 int fileNameLen = storageName.length(); 306 int excludeExtensionLen = strlen(kExcludeExtension); 307 if (fileNameLen > excludeExtensionLen 308 && (0 == strcmp(storageName.string() + (fileNameLen - excludeExtensionLen), 309 kExcludeExtension))) { 310 fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.string()); 311 return true; 312 } 313 314 if (strcasecmp(storageName.getPathExtension().string(), ".gz") == 0) { 315 fromGzip = true; 316 storageName = storageName.getBasePath(); 317 } 318 319 if (bundle->getUpdate()) { 320 entry = zip->getEntryByName(storageName.string()); 321 if (entry != NULL) { 322 /* file already exists in archive; there can be only one */ 323 if (entry->getMarked()) { 324 fprintf(stderr, 325 "ERROR: '%s' exists twice (check for with & w/o '.gz'?)\n", 326 file->getPrintableSource().string()); 327 return false; 328 } 329 if (!hasData) { 330 const String8& srcName = file->getSourceFile(); 331 time_t fileModWhen; 332 fileModWhen = getFileModDate(srcName.string()); 333 if (fileModWhen == (time_t) -1) { // file existence tested earlier, 334 return false; // not expecting an error here 335 } 336 337 if (fileModWhen > entry->getModWhen()) { 338 // mark as deleted so add() will succeed 339 if (bundle->getVerbose()) { 340 printf(" (removing old '%s')\n", storageName.string()); 341 } 342 343 zip->remove(entry); 344 } else { 345 // version in archive is newer 346 if (bundle->getVerbose()) { 347 printf(" (not updating '%s')\n", storageName.string()); 348 } 349 entry->setMarked(true); 350 return true; 351 } 352 } else { 353 // Generated files are always replaced. 354 zip->remove(entry); 355 } 356 } 357 } 358 359 //android_setMinPriority(NULL, ANDROID_LOG_VERBOSE); 360 361 if (fromGzip) { 362 result = zip->addGzip(file->getSourceFile().string(), storageName.string(), &entry); 363 } else if (!hasData) { 364 /* don't compress certain files, e.g. PNGs */ 365 int compressionMethod = bundle->getCompressionMethod(); 366 if (!okayToCompress(bundle, storageName)) { 367 compressionMethod = ZipEntry::kCompressStored; 368 } 369 result = zip->add(file->getSourceFile().string(), storageName.string(), compressionMethod, 370 &entry); 371 } else { 372 result = zip->add(file->getData(), file->getSize(), storageName.string(), 373 file->getCompressionMethod(), &entry); 374 } 375 if (result == NO_ERROR) { 376 if (bundle->getVerbose()) { 377 printf(" '%s'%s", storageName.string(), fromGzip ? " (from .gz)" : ""); 378 if (entry->getCompressionMethod() == ZipEntry::kCompressStored) { 379 printf(" (not compressed)\n"); 380 } else { 381 printf(" (compressed %d%%)\n", calcPercent(entry->getUncompressedLen(), 382 entry->getCompressedLen())); 383 } 384 } 385 entry->setMarked(true); 386 } else { 387 if (result == ALREADY_EXISTS) { 388 fprintf(stderr, " Unable to add '%s': file already in archive (try '-u'?)\n", 389 file->getPrintableSource().string()); 390 } else { 391 fprintf(stderr, " Unable to add '%s': Zip add failed\n", 392 file->getPrintableSource().string()); 393 } 394 return false; 395 } 396 397 return true; 398} 399 400/* 401 * Determine whether or not we want to try to compress this file based 402 * on the file extension. 403 */ 404bool okayToCompress(Bundle* bundle, const String8& pathName) 405{ 406 String8 ext = pathName.getPathExtension(); 407 int i; 408 409 if (ext.length() == 0) 410 return true; 411 412 for (i = 0; i < NELEM(kNoCompressExt); i++) { 413 if (strcasecmp(ext.string(), kNoCompressExt[i]) == 0) 414 return false; 415 } 416 417 const android::Vector<const char*>& others(bundle->getNoCompressExtensions()); 418 for (i = 0; i < (int)others.size(); i++) { 419 const char* str = others[i]; 420 int pos = pathName.length() - strlen(str); 421 if (pos < 0) { 422 continue; 423 } 424 const char* path = pathName.string(); 425 if (strcasecmp(path + pos, str) == 0) { 426 return false; 427 } 428 } 429 430 return true; 431} 432 433bool endsWith(const char* haystack, const char* needle) 434{ 435 size_t a = strlen(haystack); 436 size_t b = strlen(needle); 437 if (a < b) return false; 438 return strcasecmp(haystack+(a-b), needle) == 0; 439} 440 441ssize_t processJarFile(ZipFile* jar, ZipFile* out) 442{ 443 status_t err; 444 size_t N = jar->getNumEntries(); 445 size_t count = 0; 446 for (size_t i=0; i<N; i++) { 447 ZipEntry* entry = jar->getEntryByIndex(i); 448 const char* storageName = entry->getFileName(); 449 if (endsWith(storageName, ".class")) { 450 int compressionMethod = entry->getCompressionMethod(); 451 size_t size = entry->getUncompressedLen(); 452 const void* data = jar->uncompress(entry); 453 if (data == NULL) { 454 fprintf(stderr, "ERROR: unable to uncompress entry '%s'\n", 455 storageName); 456 return -1; 457 } 458 out->add(data, size, storageName, compressionMethod, NULL); 459 free((void*)data); 460 } 461 count++; 462 } 463 return count; 464} 465 466ssize_t processJarFiles(Bundle* bundle, ZipFile* zip) 467{ 468 ssize_t err; 469 ssize_t count = 0; 470 const android::Vector<const char*>& jars = bundle->getJarFiles(); 471 472 size_t N = jars.size(); 473 for (size_t i=0; i<N; i++) { 474 ZipFile jar; 475 err = jar.open(jars[i], ZipFile::kOpenReadOnly); 476 if (err != 0) { 477 fprintf(stderr, "ERROR: unable to open '%s' as a zip file: %zd\n", 478 jars[i], err); 479 return err; 480 } 481 err += processJarFile(&jar, zip); 482 if (err < 0) { 483 fprintf(stderr, "ERROR: unable to process '%s'\n", jars[i]); 484 return err; 485 } 486 count += err; 487 } 488 489 return count; 490} 491