2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Read-only access to Zip archives, with minimal heap allocation.
20 #include "ZipArchive.h"
30 #include <JNIHelp.h> // TEMP_FAILURE_RETRY may or may not be in unistd
39 #define kEOCDSignature 0x06054b50
41 #define kEOCDNumEntries 8 // offset to #of entries in file
42 #define kEOCDSize 12 // size of the central directory
43 #define kEOCDFileOffset 16 // offset to central directory
45 #define kMaxCommentLen 65535 // longest possible in ushort
46 #define kMaxEOCDSearch (kMaxCommentLen + kEOCDLen)
48 #define kLFHSignature 0x04034b50
49 #define kLFHLen 30 // excluding variable-len fields
50 #define kLFHNameLen 26 // offset to filename length
51 #define kLFHExtraLen 28 // offset to extra length
53 #define kCDESignature 0x02014b50
54 #define kCDELen 46 // excluding variable-len fields
55 #define kCDEMethod 10 // offset to compression method
56 #define kCDEModWhen 12 // offset to modification timestamp
57 #define kCDECRC 16 // offset to entry CRC
58 #define kCDECompLen 20 // offset to compressed length
59 #define kCDEUncompLen 24 // offset to uncompressed length
60 #define kCDENameLen 28 // offset to filename length
61 #define kCDEExtraLen 30 // offset to extra length
62 #define kCDECommentLen 32 // offset to comment length
63 #define kCDELocalOffset 42 // offset to local hdr
66 * The values we return for ZipEntry use 0 as an invalid value, so we
67 * want to adjust the hash table index by a fixed amount. Using a large
68 * value helps insure that people don't mix & match arguments, e.g. with
71 #define kZipEntryAdj 10000
74 * Convert a ZipEntry to a hash table index, verifying that it's in a
77 static int entryToIndex(const ZipArchive* pArchive, const ZipEntry entry)
79 long ent = ((long) entry) - kZipEntryAdj;
80 if (ent < 0 || ent >= pArchive->mHashTableSize ||
81 pArchive->mHashTable[ent].name == NULL)
83 LOGW("Zip: invalid ZipEntry %p (%ld)\n", entry, ent);
90 * Simple string hash function for non-null-terminated strings.
92 static unsigned int computeHash(const char* str, int len)
94 unsigned int hash = 0;
97 hash = hash * 31 + *str++;
103 * Add a new entry to the hash table.
105 static void addToHash(ZipArchive* pArchive, const char* str, int strLen,
108 const int hashTableSize = pArchive->mHashTableSize;
109 int ent = hash & (hashTableSize - 1);
112 * We over-allocated the table, so we're guaranteed to find an empty slot.
114 while (pArchive->mHashTable[ent].name != NULL)
115 ent = (ent + 1) & (hashTableSize-1);
117 pArchive->mHashTable[ent].name = str;
118 pArchive->mHashTable[ent].nameLen = strLen;
122 * Get 2 little-endian bytes.
124 static u2 get2LE(unsigned char const* pSrc)
126 return pSrc[0] | (pSrc[1] << 8);
130 * Get 4 little-endian bytes.
132 static u4 get4LE(unsigned char const* pSrc)
137 result |= pSrc[1] << 8;
138 result |= pSrc[2] << 16;
139 result |= pSrc[3] << 24;
145 * Find the zip Central Directory and memory-map it.
147 * On success, returns 0 after populating fields from the EOCD area:
152 static int mapCentralDirectory(int fd, const char* debugFileName,
153 ZipArchive* pArchive)
159 * Get and test file length.
161 off_t fileLength = lseek(fd, 0, SEEK_END);
162 if (fileLength < kEOCDLen) {
163 LOGV("Zip: length %ld is too small to be zip\n", (long) fileLength);
168 * Perform the traditional EOCD snipe hunt.
170 * We're searching for the End of Central Directory magic number,
171 * which appears at the start of the EOCD block. It's followed by
172 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
173 * need to read the last part of the file into a buffer, dig through
174 * it to find the magic number, parse some values out, and use those
175 * to determine the extent of the CD.
177 * We start by pulling in the last part of the file.
179 size_t readAmount = kMaxEOCDSearch;
180 if (readAmount > (size_t) fileLength)
181 readAmount = fileLength;
182 off_t searchStart = fileLength - readAmount;
184 scanBuf = (u1*) malloc(readAmount);
185 if (lseek(fd, searchStart, SEEK_SET) != searchStart) {
186 LOGW("Zip: seek %ld failed: %s\n", (long) searchStart, strerror(errno));
189 ssize_t actual = TEMP_FAILURE_RETRY(read(fd, scanBuf, readAmount));
190 if (actual != (ssize_t) readAmount) {
191 LOGW("Zip: read %zd failed: %s\n", readAmount, strerror(errno));
196 * Scan backward for the EOCD magic. In an archive without a trailing
197 * comment, we'll find it on the first try. (We may want to consider
198 * doing an initial minimal read; if we don't find it, retry with a
199 * second read as above.)
202 for (i = readAmount - kEOCDLen; i >= 0; i--) {
203 if (scanBuf[i] == 0x50 && get4LE(&scanBuf[i]) == kEOCDSignature) {
204 LOGV("+++ Found EOCD at buf+%d\n", i);
209 LOGD("Zip: EOCD not found, %s is not zip\n", debugFileName);
213 off_t eocdOffset = searchStart + i;
214 const u1* eocdPtr = scanBuf + i;
216 assert(eocdOffset < fileLength);
219 * Grab the CD offset and size, and the number of entries in the
220 * archive. Verify that they look reasonable.
222 u4 numEntries = get2LE(eocdPtr + kEOCDNumEntries);
223 u4 dirSize = get4LE(eocdPtr + kEOCDSize);
224 u4 dirOffset = get4LE(eocdPtr + kEOCDFileOffset);
226 if ((long long) dirOffset + (long long) dirSize > (long long) eocdOffset) {
227 LOGW("Zip: bad offsets (dir %ld, size %u, eocd %ld)\n",
228 (long) dirOffset, dirSize, (long) eocdOffset);
231 if (numEntries == 0) {
232 LOGW("Zip: empty archive?\n");
236 LOGV("+++ numEntries=%d dirSize=%d dirOffset=%d\n",
237 numEntries, dirSize, dirOffset);
240 * It all looks good. Create a mapping for the CD, and set the fields
243 if (sysMapFileSegmentInShmem(fd, dirOffset, dirSize,
244 &pArchive->mDirectoryMap) != 0)
246 LOGW("Zip: cd map failed\n");
250 pArchive->mNumEntries = numEntries;
251 pArchive->mDirectoryOffset = dirOffset;
261 * Parses the Zip archive's Central Directory. Allocates and populates the
264 * Returns 0 on success.
266 static int parseZipArchive(ZipArchive* pArchive)
269 const u1* cdPtr = (const u1*)pArchive->mDirectoryMap.addr;
270 size_t cdLength = pArchive->mDirectoryMap.length;
271 int numEntries = pArchive->mNumEntries;
274 * Create hash table. We have a minimum 75% load factor, possibly as
275 * low as 50% after we round off to a power of 2. There must be at
276 * least one unused entry to avoid an infinite loop during creation.
278 pArchive->mHashTableSize = dexRoundUpPower2(1 + (numEntries * 4) / 3);
279 pArchive->mHashTable = (ZipHashEntry*)
280 calloc(pArchive->mHashTableSize, sizeof(ZipHashEntry));
283 * Walk through the central directory, adding entries to the hash
284 * table and verifying values.
286 const u1* ptr = cdPtr;
288 for (i = 0; i < numEntries; i++) {
289 if (get4LE(ptr) != kCDESignature) {
290 LOGW("Zip: missed a central dir sig (at %d)\n", i);
293 if (ptr + kCDELen > cdPtr + cdLength) {
294 LOGW("Zip: ran off the end (at %d)\n", i);
298 long localHdrOffset = (long) get4LE(ptr + kCDELocalOffset);
299 if (localHdrOffset >= pArchive->mDirectoryOffset) {
300 LOGW("Zip: bad LFH offset %ld at entry %d\n", localHdrOffset, i);
304 unsigned int fileNameLen, extraLen, commentLen, hash;
305 fileNameLen = get2LE(ptr + kCDENameLen);
306 extraLen = get2LE(ptr + kCDEExtraLen);
307 commentLen = get2LE(ptr + kCDECommentLen);
309 /* add the CDE filename to the hash table */
310 hash = computeHash((const char*)ptr + kCDELen, fileNameLen);
311 addToHash(pArchive, (const char*)ptr + kCDELen, fileNameLen, hash);
313 ptr += kCDELen + fileNameLen + extraLen + commentLen;
314 if ((size_t)(ptr - cdPtr) > cdLength) {
315 LOGW("Zip: bad CD advance (%d vs %zd) at entry %d\n",
316 (int) (ptr - cdPtr), cdLength, i);
320 LOGV("+++ zip good scan %d entries\n", numEntries);
329 * Open the specified file read-only. We examine the contents and verify
330 * that it appears to be a valid zip file.
332 * This will be called on non-Zip files, especially during VM startup, so
333 * we don't want to be too noisy about certain types of failure. (Do
334 * we want a "quiet" flag?)
336 * On success, we fill out the contents of "pArchive" and return 0. On
337 * failure we return the errno value.
339 int dexZipOpenArchive(const char* fileName, ZipArchive* pArchive)
343 LOGV("Opening as zip '%s' %p\n", fileName, pArchive);
345 memset(pArchive, 0, sizeof(ZipArchive));
347 fd = open(fileName, O_RDONLY | O_BINARY, 0);
349 err = errno ? errno : -1;
350 LOGV("Unable to open '%s': %s\n", fileName, strerror(err));
354 return dexZipPrepArchive(fd, fileName, pArchive);
358 * Prepare to access a ZipArchive through an open file descriptor.
360 * On success, we fill out the contents of "pArchive" and return 0.
362 int dexZipPrepArchive(int fd, const char* debugFileName, ZipArchive* pArchive)
366 memset(pArchive, 0, sizeof(*pArchive));
369 if (mapCentralDirectory(fd, debugFileName, pArchive) != 0)
372 if (parseZipArchive(pArchive) != 0) {
373 LOGV("Zip: parsing '%s' failed\n", debugFileName);
382 dexZipCloseArchive(pArchive);
388 * Close a ZipArchive, closing the file and freeing the contents.
390 * NOTE: the ZipArchive may not have been fully created.
392 void dexZipCloseArchive(ZipArchive* pArchive)
394 LOGV("Closing archive %p\n", pArchive);
396 if (pArchive->mFd >= 0)
397 close(pArchive->mFd);
399 sysReleaseShmem(&pArchive->mDirectoryMap);
401 free(pArchive->mHashTable);
403 /* ensure nobody tries to use the ZipArchive after it's closed */
404 pArchive->mDirectoryOffset = -1;
406 pArchive->mNumEntries = -1;
407 pArchive->mHashTableSize = -1;
408 pArchive->mHashTable = NULL;
413 * Find a matching entry.
415 * Returns 0 if not found.
417 ZipEntry dexZipFindEntry(const ZipArchive* pArchive, const char* entryName)
419 int nameLen = strlen(entryName);
420 unsigned int hash = computeHash(entryName, nameLen);
421 const int hashTableSize = pArchive->mHashTableSize;
422 int ent = hash & (hashTableSize-1);
424 while (pArchive->mHashTable[ent].name != NULL) {
425 if (pArchive->mHashTable[ent].nameLen == nameLen &&
426 memcmp(pArchive->mHashTable[ent].name, entryName, nameLen) == 0)
429 return (ZipEntry)(long)(ent + kZipEntryAdj);
432 ent = (ent + 1) & (hashTableSize-1);
440 * Find the Nth entry.
442 * This currently involves walking through the sparse hash table, counting
443 * non-empty entries. If we need to speed this up we can either allocate
444 * a parallel lookup table or (perhaps better) provide an iterator interface.
446 ZipEntry findEntryByIndex(ZipArchive* pArchive, int idx)
448 if (idx < 0 || idx >= pArchive->mNumEntries) {
449 LOGW("Invalid index %d\n", idx);
454 for (ent = 0; ent < pArchive->mHashTableSize; ent++) {
455 if (pArchive->mHashTable[ent].name != NULL) {
457 return (ZipEntry) (ent + kZipEntryAdj);
466 * Get the useful fields from the zip entry.
468 * Returns non-zero if the contents of the fields (particularly the data
469 * offset) appear to be bogus.
471 int dexZipGetEntryInfo(const ZipArchive* pArchive, ZipEntry entry,
472 int* pMethod, size_t* pUncompLen, size_t* pCompLen, off_t* pOffset,
473 long* pModWhen, long* pCrc32)
475 int ent = entryToIndex(pArchive, entry);
480 * Recover the start of the central directory entry from the filename
481 * pointer. The filename is the first entry past the fixed-size data,
482 * so we can just subtract back from that.
484 const unsigned char* basePtr = (const unsigned char*)
485 pArchive->mDirectoryMap.addr;
486 const unsigned char* ptr = (const unsigned char*)
487 pArchive->mHashTable[ent].name;
488 off_t cdOffset = pArchive->mDirectoryOffset;
492 int method = get2LE(ptr + kCDEMethod);
496 if (pModWhen != NULL)
497 *pModWhen = get4LE(ptr + kCDEModWhen);
499 *pCrc32 = get4LE(ptr + kCDECRC);
501 size_t compLen = get4LE(ptr + kCDECompLen);
502 if (pCompLen != NULL)
504 size_t uncompLen = get4LE(ptr + kCDEUncompLen);
505 if (pUncompLen != NULL)
506 *pUncompLen = uncompLen;
509 * If requested, determine the offset of the start of the data. All we
510 * have is the offset to the Local File Header, which is variable size,
511 * so we have to read the contents of the struct to figure out where
512 * the actual data starts.
514 * We also need to make sure that the lengths are not so large that
515 * somebody trying to map the compressed or uncompressed data runs
516 * off the end of the mapped region.
518 * Note we don't verify compLen/uncompLen if they don't request the
519 * dataOffset, because dataOffset is expensive to determine. However,
520 * if they don't have the file offset, they're not likely to be doing
521 * anything with the contents.
523 if (pOffset != NULL) {
524 long localHdrOffset = (long) get4LE(ptr + kCDELocalOffset);
525 if (localHdrOffset + kLFHLen >= cdOffset) {
526 LOGW("Zip: bad local hdr offset in zip\n");
531 if (lseek(pArchive->mFd, localHdrOffset, SEEK_SET) != localHdrOffset) {
532 LOGW("Zip: failed seeking to lfh at offset %ld\n", localHdrOffset);
536 TEMP_FAILURE_RETRY(read(pArchive->mFd, lfhBuf, sizeof(lfhBuf)));
537 if (actual != sizeof(lfhBuf)) {
538 LOGW("Zip: failed reading lfh from offset %ld\n", localHdrOffset);
542 if (get4LE(lfhBuf) != kLFHSignature) {
543 LOGW("Zip: didn't find signature at start of lfh, offset=%ld\n",
548 off_t dataOffset = localHdrOffset + kLFHLen
549 + get2LE(lfhBuf + kLFHNameLen) + get2LE(lfhBuf + kLFHExtraLen);
550 if (dataOffset >= cdOffset) {
551 LOGW("Zip: bad data offset %ld in zip\n", (long) dataOffset);
556 if ((off_t)(dataOffset + compLen) > cdOffset) {
557 LOGW("Zip: bad compressed length in zip (%ld + %zd > %ld)\n",
558 (long) dataOffset, compLen, (long) cdOffset);
562 if (method == kCompressStored &&
563 (off_t)(dataOffset + uncompLen) > cdOffset)
565 LOGW("Zip: bad uncompressed length in zip (%ld + %zd > %ld)\n",
566 (long) dataOffset, uncompLen, (long) cdOffset);
570 *pOffset = dataOffset;
576 * Uncompress "deflate" data from the archive's file to an open file
579 static int inflateToFile(int outFd, int inFd, size_t uncompLen, size_t compLen)
582 const size_t kBufSize = 32768;
583 unsigned char* readBuf = (unsigned char*) malloc(kBufSize);
584 unsigned char* writeBuf = (unsigned char*) malloc(kBufSize);
588 if (readBuf == NULL || writeBuf == NULL)
592 * Initialize the zlib stream struct.
594 memset(&zstream, 0, sizeof(zstream));
595 zstream.zalloc = Z_NULL;
596 zstream.zfree = Z_NULL;
597 zstream.opaque = Z_NULL;
598 zstream.next_in = NULL;
599 zstream.avail_in = 0;
600 zstream.next_out = (Bytef*) writeBuf;
601 zstream.avail_out = kBufSize;
602 zstream.data_type = Z_UNKNOWN;
605 * Use the undocumented "negative window bits" feature to tell zlib
606 * that there's no zlib header waiting for it.
608 zerr = inflateInit2(&zstream, -MAX_WBITS);
610 if (zerr == Z_VERSION_ERROR) {
611 LOGE("Installed zlib is not compatible with linked version (%s)\n",
614 LOGW("Call to inflateInit2 failed (zerr=%d)\n", zerr);
620 * Loop while we have more to do.
623 /* read as much as we can */
624 if (zstream.avail_in == 0) {
625 size_t getSize = (compLen > kBufSize) ? kBufSize : compLen;
627 ssize_t actual = TEMP_FAILURE_RETRY(read(inFd, readBuf, getSize));
628 if (actual != (ssize_t) getSize) {
629 LOGW("Zip: inflate read failed (%d vs %zd)\n",
630 (int)actual, getSize);
636 zstream.next_in = readBuf;
637 zstream.avail_in = getSize;
640 /* uncompress the data */
641 zerr = inflate(&zstream, Z_NO_FLUSH);
642 if (zerr != Z_OK && zerr != Z_STREAM_END) {
643 LOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)\n",
644 zerr, zstream.next_in, zstream.avail_in,
645 zstream.next_out, zstream.avail_out);
649 /* write when we're full or when we're done */
650 if (zstream.avail_out == 0 ||
651 (zerr == Z_STREAM_END && zstream.avail_out != kBufSize))
653 size_t writeSize = zstream.next_out - writeBuf;
654 if (sysWriteFully(outFd, writeBuf, writeSize, "Zip inflate") != 0)
657 zstream.next_out = writeBuf;
658 zstream.avail_out = kBufSize;
660 } while (zerr == Z_OK);
662 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
665 if (zstream.total_out != uncompLen) {
666 LOGW("Zip: size mismatch on inflated file (%ld vs %zd)\n",
667 zstream.total_out, uncompLen);
674 inflateEnd(&zstream); /* free up any allocated structures */
683 * Uncompress an entry, in its entirety, to an open file descriptor.
685 * TODO: this doesn't verify the data's CRC, but probably should (especially
686 * for uncompressed data).
688 int dexZipExtractEntryToFile(const ZipArchive* pArchive,
689 const ZipEntry entry, int fd)
692 int ent = entryToIndex(pArchive, entry);
694 LOGW("Zip: extract can't find entry %p\n", entry);
699 size_t uncompLen, compLen;
702 if (dexZipGetEntryInfo(pArchive, entry, &method, &uncompLen, &compLen,
703 &dataOffset, NULL, NULL) != 0)
707 if (lseek(pArchive->mFd, dataOffset, SEEK_SET) != dataOffset) {
708 LOGW("Zip: lseek to data at %ld failed\n", (long) dataOffset);
712 if (method == kCompressStored) {
713 if (sysCopyFileToFile(fd, pArchive->mFd, uncompLen) != 0)
716 if (inflateToFile(fd, pArchive->mFd, uncompLen, compLen) != 0)