Package.cpp revision 8a39da80b33691b0c82458c3b7727e13ff71277e
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 (bundle->getGenDependencies()) { 181 // Add this file to the dependency file 182 String8 dependencyFile = outputFile.getBasePath(); 183 dependencyFile.append(".d"); 184 185 FILE* fp = fopen(dependencyFile.string(), "a"); 186 fprintf(fp, "%s \\\n", outputFile.string()); 187 fclose(fp); 188 } 189 190 assert(result == NO_ERROR); 191 192bail: 193 delete zip; // must close before remove in Win32 194 if (result != NO_ERROR) { 195 if (bundle->getVerbose()) { 196 printf("Removing %s due to earlier failures\n", outputFile.string()); 197 } 198 if (unlink(outputFile.string()) != 0) { 199 fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string()); 200 } 201 } 202 203 if (result == NO_ERROR && bundle->getVerbose()) 204 printf("Done!\n"); 205 206 #if BENCHMARK 207 fprintf(stdout, "BENCHMARK: End APK Bundling. Time Elapsed: %f ms \n",(clock() - startAPKTime)/1000.0); 208 #endif /* BENCHMARK */ 209 return result; 210} 211 212ssize_t processAssets(Bundle* bundle, ZipFile* zip, 213 const sp<AaptAssets>& assets) 214{ 215 ResourceFilter filter; 216 status_t status = filter.parse(bundle->getConfigurations()); 217 if (status != NO_ERROR) { 218 return -1; 219 } 220 221 ssize_t count = 0; 222 223 const size_t N = assets->getGroupEntries().size(); 224 for (size_t i=0; i<N; i++) { 225 const AaptGroupEntry& ge = assets->getGroupEntries()[i]; 226 if (!filter.match(ge.toParams())) { 227 continue; 228 } 229 ssize_t res = processAssets(bundle, zip, assets, ge); 230 if (res < 0) { 231 return res; 232 } 233 count += res; 234 } 235 236 return count; 237} 238 239ssize_t processAssets(Bundle* bundle, ZipFile* zip, 240 const sp<AaptDir>& dir, const AaptGroupEntry& ge) 241{ 242 ssize_t count = 0; 243 244 const size_t ND = dir->getDirs().size(); 245 size_t i; 246 for (i=0; i<ND; i++) { 247 ssize_t res = processAssets(bundle, zip, dir->getDirs().valueAt(i), ge); 248 if (res < 0) { 249 return res; 250 } 251 count += res; 252 } 253 254 const size_t NF = dir->getFiles().size(); 255 for (i=0; i<NF; i++) { 256 sp<AaptGroup> gp = dir->getFiles().valueAt(i); 257 ssize_t fi = gp->getFiles().indexOfKey(ge); 258 if (fi >= 0) { 259 sp<AaptFile> fl = gp->getFiles().valueAt(fi); 260 if (!processFile(bundle, zip, gp, fl)) { 261 return UNKNOWN_ERROR; 262 } 263 count++; 264 } 265 } 266 267 return count; 268} 269 270/* 271 * Process a regular file, adding it to the archive if appropriate. 272 * 273 * If we're in "update" mode, and the file already exists in the archive, 274 * delete the existing entry before adding the new one. 275 */ 276bool processFile(Bundle* bundle, ZipFile* zip, 277 const sp<AaptGroup>& group, const sp<AaptFile>& file) 278{ 279 const bool hasData = file->hasData(); 280 281 String8 storageName(group->getPath()); 282 storageName.convertToResPath(); 283 ZipEntry* entry; 284 bool fromGzip = false; 285 status_t result; 286 287 /* 288 * See if the filename ends in ".EXCLUDE". We can't use 289 * String8::getPathExtension() because the length of what it considers 290 * to be an extension is capped. 291 * 292 * The Asset Manager doesn't check for ".EXCLUDE" in Zip archives, 293 * so there's no value in adding them (and it makes life easier on 294 * the AssetManager lib if we don't). 295 * 296 * NOTE: this restriction has been removed. If you're in this code, you 297 * should clean this up, but I'm in here getting rid of Path Name, and I 298 * don't want to make other potentially breaking changes --joeo 299 */ 300 int fileNameLen = storageName.length(); 301 int excludeExtensionLen = strlen(kExcludeExtension); 302 if (fileNameLen > excludeExtensionLen 303 && (0 == strcmp(storageName.string() + (fileNameLen - excludeExtensionLen), 304 kExcludeExtension))) { 305 fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.string()); 306 return true; 307 } 308 309 if (strcasecmp(storageName.getPathExtension().string(), ".gz") == 0) { 310 fromGzip = true; 311 storageName = storageName.getBasePath(); 312 } 313 314 if (bundle->getUpdate()) { 315 entry = zip->getEntryByName(storageName.string()); 316 if (entry != NULL) { 317 /* file already exists in archive; there can be only one */ 318 if (entry->getMarked()) { 319 fprintf(stderr, 320 "ERROR: '%s' exists twice (check for with & w/o '.gz'?)\n", 321 file->getPrintableSource().string()); 322 return false; 323 } 324 if (!hasData) { 325 const String8& srcName = file->getSourceFile(); 326 time_t fileModWhen; 327 fileModWhen = getFileModDate(srcName.string()); 328 if (fileModWhen == (time_t) -1) { // file existence tested earlier, 329 return false; // not expecting an error here 330 } 331 332 if (fileModWhen > entry->getModWhen()) { 333 // mark as deleted so add() will succeed 334 if (bundle->getVerbose()) { 335 printf(" (removing old '%s')\n", storageName.string()); 336 } 337 338 zip->remove(entry); 339 } else { 340 // version in archive is newer 341 if (bundle->getVerbose()) { 342 printf(" (not updating '%s')\n", storageName.string()); 343 } 344 entry->setMarked(true); 345 return true; 346 } 347 } else { 348 // Generated files are always replaced. 349 zip->remove(entry); 350 } 351 } 352 } 353 354 //android_setMinPriority(NULL, ANDROID_LOG_VERBOSE); 355 356 if (fromGzip) { 357 result = zip->addGzip(file->getSourceFile().string(), storageName.string(), &entry); 358 } else if (!hasData) { 359 /* don't compress certain files, e.g. PNGs */ 360 int compressionMethod = bundle->getCompressionMethod(); 361 if (!okayToCompress(bundle, storageName)) { 362 compressionMethod = ZipEntry::kCompressStored; 363 } 364 result = zip->add(file->getSourceFile().string(), storageName.string(), compressionMethod, 365 &entry); 366 } else { 367 result = zip->add(file->getData(), file->getSize(), storageName.string(), 368 file->getCompressionMethod(), &entry); 369 } 370 if (result == NO_ERROR) { 371 if (bundle->getVerbose()) { 372 printf(" '%s'%s", storageName.string(), fromGzip ? " (from .gz)" : ""); 373 if (entry->getCompressionMethod() == ZipEntry::kCompressStored) { 374 printf(" (not compressed)\n"); 375 } else { 376 printf(" (compressed %d%%)\n", calcPercent(entry->getUncompressedLen(), 377 entry->getCompressedLen())); 378 } 379 } 380 entry->setMarked(true); 381 } else { 382 if (result == ALREADY_EXISTS) { 383 fprintf(stderr, " Unable to add '%s': file already in archive (try '-u'?)\n", 384 file->getPrintableSource().string()); 385 } else { 386 fprintf(stderr, " Unable to add '%s': Zip add failed\n", 387 file->getPrintableSource().string()); 388 } 389 return false; 390 } 391 392 return true; 393} 394 395/* 396 * Determine whether or not we want to try to compress this file based 397 * on the file extension. 398 */ 399bool okayToCompress(Bundle* bundle, const String8& pathName) 400{ 401 String8 ext = pathName.getPathExtension(); 402 int i; 403 404 if (ext.length() == 0) 405 return true; 406 407 for (i = 0; i < NELEM(kNoCompressExt); i++) { 408 if (strcasecmp(ext.string(), kNoCompressExt[i]) == 0) 409 return false; 410 } 411 412 const android::Vector<const char*>& others(bundle->getNoCompressExtensions()); 413 for (i = 0; i < (int)others.size(); i++) { 414 const char* str = others[i]; 415 int pos = pathName.length() - strlen(str); 416 if (pos < 0) { 417 continue; 418 } 419 const char* path = pathName.string(); 420 if (strcasecmp(path + pos, str) == 0) { 421 return false; 422 } 423 } 424 425 return true; 426} 427 428bool endsWith(const char* haystack, const char* needle) 429{ 430 size_t a = strlen(haystack); 431 size_t b = strlen(needle); 432 if (a < b) return false; 433 return strcasecmp(haystack+(a-b), needle) == 0; 434} 435 436ssize_t processJarFile(ZipFile* jar, ZipFile* out) 437{ 438 status_t err; 439 size_t N = jar->getNumEntries(); 440 size_t count = 0; 441 for (size_t i=0; i<N; i++) { 442 ZipEntry* entry = jar->getEntryByIndex(i); 443 const char* storageName = entry->getFileName(); 444 if (endsWith(storageName, ".class")) { 445 int compressionMethod = entry->getCompressionMethod(); 446 size_t size = entry->getUncompressedLen(); 447 const void* data = jar->uncompress(entry); 448 if (data == NULL) { 449 fprintf(stderr, "ERROR: unable to uncompress entry '%s'\n", 450 storageName); 451 return -1; 452 } 453 out->add(data, size, storageName, compressionMethod, NULL); 454 free((void*)data); 455 } 456 count++; 457 } 458 return count; 459} 460 461ssize_t processJarFiles(Bundle* bundle, ZipFile* zip) 462{ 463 ssize_t err; 464 ssize_t count = 0; 465 const android::Vector<const char*>& jars = bundle->getJarFiles(); 466 467 size_t N = jars.size(); 468 for (size_t i=0; i<N; i++) { 469 ZipFile jar; 470 err = jar.open(jars[i], ZipFile::kOpenReadOnly); 471 if (err != 0) { 472 fprintf(stderr, "ERROR: unable to open '%s' as a zip file: %zd\n", 473 jars[i], err); 474 return err; 475 } 476 err += processJarFile(&jar, zip); 477 if (err < 0) { 478 fprintf(stderr, "ERROR: unable to process '%s'\n", jars[i]); 479 return err; 480 } 481 count += err; 482 } 483 484 return count; 485} 486