AssetManager.cpp revision 2204f0bf56af53b588a01701b8cf9cd05b1b3ff9
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17//
18// Provide access to read-only assets.
19//
20
21#define LOG_TAG "asset"
22#define ATRACE_TAG ATRACE_TAG_RESOURCES
23//#define LOG_NDEBUG 0
24
25#include <androidfw/Asset.h>
26#include <androidfw/AssetDir.h>
27#include <androidfw/AssetManager.h>
28#include <androidfw/misc.h>
29#include <androidfw/ResourceTypes.h>
30#include <androidfw/ZipFileRO.h>
31#include <utils/Atomic.h>
32#include <utils/Log.h>
33#include <utils/String8.h>
34#include <utils/String8.h>
35#include <utils/threads.h>
36#include <utils/Timers.h>
37#ifdef HAVE_ANDROID_OS
38#include <cutils/trace.h>
39#endif
40
41#include <assert.h>
42#include <dirent.h>
43#include <errno.h>
44#include <string.h> // strerror
45#include <strings.h>
46
47#ifndef TEMP_FAILURE_RETRY
48/* Used to retry syscalls that can return EINTR. */
49#define TEMP_FAILURE_RETRY(exp) ({         \
50    typeof (exp) _rc;                      \
51    do {                                   \
52        _rc = (exp);                       \
53    } while (_rc == -1 && errno == EINTR); \
54    _rc; })
55#endif
56
57#ifdef HAVE_ANDROID_OS
58#define MY_TRACE_BEGIN(x) ATRACE_BEGIN(x)
59#define MY_TRACE_END() ATRACE_END()
60#else
61#define MY_TRACE_BEGIN(x)
62#define MY_TRACE_END()
63#endif
64
65using namespace android;
66
67static const bool kIsDebug = false;
68
69/*
70 * Names for default app, locale, and vendor.  We might want to change
71 * these to be an actual locale, e.g. always use en-US as the default.
72 */
73static const char* kDefaultLocale = "default";
74static const char* kDefaultVendor = "default";
75static const char* kAssetsRoot = "assets";
76static const char* kAppZipName = NULL; //"classes.jar";
77static const char* kSystemAssets = "framework/framework-res.apk";
78static const char* kResourceCache = "resource-cache";
79static const char* kAndroidManifest = "AndroidManifest.xml";
80
81static const char* kExcludeExtension = ".EXCLUDE";
82
83static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
84
85static volatile int32_t gCount = 0;
86
87const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
88const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
89const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
90const char* AssetManager::TARGET_PACKAGE_NAME = "android";
91const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
92const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
93
94namespace {
95    String8 idmapPathForPackagePath(const String8& pkgPath)
96    {
97        const char* root = getenv("ANDROID_DATA");
98        LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
99        String8 path(root);
100        path.appendPath(kResourceCache);
101
102        char buf[256]; // 256 chars should be enough for anyone...
103        strncpy(buf, pkgPath.string(), 255);
104        buf[255] = '\0';
105        char* filename = buf;
106        while (*filename && *filename == '/') {
107            ++filename;
108        }
109        char* p = filename;
110        while (*p) {
111            if (*p == '/') {
112                *p = '@';
113            }
114            ++p;
115        }
116        path.appendPath(filename);
117        path.append("@idmap");
118
119        return path;
120    }
121
122    /*
123     * Like strdup(), but uses C++ "new" operator instead of malloc.
124     */
125    static char* strdupNew(const char* str)
126    {
127        char* newStr;
128        int len;
129
130        if (str == NULL)
131            return NULL;
132
133        len = strlen(str);
134        newStr = new char[len+1];
135        memcpy(newStr, str, len+1);
136
137        return newStr;
138    }
139}
140
141/*
142 * ===========================================================================
143 *      AssetManager
144 * ===========================================================================
145 */
146
147int32_t AssetManager::getGlobalCount()
148{
149    return gCount;
150}
151
152AssetManager::AssetManager(CacheMode cacheMode)
153    : mLocale(NULL), mVendor(NULL),
154      mResources(NULL), mConfig(new ResTable_config),
155      mCacheMode(cacheMode), mCacheValid(false)
156{
157    int count = android_atomic_inc(&gCount) + 1;
158    if (kIsDebug) {
159        ALOGI("Creating AssetManager %p #%d\n", this, count);
160    }
161    memset(mConfig, 0, sizeof(ResTable_config));
162}
163
164AssetManager::~AssetManager(void)
165{
166    int count = android_atomic_dec(&gCount);
167    if (kIsDebug) {
168        ALOGI("Destroying AssetManager in %p #%d\n", this, count);
169    }
170
171    delete mConfig;
172    delete mResources;
173
174    // don't have a String class yet, so make sure we clean up
175    delete[] mLocale;
176    delete[] mVendor;
177}
178
179bool AssetManager::addAssetPath(const String8& path, int32_t* cookie)
180{
181    AutoMutex _l(mLock);
182
183    asset_path ap;
184
185    String8 realPath(path);
186    if (kAppZipName) {
187        realPath.appendPath(kAppZipName);
188    }
189    ap.type = ::getFileType(realPath.string());
190    if (ap.type == kFileTypeRegular) {
191        ap.path = realPath;
192    } else {
193        ap.path = path;
194        ap.type = ::getFileType(path.string());
195        if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
196            ALOGW("Asset path %s is neither a directory nor file (type=%d).",
197                 path.string(), (int)ap.type);
198            return false;
199        }
200    }
201
202    // Skip if we have it already.
203    for (size_t i=0; i<mAssetPaths.size(); i++) {
204        if (mAssetPaths[i].path == ap.path) {
205            if (cookie) {
206                *cookie = static_cast<int32_t>(i+1);
207            }
208            return true;
209        }
210    }
211
212    ALOGV("In %p Asset %s path: %s", this,
213         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
214
215    // Check that the path has an AndroidManifest.xml
216    Asset* manifestAsset = const_cast<AssetManager*>(this)->openNonAssetInPathLocked(
217            kAndroidManifest, Asset::ACCESS_BUFFER, ap);
218    if (manifestAsset == NULL) {
219        // This asset path does not contain any resources.
220        delete manifestAsset;
221        return false;
222    }
223    delete manifestAsset;
224
225    mAssetPaths.add(ap);
226
227    // new paths are always added at the end
228    if (cookie) {
229        *cookie = static_cast<int32_t>(mAssetPaths.size());
230    }
231
232#ifdef HAVE_ANDROID_OS
233    // Load overlays, if any
234    asset_path oap;
235    for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
236        mAssetPaths.add(oap);
237    }
238#endif
239
240    if (mResources != NULL) {
241        appendPathToResTable(ap);
242    }
243
244    return true;
245}
246
247bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
248{
249    const String8 idmapPath = idmapPathForPackagePath(packagePath);
250
251    AutoMutex _l(mLock);
252
253    for (size_t i = 0; i < mAssetPaths.size(); ++i) {
254        if (mAssetPaths[i].idmap == idmapPath) {
255           *cookie = static_cast<int32_t>(i + 1);
256            return true;
257         }
258     }
259
260    Asset* idmap = NULL;
261    if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
262        ALOGW("failed to open idmap file %s\n", idmapPath.string());
263        return false;
264    }
265
266    String8 targetPath;
267    String8 overlayPath;
268    if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
269                NULL, NULL, NULL, &targetPath, &overlayPath)) {
270        ALOGW("failed to read idmap file %s\n", idmapPath.string());
271        delete idmap;
272        return false;
273    }
274    delete idmap;
275
276    if (overlayPath != packagePath) {
277        ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
278                idmapPath.string(), packagePath.string(), overlayPath.string());
279        return false;
280    }
281    if (access(targetPath.string(), R_OK) != 0) {
282        ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
283        return false;
284    }
285    if (access(idmapPath.string(), R_OK) != 0) {
286        ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
287        return false;
288    }
289    if (access(overlayPath.string(), R_OK) != 0) {
290        ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
291        return false;
292    }
293
294    asset_path oap;
295    oap.path = overlayPath;
296    oap.type = ::getFileType(overlayPath.string());
297    oap.idmap = idmapPath;
298#if 0
299    ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
300            targetPath.string(), overlayPath.string(), idmapPath.string());
301#endif
302    mAssetPaths.add(oap);
303    *cookie = static_cast<int32_t>(mAssetPaths.size());
304
305    return true;
306 }
307
308bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
309        uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
310{
311    AutoMutex _l(mLock);
312    const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
313    ResTable tables[2];
314
315    for (int i = 0; i < 2; ++i) {
316        asset_path ap;
317        ap.type = kFileTypeRegular;
318        ap.path = paths[i];
319        Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
320        if (ass == NULL) {
321            ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
322            return false;
323        }
324        tables[i].add(ass);
325    }
326
327    return tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
328            targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
329}
330
331bool AssetManager::addDefaultAssets()
332{
333    const char* root = getenv("ANDROID_ROOT");
334    LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
335
336    String8 path(root);
337    path.appendPath(kSystemAssets);
338
339    return addAssetPath(path, NULL);
340}
341
342int32_t AssetManager::nextAssetPath(const int32_t cookie) const
343{
344    AutoMutex _l(mLock);
345    const size_t next = static_cast<size_t>(cookie) + 1;
346    return next > mAssetPaths.size() ? -1 : next;
347}
348
349String8 AssetManager::getAssetPath(const int32_t cookie) const
350{
351    AutoMutex _l(mLock);
352    const size_t which = static_cast<size_t>(cookie) - 1;
353    if (which < mAssetPaths.size()) {
354        return mAssetPaths[which].path;
355    }
356    return String8();
357}
358
359/*
360 * Set the current locale.  Use NULL to indicate no locale.
361 *
362 * Close and reopen Zip archives as appropriate, and reset cached
363 * information in the locale-specific sections of the tree.
364 */
365void AssetManager::setLocale(const char* locale)
366{
367    AutoMutex _l(mLock);
368    setLocaleLocked(locale);
369}
370
371
372static const char kFilPrefix[] = "fil";
373static const char kTlPrefix[] = "tl";
374
375// The sizes of the prefixes, excluding the 0 suffix.
376// char.
377static const int kFilPrefixLen = sizeof(kFilPrefix) - 1;
378static const int kTlPrefixLen = sizeof(kTlPrefix) - 1;
379
380void AssetManager::setLocaleLocked(const char* locale)
381{
382    if (mLocale != NULL) {
383        /* previously set, purge cached data */
384        purgeFileNameCacheLocked();
385        //mZipSet.purgeLocale();
386        delete[] mLocale;
387    }
388
389    // If we're attempting to set a locale that starts with "fil",
390    // we should convert it to "tl" for backwards compatibility since
391    // we've been using "tl" instead of "fil" prior to L.
392    //
393    // If the resource table already has entries for "fil", we use that
394    // instead of attempting a fallback.
395    if (strncmp(locale, kFilPrefix, kFilPrefixLen) == 0) {
396        Vector<String8> locales;
397        ResTable* res = mResources;
398        if (res != NULL) {
399            res->getLocales(&locales);
400        }
401        const size_t localesSize = locales.size();
402        bool hasFil = false;
403        for (size_t i = 0; i < localesSize; ++i) {
404            if (locales[i].find(kFilPrefix) == 0) {
405                hasFil = true;
406                break;
407            }
408        }
409
410
411        if (!hasFil) {
412            const size_t newLocaleLen = strlen(locale);
413            // This isn't a bug. We really do want mLocale to be 1 byte
414            // shorter than locale, because we're replacing "fil-" with
415            // "tl-".
416            mLocale = new char[newLocaleLen];
417            // Copy over "tl".
418            memcpy(mLocale, kTlPrefix, kTlPrefixLen);
419            // Copy the rest of |locale|, including the terminating '\0'.
420            memcpy(mLocale + kTlPrefixLen, locale + kFilPrefixLen,
421                   newLocaleLen - kFilPrefixLen + 1);
422            updateResourceParamsLocked();
423            return;
424        }
425    }
426
427    mLocale = strdupNew(locale);
428    updateResourceParamsLocked();
429}
430
431/*
432 * Set the current vendor.  Use NULL to indicate no vendor.
433 *
434 * Close and reopen Zip archives as appropriate, and reset cached
435 * information in the vendor-specific sections of the tree.
436 */
437void AssetManager::setVendor(const char* vendor)
438{
439    AutoMutex _l(mLock);
440
441    if (mVendor != NULL) {
442        /* previously set, purge cached data */
443        purgeFileNameCacheLocked();
444        //mZipSet.purgeVendor();
445        delete[] mVendor;
446    }
447    mVendor = strdupNew(vendor);
448}
449
450void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
451{
452    AutoMutex _l(mLock);
453    *mConfig = config;
454    if (locale) {
455        setLocaleLocked(locale);
456    } else if (config.language[0] != 0) {
457        char spec[RESTABLE_MAX_LOCALE_LEN];
458        config.getBcp47Locale(spec);
459        setLocaleLocked(spec);
460    } else {
461        updateResourceParamsLocked();
462    }
463}
464
465void AssetManager::getConfiguration(ResTable_config* outConfig) const
466{
467    AutoMutex _l(mLock);
468    *outConfig = *mConfig;
469}
470
471/*
472 * Open an asset.
473 *
474 * The data could be;
475 *  - In a file on disk (assetBase + fileName).
476 *  - In a compressed file on disk (assetBase + fileName.gz).
477 *  - In a Zip archive, uncompressed or compressed.
478 *
479 * It can be in a number of different directories and Zip archives.
480 * The search order is:
481 *  - [appname]
482 *    - locale + vendor
483 *    - "default" + vendor
484 *    - locale + "default"
485 *    - "default + "default"
486 *  - "common"
487 *    - (same as above)
488 *
489 * To find a particular file, we have to try up to eight paths with
490 * all three forms of data.
491 *
492 * We should probably reject requests for "illegal" filenames, e.g. those
493 * with illegal characters or "../" backward relative paths.
494 */
495Asset* AssetManager::open(const char* fileName, AccessMode mode)
496{
497    AutoMutex _l(mLock);
498
499    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
500
501
502    if (mCacheMode != CACHE_OFF && !mCacheValid)
503        loadFileNameCacheLocked();
504
505    String8 assetName(kAssetsRoot);
506    assetName.appendPath(fileName);
507
508    /*
509     * For each top-level asset path, search for the asset.
510     */
511
512    size_t i = mAssetPaths.size();
513    while (i > 0) {
514        i--;
515        ALOGV("Looking for asset '%s' in '%s'\n",
516                assetName.string(), mAssetPaths.itemAt(i).path.string());
517        Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
518        if (pAsset != NULL) {
519            return pAsset != kExcludedAsset ? pAsset : NULL;
520        }
521    }
522
523    return NULL;
524}
525
526/*
527 * Open a non-asset file as if it were an asset.
528 *
529 * The "fileName" is the partial path starting from the application
530 * name.
531 */
532Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
533{
534    AutoMutex _l(mLock);
535
536    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
537
538
539    if (mCacheMode != CACHE_OFF && !mCacheValid)
540        loadFileNameCacheLocked();
541
542    /*
543     * For each top-level asset path, search for the asset.
544     */
545
546    size_t i = mAssetPaths.size();
547    while (i > 0) {
548        i--;
549        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
550        Asset* pAsset = openNonAssetInPathLocked(
551            fileName, mode, mAssetPaths.itemAt(i));
552        if (pAsset != NULL) {
553            if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
554            return pAsset != kExcludedAsset ? pAsset : NULL;
555        }
556    }
557
558    return NULL;
559}
560
561Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
562{
563    const size_t which = static_cast<size_t>(cookie) - 1;
564
565    AutoMutex _l(mLock);
566
567    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
568
569    if (mCacheMode != CACHE_OFF && !mCacheValid)
570        loadFileNameCacheLocked();
571
572    if (which < mAssetPaths.size()) {
573        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
574                mAssetPaths.itemAt(which).path.string());
575        Asset* pAsset = openNonAssetInPathLocked(
576            fileName, mode, mAssetPaths.itemAt(which));
577        if (pAsset != NULL) {
578            return pAsset != kExcludedAsset ? pAsset : NULL;
579        }
580    }
581
582    return NULL;
583}
584
585/*
586 * Get the type of a file in the asset namespace.
587 *
588 * This currently only works for regular files.  All others (including
589 * directories) will return kFileTypeNonexistent.
590 */
591FileType AssetManager::getFileType(const char* fileName)
592{
593    Asset* pAsset = NULL;
594
595    /*
596     * Open the asset.  This is less efficient than simply finding the
597     * file, but it's not too bad (we don't uncompress or mmap data until
598     * the first read() call).
599     */
600    pAsset = open(fileName, Asset::ACCESS_STREAMING);
601    delete pAsset;
602
603    if (pAsset == NULL)
604        return kFileTypeNonexistent;
605    else
606        return kFileTypeRegular;
607}
608
609bool AssetManager::appendPathToResTable(const asset_path& ap) const {
610    Asset* ass = NULL;
611    ResTable* sharedRes = NULL;
612    bool shared = true;
613    bool onlyEmptyResources = true;
614    MY_TRACE_BEGIN(ap.path.string());
615    Asset* idmap = openIdmapLocked(ap);
616    size_t nextEntryIdx = mResources->getTableCount();
617    ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
618    if (ap.type != kFileTypeDirectory) {
619        if (nextEntryIdx == 0) {
620            // The first item is typically the framework resources,
621            // which we want to avoid parsing every time.
622            sharedRes = const_cast<AssetManager*>(this)->
623                mZipSet.getZipResourceTable(ap.path);
624            if (sharedRes != NULL) {
625                // skip ahead the number of system overlay packages preloaded
626                nextEntryIdx = sharedRes->getTableCount();
627            }
628        }
629        if (sharedRes == NULL) {
630            ass = const_cast<AssetManager*>(this)->
631                mZipSet.getZipResourceTableAsset(ap.path);
632            if (ass == NULL) {
633                ALOGV("loading resource table %s\n", ap.path.string());
634                ass = const_cast<AssetManager*>(this)->
635                    openNonAssetInPathLocked("resources.arsc",
636                                             Asset::ACCESS_BUFFER,
637                                             ap);
638                if (ass != NULL && ass != kExcludedAsset) {
639                    ass = const_cast<AssetManager*>(this)->
640                        mZipSet.setZipResourceTableAsset(ap.path, ass);
641                }
642            }
643
644            if (nextEntryIdx == 0 && ass != NULL) {
645                // If this is the first resource table in the asset
646                // manager, then we are going to cache it so that we
647                // can quickly copy it out for others.
648                ALOGV("Creating shared resources for %s", ap.path.string());
649                sharedRes = new ResTable();
650                sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
651#ifdef HAVE_ANDROID_OS
652                const char* data = getenv("ANDROID_DATA");
653                LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
654                String8 overlaysListPath(data);
655                overlaysListPath.appendPath(kResourceCache);
656                overlaysListPath.appendPath("overlays.list");
657                addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
658#endif
659                sharedRes = const_cast<AssetManager*>(this)->
660                    mZipSet.setZipResourceTable(ap.path, sharedRes);
661            }
662        }
663    } else {
664        ALOGV("loading resource table %s\n", ap.path.string());
665        ass = const_cast<AssetManager*>(this)->
666            openNonAssetInPathLocked("resources.arsc",
667                                     Asset::ACCESS_BUFFER,
668                                     ap);
669        shared = false;
670    }
671
672    if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
673        ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
674        if (sharedRes != NULL) {
675            ALOGV("Copying existing resources for %s", ap.path.string());
676            mResources->add(sharedRes);
677        } else {
678            ALOGV("Parsing resources for %s", ap.path.string());
679            mResources->add(ass, idmap, nextEntryIdx + 1, !shared);
680        }
681        onlyEmptyResources = false;
682
683        if (!shared) {
684            delete ass;
685        }
686    } else {
687        ALOGV("Installing empty resources in to table %p\n", mResources);
688        mResources->addEmpty(nextEntryIdx + 1);
689    }
690
691    if (idmap != NULL) {
692        delete idmap;
693    }
694    MY_TRACE_END();
695
696    return onlyEmptyResources;
697}
698
699const ResTable* AssetManager::getResTable(bool required) const
700{
701    ResTable* rt = mResources;
702    if (rt) {
703        return rt;
704    }
705
706    // Iterate through all asset packages, collecting resources from each.
707
708    AutoMutex _l(mLock);
709
710    if (mResources != NULL) {
711        return mResources;
712    }
713
714    if (required) {
715        LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
716    }
717
718    if (mCacheMode != CACHE_OFF && !mCacheValid) {
719        const_cast<AssetManager*>(this)->loadFileNameCacheLocked();
720    }
721
722    mResources = new ResTable();
723    updateResourceParamsLocked();
724
725    bool onlyEmptyResources = true;
726    const size_t N = mAssetPaths.size();
727    for (size_t i=0; i<N; i++) {
728        bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
729        onlyEmptyResources = onlyEmptyResources && empty;
730    }
731
732    if (required && onlyEmptyResources) {
733        ALOGW("Unable to find resources file resources.arsc");
734        delete mResources;
735        mResources = NULL;
736    }
737
738    return mResources;
739}
740
741void AssetManager::updateResourceParamsLocked() const
742{
743    ResTable* res = mResources;
744    if (!res) {
745        return;
746    }
747
748    if (mLocale) {
749        mConfig->setBcp47Locale(mLocale);
750    } else {
751        mConfig->clearLocale();
752    }
753
754    res->setParameters(mConfig);
755}
756
757Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
758{
759    Asset* ass = NULL;
760    if (ap.idmap.size() != 0) {
761        ass = const_cast<AssetManager*>(this)->
762            openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
763        if (ass) {
764            ALOGV("loading idmap %s\n", ap.idmap.string());
765        } else {
766            ALOGW("failed to load idmap %s\n", ap.idmap.string());
767        }
768    }
769    return ass;
770}
771
772void AssetManager::addSystemOverlays(const char* pathOverlaysList,
773        const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
774{
775    FILE* fin = fopen(pathOverlaysList, "r");
776    if (fin == NULL) {
777        return;
778    }
779
780    char buf[1024];
781    while (fgets(buf, sizeof(buf), fin)) {
782        // format of each line:
783        //   <path to apk><space><path to idmap><newline>
784        char* space = strchr(buf, ' ');
785        char* newline = strchr(buf, '\n');
786        asset_path oap;
787
788        if (space == NULL || newline == NULL || newline < space) {
789            continue;
790        }
791
792        oap.path = String8(buf, space - buf);
793        oap.type = kFileTypeRegular;
794        oap.idmap = String8(space + 1, newline - space - 1);
795
796        Asset* oass = const_cast<AssetManager*>(this)->
797            openNonAssetInPathLocked("resources.arsc",
798                    Asset::ACCESS_BUFFER,
799                    oap);
800
801        if (oass != NULL) {
802            Asset* oidmap = openIdmapLocked(oap);
803            offset++;
804            sharedRes->add(oass, oidmap, offset + 1, false);
805            const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
806            const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
807        }
808    }
809    fclose(fin);
810}
811
812const ResTable& AssetManager::getResources(bool required) const
813{
814    const ResTable* rt = getResTable(required);
815    return *rt;
816}
817
818bool AssetManager::isUpToDate()
819{
820    AutoMutex _l(mLock);
821    return mZipSet.isUpToDate();
822}
823
824void AssetManager::getLocales(Vector<String8>* locales) const
825{
826    ResTable* res = mResources;
827    if (res != NULL) {
828        res->getLocales(locales);
829    }
830
831    const size_t numLocales = locales->size();
832    for (size_t i = 0; i < numLocales; ++i) {
833        const String8& localeStr = locales->itemAt(i);
834        if (localeStr.find(kTlPrefix) == 0) {
835            String8 replaced("fil");
836            replaced += (localeStr.string() + kTlPrefixLen);
837            locales->editItemAt(i) = replaced;
838        }
839    }
840}
841
842/*
843 * Open a non-asset file as if it were an asset, searching for it in the
844 * specified app.
845 *
846 * Pass in a NULL values for "appName" if the common app directory should
847 * be used.
848 */
849Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
850    const asset_path& ap)
851{
852    Asset* pAsset = NULL;
853
854    /* look at the filesystem on disk */
855    if (ap.type == kFileTypeDirectory) {
856        String8 path(ap.path);
857        path.appendPath(fileName);
858
859        pAsset = openAssetFromFileLocked(path, mode);
860
861        if (pAsset == NULL) {
862            /* try again, this time with ".gz" */
863            path.append(".gz");
864            pAsset = openAssetFromFileLocked(path, mode);
865        }
866
867        if (pAsset != NULL) {
868            //printf("FOUND NA '%s' on disk\n", fileName);
869            pAsset->setAssetSource(path);
870        }
871
872    /* look inside the zip file */
873    } else {
874        String8 path(fileName);
875
876        /* check the appropriate Zip file */
877        ZipFileRO* pZip = getZipFileLocked(ap);
878        if (pZip != NULL) {
879            //printf("GOT zip, checking NA '%s'\n", (const char*) path);
880            ZipEntryRO entry = pZip->findEntryByName(path.string());
881            if (entry != NULL) {
882                //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
883                pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
884                pZip->releaseEntry(entry);
885            }
886        }
887
888        if (pAsset != NULL) {
889            /* create a "source" name, for debug/display */
890            pAsset->setAssetSource(
891                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
892                                                String8(fileName)));
893        }
894    }
895
896    return pAsset;
897}
898
899/*
900 * Open an asset, searching for it in the directory hierarchy for the
901 * specified app.
902 *
903 * Pass in a NULL values for "appName" if the common app directory should
904 * be used.
905 */
906Asset* AssetManager::openInPathLocked(const char* fileName, AccessMode mode,
907    const asset_path& ap)
908{
909    Asset* pAsset = NULL;
910
911    /*
912     * Try various combinations of locale and vendor.
913     */
914    if (mLocale != NULL && mVendor != NULL)
915        pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, mVendor);
916    if (pAsset == NULL && mVendor != NULL)
917        pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, mVendor);
918    if (pAsset == NULL && mLocale != NULL)
919        pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, NULL);
920    if (pAsset == NULL)
921        pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, NULL);
922
923    return pAsset;
924}
925
926/*
927 * Open an asset, searching for it in the directory hierarchy for the
928 * specified locale and vendor.
929 *
930 * We also search in "app.jar".
931 *
932 * Pass in NULL values for "appName", "locale", and "vendor" if the
933 * defaults should be used.
934 */
935Asset* AssetManager::openInLocaleVendorLocked(const char* fileName, AccessMode mode,
936    const asset_path& ap, const char* locale, const char* vendor)
937{
938    Asset* pAsset = NULL;
939
940    if (ap.type == kFileTypeDirectory) {
941        if (mCacheMode == CACHE_OFF) {
942            /* look at the filesystem on disk */
943            String8 path(createPathNameLocked(ap, locale, vendor));
944            path.appendPath(fileName);
945
946            String8 excludeName(path);
947            excludeName.append(kExcludeExtension);
948            if (::getFileType(excludeName.string()) != kFileTypeNonexistent) {
949                /* say no more */
950                //printf("+++ excluding '%s'\n", (const char*) excludeName);
951                return kExcludedAsset;
952            }
953
954            pAsset = openAssetFromFileLocked(path, mode);
955
956            if (pAsset == NULL) {
957                /* try again, this time with ".gz" */
958                path.append(".gz");
959                pAsset = openAssetFromFileLocked(path, mode);
960            }
961
962            if (pAsset != NULL)
963                pAsset->setAssetSource(path);
964        } else {
965            /* find in cache */
966            String8 path(createPathNameLocked(ap, locale, vendor));
967            path.appendPath(fileName);
968
969            AssetDir::FileInfo tmpInfo;
970            bool found = false;
971
972            String8 excludeName(path);
973            excludeName.append(kExcludeExtension);
974
975            if (mCache.indexOf(excludeName) != NAME_NOT_FOUND) {
976                /* go no farther */
977                //printf("+++ Excluding '%s'\n", (const char*) excludeName);
978                return kExcludedAsset;
979            }
980
981            /*
982             * File compression extensions (".gz") don't get stored in the
983             * name cache, so we have to try both here.
984             */
985            if (mCache.indexOf(path) != NAME_NOT_FOUND) {
986                found = true;
987                pAsset = openAssetFromFileLocked(path, mode);
988                if (pAsset == NULL) {
989                    /* try again, this time with ".gz" */
990                    path.append(".gz");
991                    pAsset = openAssetFromFileLocked(path, mode);
992                }
993            }
994
995            if (pAsset != NULL)
996                pAsset->setAssetSource(path);
997
998            /*
999             * Don't continue the search into the Zip files.  Our cached info
1000             * said it was a file on disk; to be consistent with openDir()
1001             * we want to return the loose asset.  If the cached file gets
1002             * removed, we fail.
1003             *
1004             * The alternative is to update our cache when files get deleted,
1005             * or make some sort of "best effort" promise, but for now I'm
1006             * taking the hard line.
1007             */
1008            if (found) {
1009                if (pAsset == NULL)
1010                    ALOGD("Expected file not found: '%s'\n", path.string());
1011                return pAsset;
1012            }
1013        }
1014    }
1015
1016    /*
1017     * Either it wasn't found on disk or on the cached view of the disk.
1018     * Dig through the currently-opened set of Zip files.  If caching
1019     * is disabled, the Zip file may get reopened.
1020     */
1021    if (pAsset == NULL && ap.type == kFileTypeRegular) {
1022        String8 path;
1023
1024        path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1025        path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1026        path.appendPath(fileName);
1027
1028        /* check the appropriate Zip file */
1029        ZipFileRO* pZip = getZipFileLocked(ap);
1030        if (pZip != NULL) {
1031            //printf("GOT zip, checking '%s'\n", (const char*) path);
1032            ZipEntryRO entry = pZip->findEntryByName(path.string());
1033            if (entry != NULL) {
1034                //printf("FOUND in Zip file for %s/%s-%s\n",
1035                //    appName, locale, vendor);
1036                pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
1037                pZip->releaseEntry(entry);
1038            }
1039        }
1040
1041        if (pAsset != NULL) {
1042            /* create a "source" name, for debug/display */
1043            pAsset->setAssetSource(createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()),
1044                                                             String8(""), String8(fileName)));
1045        }
1046    }
1047
1048    return pAsset;
1049}
1050
1051/*
1052 * Create a "source name" for a file from a Zip archive.
1053 */
1054String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
1055    const String8& dirName, const String8& fileName)
1056{
1057    String8 sourceName("zip:");
1058    sourceName.append(zipFileName);
1059    sourceName.append(":");
1060    if (dirName.length() > 0) {
1061        sourceName.appendPath(dirName);
1062    }
1063    sourceName.appendPath(fileName);
1064    return sourceName;
1065}
1066
1067/*
1068 * Create a path to a loose asset (asset-base/app/locale/vendor).
1069 */
1070String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
1071    const char* vendor)
1072{
1073    String8 path(ap.path);
1074    path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1075    path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1076    return path;
1077}
1078
1079/*
1080 * Create a path to a loose asset (asset-base/app/rootDir).
1081 */
1082String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
1083{
1084    String8 path(ap.path);
1085    if (rootDir != NULL) path.appendPath(rootDir);
1086    return path;
1087}
1088
1089/*
1090 * Return a pointer to one of our open Zip archives.  Returns NULL if no
1091 * matching Zip file exists.
1092 *
1093 * Right now we have 2 possible Zip files (1 each in app/"common").
1094 *
1095 * If caching is set to CACHE_OFF, to get the expected behavior we
1096 * need to reopen the Zip file on every request.  That would be silly
1097 * and expensive, so instead we just check the file modification date.
1098 *
1099 * Pass in NULL values for "appName", "locale", and "vendor" if the
1100 * generics should be used.
1101 */
1102ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
1103{
1104    ALOGV("getZipFileLocked() in %p\n", this);
1105
1106    return mZipSet.getZip(ap.path);
1107}
1108
1109/*
1110 * Try to open an asset from a file on disk.
1111 *
1112 * If the file is compressed with gzip, we seek to the start of the
1113 * deflated data and pass that in (just like we would for a Zip archive).
1114 *
1115 * For uncompressed data, we may already have an mmap()ed version sitting
1116 * around.  If so, we want to hand that to the Asset instead.
1117 *
1118 * This returns NULL if the file doesn't exist, couldn't be opened, or
1119 * claims to be a ".gz" but isn't.
1120 */
1121Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
1122    AccessMode mode)
1123{
1124    Asset* pAsset = NULL;
1125
1126    if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
1127        //printf("TRYING '%s'\n", (const char*) pathName);
1128        pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
1129    } else {
1130        //printf("TRYING '%s'\n", (const char*) pathName);
1131        pAsset = Asset::createFromFile(pathName.string(), mode);
1132    }
1133
1134    return pAsset;
1135}
1136
1137/*
1138 * Given an entry in a Zip archive, create a new Asset object.
1139 *
1140 * If the entry is uncompressed, we may want to create or share a
1141 * slice of shared memory.
1142 */
1143Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
1144    const ZipEntryRO entry, AccessMode mode, const String8& entryName)
1145{
1146    Asset* pAsset = NULL;
1147
1148    // TODO: look for previously-created shared memory slice?
1149    int method;
1150    size_t uncompressedLen;
1151
1152    //printf("USING Zip '%s'\n", pEntry->getFileName());
1153
1154    //pZipFile->getEntryInfo(entry, &method, &uncompressedLen, &compressedLen,
1155    //    &offset);
1156    if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
1157            NULL, NULL))
1158    {
1159        ALOGW("getEntryInfo failed\n");
1160        return NULL;
1161    }
1162
1163    FileMap* dataMap = pZipFile->createEntryFileMap(entry);
1164    if (dataMap == NULL) {
1165        ALOGW("create map from entry failed\n");
1166        return NULL;
1167    }
1168
1169    if (method == ZipFileRO::kCompressStored) {
1170        pAsset = Asset::createFromUncompressedMap(dataMap, mode);
1171        ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
1172                dataMap->getFileName(), mode, pAsset);
1173    } else {
1174        pAsset = Asset::createFromCompressedMap(dataMap, method,
1175            uncompressedLen, mode);
1176        ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
1177                dataMap->getFileName(), mode, pAsset);
1178    }
1179    if (pAsset == NULL) {
1180        /* unexpected */
1181        ALOGW("create from segment failed\n");
1182    }
1183
1184    return pAsset;
1185}
1186
1187
1188
1189/*
1190 * Open a directory in the asset namespace.
1191 *
1192 * An "asset directory" is simply the combination of all files in all
1193 * locations, with ".gz" stripped for loose files.  With app, locale, and
1194 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1195 *
1196 * Pass in "" for the root dir.
1197 */
1198AssetDir* AssetManager::openDir(const char* dirName)
1199{
1200    AutoMutex _l(mLock);
1201
1202    AssetDir* pDir = NULL;
1203    SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1204
1205    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1206    assert(dirName != NULL);
1207
1208    //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1209
1210    if (mCacheMode != CACHE_OFF && !mCacheValid)
1211        loadFileNameCacheLocked();
1212
1213    pDir = new AssetDir;
1214
1215    /*
1216     * Scan the various directories, merging what we find into a single
1217     * vector.  We want to scan them in reverse priority order so that
1218     * the ".EXCLUDE" processing works correctly.  Also, if we decide we
1219     * want to remember where the file is coming from, we'll get the right
1220     * version.
1221     *
1222     * We start with Zip archives, then do loose files.
1223     */
1224    pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1225
1226    size_t i = mAssetPaths.size();
1227    while (i > 0) {
1228        i--;
1229        const asset_path& ap = mAssetPaths.itemAt(i);
1230        if (ap.type == kFileTypeRegular) {
1231            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1232            scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1233        } else {
1234            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1235            scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1236        }
1237    }
1238
1239#if 0
1240    printf("FILE LIST:\n");
1241    for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1242        printf(" %d: (%d) '%s'\n", i,
1243            pMergedInfo->itemAt(i).getFileType(),
1244            (const char*) pMergedInfo->itemAt(i).getFileName());
1245    }
1246#endif
1247
1248    pDir->setFileList(pMergedInfo);
1249    return pDir;
1250}
1251
1252/*
1253 * Open a directory in the non-asset namespace.
1254 *
1255 * An "asset directory" is simply the combination of all files in all
1256 * locations, with ".gz" stripped for loose files.  With app, locale, and
1257 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1258 *
1259 * Pass in "" for the root dir.
1260 */
1261AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
1262{
1263    AutoMutex _l(mLock);
1264
1265    AssetDir* pDir = NULL;
1266    SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1267
1268    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1269    assert(dirName != NULL);
1270
1271    //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1272
1273    if (mCacheMode != CACHE_OFF && !mCacheValid)
1274        loadFileNameCacheLocked();
1275
1276    pDir = new AssetDir;
1277
1278    pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1279
1280    const size_t which = static_cast<size_t>(cookie) - 1;
1281
1282    if (which < mAssetPaths.size()) {
1283        const asset_path& ap = mAssetPaths.itemAt(which);
1284        if (ap.type == kFileTypeRegular) {
1285            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1286            scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
1287        } else {
1288            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1289            scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
1290        }
1291    }
1292
1293#if 0
1294    printf("FILE LIST:\n");
1295    for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1296        printf(" %d: (%d) '%s'\n", i,
1297            pMergedInfo->itemAt(i).getFileType(),
1298            (const char*) pMergedInfo->itemAt(i).getFileName());
1299    }
1300#endif
1301
1302    pDir->setFileList(pMergedInfo);
1303    return pDir;
1304}
1305
1306/*
1307 * Scan the contents of the specified directory and merge them into the
1308 * "pMergedInfo" vector, removing previous entries if we find "exclude"
1309 * directives.
1310 *
1311 * Returns "false" if we found nothing to contribute.
1312 */
1313bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1314    const asset_path& ap, const char* rootDir, const char* dirName)
1315{
1316    SortedVector<AssetDir::FileInfo>* pContents;
1317    String8 path;
1318
1319    assert(pMergedInfo != NULL);
1320
1321    //printf("scanAndMergeDir: %s %s %s %s\n", appName, locale, vendor,dirName);
1322
1323    if (mCacheValid) {
1324        int i, start, count;
1325
1326        pContents = new SortedVector<AssetDir::FileInfo>;
1327
1328        /*
1329         * Get the basic partial path and find it in the cache.  That's
1330         * the start point for the search.
1331         */
1332        path = createPathNameLocked(ap, rootDir);
1333        if (dirName[0] != '\0')
1334            path.appendPath(dirName);
1335
1336        start = mCache.indexOf(path);
1337        if (start == NAME_NOT_FOUND) {
1338            //printf("+++ not found in cache: dir '%s'\n", (const char*) path);
1339            delete pContents;
1340            return false;
1341        }
1342
1343        /*
1344         * The match string looks like "common/default/default/foo/bar/".
1345         * The '/' on the end ensures that we don't match on the directory
1346         * itself or on ".../foo/barfy/".
1347         */
1348        path.append("/");
1349
1350        count = mCache.size();
1351
1352        /*
1353         * Pick out the stuff in the current dir by examining the pathname.
1354         * It needs to match the partial pathname prefix, and not have a '/'
1355         * (fssep) anywhere after the prefix.
1356         */
1357        for (i = start+1; i < count; i++) {
1358            if (mCache[i].getFileName().length() > path.length() &&
1359                strncmp(mCache[i].getFileName().string(), path.string(), path.length()) == 0)
1360            {
1361                const char* name = mCache[i].getFileName().string();
1362                // XXX THIS IS BROKEN!  Looks like we need to store the full
1363                // path prefix separately from the file path.
1364                if (strchr(name + path.length(), '/') == NULL) {
1365                    /* grab it, reducing path to just the filename component */
1366                    AssetDir::FileInfo tmp = mCache[i];
1367                    tmp.setFileName(tmp.getFileName().getPathLeaf());
1368                    pContents->add(tmp);
1369                }
1370            } else {
1371                /* no longer in the dir or its subdirs */
1372                break;
1373            }
1374
1375        }
1376    } else {
1377        path = createPathNameLocked(ap, rootDir);
1378        if (dirName[0] != '\0')
1379            path.appendPath(dirName);
1380        pContents = scanDirLocked(path);
1381        if (pContents == NULL)
1382            return false;
1383    }
1384
1385    // if we wanted to do an incremental cache fill, we would do it here
1386
1387    /*
1388     * Process "exclude" directives.  If we find a filename that ends with
1389     * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1390     * remove it if we find it.  We also delete the "exclude" entry.
1391     */
1392    int i, count, exclExtLen;
1393
1394    count = pContents->size();
1395    exclExtLen = strlen(kExcludeExtension);
1396    for (i = 0; i < count; i++) {
1397        const char* name;
1398        int nameLen;
1399
1400        name = pContents->itemAt(i).getFileName().string();
1401        nameLen = strlen(name);
1402        if (nameLen > exclExtLen &&
1403            strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1404        {
1405            String8 match(name, nameLen - exclExtLen);
1406            int matchIdx;
1407
1408            matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1409            if (matchIdx > 0) {
1410                ALOGV("Excluding '%s' [%s]\n",
1411                    pMergedInfo->itemAt(matchIdx).getFileName().string(),
1412                    pMergedInfo->itemAt(matchIdx).getSourceName().string());
1413                pMergedInfo->removeAt(matchIdx);
1414            } else {
1415                //printf("+++ no match on '%s'\n", (const char*) match);
1416            }
1417
1418            ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1419            pContents->removeAt(i);
1420            i--;        // adjust "for" loop
1421            count--;    //  and loop limit
1422        }
1423    }
1424
1425    mergeInfoLocked(pMergedInfo, pContents);
1426
1427    delete pContents;
1428
1429    return true;
1430}
1431
1432/*
1433 * Scan the contents of the specified directory, and stuff what we find
1434 * into a newly-allocated vector.
1435 *
1436 * Files ending in ".gz" will have their extensions removed.
1437 *
1438 * We should probably think about skipping files with "illegal" names,
1439 * e.g. illegal characters (/\:) or excessive length.
1440 *
1441 * Returns NULL if the specified directory doesn't exist.
1442 */
1443SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1444{
1445    SortedVector<AssetDir::FileInfo>* pContents = NULL;
1446    DIR* dir;
1447    struct dirent* entry;
1448    FileType fileType;
1449
1450    ALOGV("Scanning dir '%s'\n", path.string());
1451
1452    dir = opendir(path.string());
1453    if (dir == NULL)
1454        return NULL;
1455
1456    pContents = new SortedVector<AssetDir::FileInfo>;
1457
1458    while (1) {
1459        entry = readdir(dir);
1460        if (entry == NULL)
1461            break;
1462
1463        if (strcmp(entry->d_name, ".") == 0 ||
1464            strcmp(entry->d_name, "..") == 0)
1465            continue;
1466
1467#ifdef _DIRENT_HAVE_D_TYPE
1468        if (entry->d_type == DT_REG)
1469            fileType = kFileTypeRegular;
1470        else if (entry->d_type == DT_DIR)
1471            fileType = kFileTypeDirectory;
1472        else
1473            fileType = kFileTypeUnknown;
1474#else
1475        // stat the file
1476        fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1477#endif
1478
1479        if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1480            continue;
1481
1482        AssetDir::FileInfo info;
1483        info.set(String8(entry->d_name), fileType);
1484        if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1485            info.setFileName(info.getFileName().getBasePath());
1486        info.setSourceName(path.appendPathCopy(info.getFileName()));
1487        pContents->add(info);
1488    }
1489
1490    closedir(dir);
1491    return pContents;
1492}
1493
1494/*
1495 * Scan the contents out of the specified Zip archive, and merge what we
1496 * find into "pMergedInfo".  If the Zip archive in question doesn't exist,
1497 * we return immediately.
1498 *
1499 * Returns "false" if we found nothing to contribute.
1500 */
1501bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1502    const asset_path& ap, const char* rootDir, const char* baseDirName)
1503{
1504    ZipFileRO* pZip;
1505    Vector<String8> dirs;
1506    AssetDir::FileInfo info;
1507    SortedVector<AssetDir::FileInfo> contents;
1508    String8 sourceName, zipName, dirName;
1509
1510    pZip = mZipSet.getZip(ap.path);
1511    if (pZip == NULL) {
1512        ALOGW("Failure opening zip %s\n", ap.path.string());
1513        return false;
1514    }
1515
1516    zipName = ZipSet::getPathName(ap.path.string());
1517
1518    /* convert "sounds" to "rootDir/sounds" */
1519    if (rootDir != NULL) dirName = rootDir;
1520    dirName.appendPath(baseDirName);
1521
1522    /*
1523     * Scan through the list of files, looking for a match.  The files in
1524     * the Zip table of contents are not in sorted order, so we have to
1525     * process the entire list.  We're looking for a string that begins
1526     * with the characters in "dirName", is followed by a '/', and has no
1527     * subsequent '/' in the stuff that follows.
1528     *
1529     * What makes this especially fun is that directories are not stored
1530     * explicitly in Zip archives, so we have to infer them from context.
1531     * When we see "sounds/foo.wav" we have to leave a note to ourselves
1532     * to insert a directory called "sounds" into the list.  We store
1533     * these in temporary vector so that we only return each one once.
1534     *
1535     * Name comparisons are case-sensitive to match UNIX filesystem
1536     * semantics.
1537     */
1538    int dirNameLen = dirName.length();
1539    void *iterationCookie;
1540    if (!pZip->startIteration(&iterationCookie)) {
1541        ALOGW("ZipFileRO::startIteration returned false");
1542        return false;
1543    }
1544
1545    ZipEntryRO entry;
1546    while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
1547        char nameBuf[256];
1548
1549        if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1550            // TODO: fix this if we expect to have long names
1551            ALOGE("ARGH: name too long?\n");
1552            continue;
1553        }
1554        //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
1555        if (dirNameLen == 0 ||
1556            (strncmp(nameBuf, dirName.string(), dirNameLen) == 0 &&
1557             nameBuf[dirNameLen] == '/'))
1558        {
1559            const char* cp;
1560            const char* nextSlash;
1561
1562            cp = nameBuf + dirNameLen;
1563            if (dirNameLen != 0)
1564                cp++;       // advance past the '/'
1565
1566            nextSlash = strchr(cp, '/');
1567//xxx this may break if there are bare directory entries
1568            if (nextSlash == NULL) {
1569                /* this is a file in the requested directory */
1570
1571                info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1572
1573                info.setSourceName(
1574                    createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1575
1576                contents.add(info);
1577                //printf("FOUND: file '%s'\n", info.getFileName().string());
1578            } else {
1579                /* this is a subdir; add it if we don't already have it*/
1580                String8 subdirName(cp, nextSlash - cp);
1581                size_t j;
1582                size_t N = dirs.size();
1583
1584                for (j = 0; j < N; j++) {
1585                    if (subdirName == dirs[j]) {
1586                        break;
1587                    }
1588                }
1589                if (j == N) {
1590                    dirs.add(subdirName);
1591                }
1592
1593                //printf("FOUND: dir '%s'\n", subdirName.string());
1594            }
1595        }
1596    }
1597
1598    pZip->endIteration(iterationCookie);
1599
1600    /*
1601     * Add the set of unique directories.
1602     */
1603    for (int i = 0; i < (int) dirs.size(); i++) {
1604        info.set(dirs[i], kFileTypeDirectory);
1605        info.setSourceName(
1606            createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1607        contents.add(info);
1608    }
1609
1610    mergeInfoLocked(pMergedInfo, &contents);
1611
1612    return true;
1613}
1614
1615
1616/*
1617 * Merge two vectors of FileInfo.
1618 *
1619 * The merged contents will be stuffed into *pMergedInfo.
1620 *
1621 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1622 * we use the newer "pContents" entry.
1623 */
1624void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1625    const SortedVector<AssetDir::FileInfo>* pContents)
1626{
1627    /*
1628     * Merge what we found in this directory with what we found in
1629     * other places.
1630     *
1631     * Two basic approaches:
1632     * (1) Create a new array that holds the unique values of the two
1633     *     arrays.
1634     * (2) Take the elements from pContents and shove them into pMergedInfo.
1635     *
1636     * Because these are vectors of complex objects, moving elements around
1637     * inside the vector requires constructing new objects and allocating
1638     * storage for members.  With approach #1, we're always adding to the
1639     * end, whereas with #2 we could be inserting multiple elements at the
1640     * front of the vector.  Approach #1 requires a full copy of the
1641     * contents of pMergedInfo, but approach #2 requires the same copy for
1642     * every insertion at the front of pMergedInfo.
1643     *
1644     * (We should probably use a SortedVector interface that allows us to
1645     * just stuff items in, trusting us to maintain the sort order.)
1646     */
1647    SortedVector<AssetDir::FileInfo>* pNewSorted;
1648    int mergeMax, contMax;
1649    int mergeIdx, contIdx;
1650
1651    pNewSorted = new SortedVector<AssetDir::FileInfo>;
1652    mergeMax = pMergedInfo->size();
1653    contMax = pContents->size();
1654    mergeIdx = contIdx = 0;
1655
1656    while (mergeIdx < mergeMax || contIdx < contMax) {
1657        if (mergeIdx == mergeMax) {
1658            /* hit end of "merge" list, copy rest of "contents" */
1659            pNewSorted->add(pContents->itemAt(contIdx));
1660            contIdx++;
1661        } else if (contIdx == contMax) {
1662            /* hit end of "cont" list, copy rest of "merge" */
1663            pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1664            mergeIdx++;
1665        } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1666        {
1667            /* items are identical, add newer and advance both indices */
1668            pNewSorted->add(pContents->itemAt(contIdx));
1669            mergeIdx++;
1670            contIdx++;
1671        } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1672        {
1673            /* "merge" is lower, add that one */
1674            pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1675            mergeIdx++;
1676        } else {
1677            /* "cont" is lower, add that one */
1678            assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1679            pNewSorted->add(pContents->itemAt(contIdx));
1680            contIdx++;
1681        }
1682    }
1683
1684    /*
1685     * Overwrite the "merged" list with the new stuff.
1686     */
1687    *pMergedInfo = *pNewSorted;
1688    delete pNewSorted;
1689
1690#if 0       // for Vector, rather than SortedVector
1691    int i, j;
1692    for (i = pContents->size() -1; i >= 0; i--) {
1693        bool add = true;
1694
1695        for (j = pMergedInfo->size() -1; j >= 0; j--) {
1696            /* case-sensitive comparisons, to behave like UNIX fs */
1697            if (strcmp(pContents->itemAt(i).mFileName,
1698                       pMergedInfo->itemAt(j).mFileName) == 0)
1699            {
1700                /* match, don't add this entry */
1701                add = false;
1702                break;
1703            }
1704        }
1705
1706        if (add)
1707            pMergedInfo->add(pContents->itemAt(i));
1708    }
1709#endif
1710}
1711
1712
1713/*
1714 * Load all files into the file name cache.  We want to do this across
1715 * all combinations of { appname, locale, vendor }, performing a recursive
1716 * directory traversal.
1717 *
1718 * This is not the most efficient data structure.  Also, gathering the
1719 * information as we needed it (file-by-file or directory-by-directory)
1720 * would be faster.  However, on the actual device, 99% of the files will
1721 * live in Zip archives, so this list will be very small.  The trouble
1722 * is that we have to check the "loose" files first, so it's important
1723 * that we don't beat the filesystem silly looking for files that aren't
1724 * there.
1725 *
1726 * Note on thread safety: this is the only function that causes updates
1727 * to mCache, and anybody who tries to use it will call here if !mCacheValid,
1728 * so we need to employ a mutex here.
1729 */
1730void AssetManager::loadFileNameCacheLocked(void)
1731{
1732    assert(!mCacheValid);
1733    assert(mCache.size() == 0);
1734
1735#ifdef DO_TIMINGS   // need to link against -lrt for this now
1736    DurationTimer timer;
1737    timer.start();
1738#endif
1739
1740    fncScanLocked(&mCache, "");
1741
1742#ifdef DO_TIMINGS
1743    timer.stop();
1744    ALOGD("Cache scan took %.3fms\n",
1745        timer.durationUsecs() / 1000.0);
1746#endif
1747
1748#if 0
1749    int i;
1750    printf("CACHED FILE LIST (%d entries):\n", mCache.size());
1751    for (i = 0; i < (int) mCache.size(); i++) {
1752        printf(" %d: (%d) '%s'\n", i,
1753            mCache.itemAt(i).getFileType(),
1754            (const char*) mCache.itemAt(i).getFileName());
1755    }
1756#endif
1757
1758    mCacheValid = true;
1759}
1760
1761/*
1762 * Scan up to 8 versions of the specified directory.
1763 */
1764void AssetManager::fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1765    const char* dirName)
1766{
1767    size_t i = mAssetPaths.size();
1768    while (i > 0) {
1769        i--;
1770        const asset_path& ap = mAssetPaths.itemAt(i);
1771        fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, NULL, dirName);
1772        if (mLocale != NULL)
1773            fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, NULL, dirName);
1774        if (mVendor != NULL)
1775            fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, mVendor, dirName);
1776        if (mLocale != NULL && mVendor != NULL)
1777            fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, mVendor, dirName);
1778    }
1779}
1780
1781/*
1782 * Recursively scan this directory and all subdirs.
1783 *
1784 * This is similar to scanAndMergeDir, but we don't remove the .EXCLUDE
1785 * files, and we prepend the extended partial path to the filenames.
1786 */
1787bool AssetManager::fncScanAndMergeDirLocked(
1788    SortedVector<AssetDir::FileInfo>* pMergedInfo,
1789    const asset_path& ap, const char* locale, const char* vendor,
1790    const char* dirName)
1791{
1792    SortedVector<AssetDir::FileInfo>* pContents;
1793    String8 partialPath;
1794    String8 fullPath;
1795
1796    // XXX This is broken -- the filename cache needs to hold the base
1797    // asset path separately from its filename.
1798
1799    partialPath = createPathNameLocked(ap, locale, vendor);
1800    if (dirName[0] != '\0') {
1801        partialPath.appendPath(dirName);
1802    }
1803
1804    fullPath = partialPath;
1805    pContents = scanDirLocked(fullPath);
1806    if (pContents == NULL) {
1807        return false;       // directory did not exist
1808    }
1809
1810    /*
1811     * Scan all subdirectories of the current dir, merging what we find
1812     * into "pMergedInfo".
1813     */
1814    for (int i = 0; i < (int) pContents->size(); i++) {
1815        if (pContents->itemAt(i).getFileType() == kFileTypeDirectory) {
1816            String8 subdir(dirName);
1817            subdir.appendPath(pContents->itemAt(i).getFileName());
1818
1819            fncScanAndMergeDirLocked(pMergedInfo, ap, locale, vendor, subdir.string());
1820        }
1821    }
1822
1823    /*
1824     * To be consistent, we want entries for the root directory.  If
1825     * we're the root, add one now.
1826     */
1827    if (dirName[0] == '\0') {
1828        AssetDir::FileInfo tmpInfo;
1829
1830        tmpInfo.set(String8(""), kFileTypeDirectory);
1831        tmpInfo.setSourceName(createPathNameLocked(ap, locale, vendor));
1832        pContents->add(tmpInfo);
1833    }
1834
1835    /*
1836     * We want to prepend the extended partial path to every entry in
1837     * "pContents".  It's the same value for each entry, so this will
1838     * not change the sorting order of the vector contents.
1839     */
1840    for (int i = 0; i < (int) pContents->size(); i++) {
1841        const AssetDir::FileInfo& info = pContents->itemAt(i);
1842        pContents->editItemAt(i).setFileName(partialPath.appendPathCopy(info.getFileName()));
1843    }
1844
1845    mergeInfoLocked(pMergedInfo, pContents);
1846    delete pContents;
1847    return true;
1848}
1849
1850/*
1851 * Trash the cache.
1852 */
1853void AssetManager::purgeFileNameCacheLocked(void)
1854{
1855    mCacheValid = false;
1856    mCache.clear();
1857}
1858
1859/*
1860 * ===========================================================================
1861 *      AssetManager::SharedZip
1862 * ===========================================================================
1863 */
1864
1865
1866Mutex AssetManager::SharedZip::gLock;
1867DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1868
1869AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1870    : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1871      mResourceTableAsset(NULL), mResourceTable(NULL)
1872{
1873    if (kIsDebug) {
1874        ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1875    }
1876    ALOGV("+++ opening zip '%s'\n", mPath.string());
1877    mZipFile = ZipFileRO::open(mPath.string());
1878    if (mZipFile == NULL) {
1879        ALOGD("failed to open Zip archive '%s'\n", mPath.string());
1880    }
1881}
1882
1883sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1884        bool createIfNotPresent)
1885{
1886    AutoMutex _l(gLock);
1887    time_t modWhen = getFileModDate(path);
1888    sp<SharedZip> zip = gOpen.valueFor(path).promote();
1889    if (zip != NULL && zip->mModWhen == modWhen) {
1890        return zip;
1891    }
1892    if (zip == NULL && !createIfNotPresent) {
1893        return NULL;
1894    }
1895    zip = new SharedZip(path, modWhen);
1896    gOpen.add(path, zip);
1897    return zip;
1898
1899}
1900
1901ZipFileRO* AssetManager::SharedZip::getZip()
1902{
1903    return mZipFile;
1904}
1905
1906Asset* AssetManager::SharedZip::getResourceTableAsset()
1907{
1908    ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1909    return mResourceTableAsset;
1910}
1911
1912Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1913{
1914    {
1915        AutoMutex _l(gLock);
1916        if (mResourceTableAsset == NULL) {
1917            mResourceTableAsset = asset;
1918            // This is not thread safe the first time it is called, so
1919            // do it here with the global lock held.
1920            asset->getBuffer(true);
1921            return asset;
1922        }
1923    }
1924    delete asset;
1925    return mResourceTableAsset;
1926}
1927
1928ResTable* AssetManager::SharedZip::getResourceTable()
1929{
1930    ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1931    return mResourceTable;
1932}
1933
1934ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1935{
1936    {
1937        AutoMutex _l(gLock);
1938        if (mResourceTable == NULL) {
1939            mResourceTable = res;
1940            return res;
1941        }
1942    }
1943    delete res;
1944    return mResourceTable;
1945}
1946
1947bool AssetManager::SharedZip::isUpToDate()
1948{
1949    time_t modWhen = getFileModDate(mPath.string());
1950    return mModWhen == modWhen;
1951}
1952
1953void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1954{
1955    mOverlays.add(ap);
1956}
1957
1958bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1959{
1960    if (idx >= mOverlays.size()) {
1961        return false;
1962    }
1963    *out = mOverlays[idx];
1964    return true;
1965}
1966
1967AssetManager::SharedZip::~SharedZip()
1968{
1969    if (kIsDebug) {
1970        ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1971    }
1972    if (mResourceTable != NULL) {
1973        delete mResourceTable;
1974    }
1975    if (mResourceTableAsset != NULL) {
1976        delete mResourceTableAsset;
1977    }
1978    if (mZipFile != NULL) {
1979        delete mZipFile;
1980        ALOGV("Closed '%s'\n", mPath.string());
1981    }
1982}
1983
1984/*
1985 * ===========================================================================
1986 *      AssetManager::ZipSet
1987 * ===========================================================================
1988 */
1989
1990/*
1991 * Constructor.
1992 */
1993AssetManager::ZipSet::ZipSet(void)
1994{
1995}
1996
1997/*
1998 * Destructor.  Close any open archives.
1999 */
2000AssetManager::ZipSet::~ZipSet(void)
2001{
2002    size_t N = mZipFile.size();
2003    for (size_t i = 0; i < N; i++)
2004        closeZip(i);
2005}
2006
2007/*
2008 * Close a Zip file and reset the entry.
2009 */
2010void AssetManager::ZipSet::closeZip(int idx)
2011{
2012    mZipFile.editItemAt(idx) = NULL;
2013}
2014
2015
2016/*
2017 * Retrieve the appropriate Zip file from the set.
2018 */
2019ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
2020{
2021    int idx = getIndex(path);
2022    sp<SharedZip> zip = mZipFile[idx];
2023    if (zip == NULL) {
2024        zip = SharedZip::get(path);
2025        mZipFile.editItemAt(idx) = zip;
2026    }
2027    return zip->getZip();
2028}
2029
2030Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
2031{
2032    int idx = getIndex(path);
2033    sp<SharedZip> zip = mZipFile[idx];
2034    if (zip == NULL) {
2035        zip = SharedZip::get(path);
2036        mZipFile.editItemAt(idx) = zip;
2037    }
2038    return zip->getResourceTableAsset();
2039}
2040
2041Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
2042                                                 Asset* asset)
2043{
2044    int idx = getIndex(path);
2045    sp<SharedZip> zip = mZipFile[idx];
2046    // doesn't make sense to call before previously accessing.
2047    return zip->setResourceTableAsset(asset);
2048}
2049
2050ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
2051{
2052    int idx = getIndex(path);
2053    sp<SharedZip> zip = mZipFile[idx];
2054    if (zip == NULL) {
2055        zip = SharedZip::get(path);
2056        mZipFile.editItemAt(idx) = zip;
2057    }
2058    return zip->getResourceTable();
2059}
2060
2061ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
2062                                                    ResTable* res)
2063{
2064    int idx = getIndex(path);
2065    sp<SharedZip> zip = mZipFile[idx];
2066    // doesn't make sense to call before previously accessing.
2067    return zip->setResourceTable(res);
2068}
2069
2070/*
2071 * Generate the partial pathname for the specified archive.  The caller
2072 * gets to prepend the asset root directory.
2073 *
2074 * Returns something like "common/en-US-noogle.jar".
2075 */
2076/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
2077{
2078    return String8(zipPath);
2079}
2080
2081bool AssetManager::ZipSet::isUpToDate()
2082{
2083    const size_t N = mZipFile.size();
2084    for (size_t i=0; i<N; i++) {
2085        if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
2086            return false;
2087        }
2088    }
2089    return true;
2090}
2091
2092void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
2093{
2094    int idx = getIndex(path);
2095    sp<SharedZip> zip = mZipFile[idx];
2096    zip->addOverlay(overlay);
2097}
2098
2099bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
2100{
2101    sp<SharedZip> zip = SharedZip::get(path, false);
2102    if (zip == NULL) {
2103        return false;
2104    }
2105    return zip->getOverlay(idx, out);
2106}
2107
2108/*
2109 * Compute the zip file's index.
2110 *
2111 * "appName", "locale", and "vendor" should be set to NULL to indicate the
2112 * default directory.
2113 */
2114int AssetManager::ZipSet::getIndex(const String8& zip) const
2115{
2116    const size_t N = mZipPath.size();
2117    for (size_t i=0; i<N; i++) {
2118        if (mZipPath[i] == zip) {
2119            return i;
2120        }
2121    }
2122
2123    mZipPath.add(zip);
2124    mZipFile.add(NULL);
2125
2126    return mZipPath.size()-1;
2127}
2128