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