AssetManager.cpp revision 5520581b5f043fb858b5b2044ff33ad8545a6d38
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#include <utils/Trace.h>
38
39#include <assert.h>
40#include <dirent.h>
41#include <errno.h>
42#include <string.h> // strerror
43#include <strings.h>
44
45#ifndef TEMP_FAILURE_RETRY
46/* Used to retry syscalls that can return EINTR. */
47#define TEMP_FAILURE_RETRY(exp) ({         \
48    typeof (exp) _rc;                      \
49    do {                                   \
50        _rc = (exp);                       \
51    } while (_rc == -1 && errno == EINTR); \
52    _rc; })
53#endif
54
55using namespace android;
56
57static const bool kIsDebug = false;
58
59/*
60 * Names for default app, locale, and vendor.  We might want to change
61 * these to be an actual locale, e.g. always use en-US as the default.
62 */
63static const char* kDefaultLocale = "default";
64static const char* kDefaultVendor = "default";
65static const char* kAssetsRoot = "assets";
66static const char* kAppZipName = NULL; //"classes.jar";
67static const char* kSystemAssets = "framework/framework-res.apk";
68static const char* kResourceCache = "resource-cache";
69static const char* kAndroidManifest = "AndroidManifest.xml";
70
71static const char* kExcludeExtension = ".EXCLUDE";
72
73static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
74
75static volatile int32_t gCount = 0;
76
77const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
78const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
79const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
80const char* AssetManager::TARGET_PACKAGE_NAME = "android";
81const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
82const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
83
84namespace {
85    String8 idmapPathForPackagePath(const String8& pkgPath)
86    {
87        const char* root = getenv("ANDROID_DATA");
88        LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
89        String8 path(root);
90        path.appendPath(kResourceCache);
91
92        char buf[256]; // 256 chars should be enough for anyone...
93        strncpy(buf, pkgPath.string(), 255);
94        buf[255] = '\0';
95        char* filename = buf;
96        while (*filename && *filename == '/') {
97            ++filename;
98        }
99        char* p = filename;
100        while (*p) {
101            if (*p == '/') {
102                *p = '@';
103            }
104            ++p;
105        }
106        path.appendPath(filename);
107        path.append("@idmap");
108
109        return path;
110    }
111
112    /*
113     * Like strdup(), but uses C++ "new" operator instead of malloc.
114     */
115    static char* strdupNew(const char* str)
116    {
117        char* newStr;
118        int len;
119
120        if (str == NULL)
121            return NULL;
122
123        len = strlen(str);
124        newStr = new char[len+1];
125        memcpy(newStr, str, len+1);
126
127        return newStr;
128    }
129}
130
131/*
132 * ===========================================================================
133 *      AssetManager
134 * ===========================================================================
135 */
136
137int32_t AssetManager::getGlobalCount()
138{
139    return gCount;
140}
141
142AssetManager::AssetManager(CacheMode cacheMode)
143    : mLocale(NULL), mVendor(NULL),
144      mResources(NULL), mConfig(new ResTable_config),
145      mCacheMode(cacheMode), mCacheValid(false)
146{
147    int count = android_atomic_inc(&gCount) + 1;
148    if (kIsDebug) {
149        ALOGI("Creating AssetManager %p #%d\n", this, count);
150    }
151    memset(mConfig, 0, sizeof(ResTable_config));
152}
153
154AssetManager::~AssetManager(void)
155{
156    int count = android_atomic_dec(&gCount);
157    if (kIsDebug) {
158        ALOGI("Destroying AssetManager in %p #%d\n", this, count);
159    }
160
161    delete mConfig;
162    delete mResources;
163
164    // don't have a String class yet, so make sure we clean up
165    delete[] mLocale;
166    delete[] mVendor;
167}
168
169bool AssetManager::addAssetPath(
170        const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset)
171{
172    AutoMutex _l(mLock);
173
174    asset_path ap;
175
176    String8 realPath(path);
177    if (kAppZipName) {
178        realPath.appendPath(kAppZipName);
179    }
180    ap.type = ::getFileType(realPath.string());
181    if (ap.type == kFileTypeRegular) {
182        ap.path = realPath;
183    } else {
184        ap.path = path;
185        ap.type = ::getFileType(path.string());
186        if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
187            ALOGW("Asset path %s is neither a directory nor file (type=%d).",
188                 path.string(), (int)ap.type);
189            return false;
190        }
191    }
192
193    // Skip if we have it already.
194    for (size_t i=0; i<mAssetPaths.size(); i++) {
195        if (mAssetPaths[i].path == ap.path) {
196            if (cookie) {
197                *cookie = static_cast<int32_t>(i+1);
198            }
199            return true;
200        }
201    }
202
203    ALOGV("In %p Asset %s path: %s", this,
204         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
205
206    // Check that the path has an AndroidManifest.xml
207    Asset* manifestAsset = const_cast<AssetManager*>(this)->openNonAssetInPathLocked(
208            kAndroidManifest, Asset::ACCESS_BUFFER, ap);
209    if (manifestAsset == NULL) {
210        // This asset path does not contain any resources.
211        delete manifestAsset;
212        return false;
213    }
214    delete manifestAsset;
215
216    ap.isSystemAsset = isSystemAsset;
217    mAssetPaths.add(ap);
218
219    // new paths are always added at the end
220    if (cookie) {
221        *cookie = static_cast<int32_t>(mAssetPaths.size());
222    }
223
224#ifdef __ANDROID__
225    // Load overlays, if any
226    asset_path oap;
227    for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
228        oap.isSystemAsset = isSystemAsset;
229        mAssetPaths.add(oap);
230    }
231#endif
232
233    if (mResources != NULL) {
234        appendPathToResTable(ap, appAsLib);
235    }
236
237    return true;
238}
239
240bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
241{
242    const String8 idmapPath = idmapPathForPackagePath(packagePath);
243
244    AutoMutex _l(mLock);
245
246    for (size_t i = 0; i < mAssetPaths.size(); ++i) {
247        if (mAssetPaths[i].idmap == idmapPath) {
248           *cookie = static_cast<int32_t>(i + 1);
249            return true;
250         }
251     }
252
253    Asset* idmap = NULL;
254    if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
255        ALOGW("failed to open idmap file %s\n", idmapPath.string());
256        return false;
257    }
258
259    String8 targetPath;
260    String8 overlayPath;
261    if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
262                NULL, NULL, NULL, &targetPath, &overlayPath)) {
263        ALOGW("failed to read idmap file %s\n", idmapPath.string());
264        delete idmap;
265        return false;
266    }
267    delete idmap;
268
269    if (overlayPath != packagePath) {
270        ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
271                idmapPath.string(), packagePath.string(), overlayPath.string());
272        return false;
273    }
274    if (access(targetPath.string(), R_OK) != 0) {
275        ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
276        return false;
277    }
278    if (access(idmapPath.string(), R_OK) != 0) {
279        ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
280        return false;
281    }
282    if (access(overlayPath.string(), R_OK) != 0) {
283        ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
284        return false;
285    }
286
287    asset_path oap;
288    oap.path = overlayPath;
289    oap.type = ::getFileType(overlayPath.string());
290    oap.idmap = idmapPath;
291#if 0
292    ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
293            targetPath.string(), overlayPath.string(), idmapPath.string());
294#endif
295    mAssetPaths.add(oap);
296    *cookie = static_cast<int32_t>(mAssetPaths.size());
297
298    if (mResources != NULL) {
299        appendPathToResTable(oap);
300    }
301
302    return true;
303 }
304
305bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
306        uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
307{
308    AutoMutex _l(mLock);
309    const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
310    ResTable tables[2];
311
312    for (int i = 0; i < 2; ++i) {
313        asset_path ap;
314        ap.type = kFileTypeRegular;
315        ap.path = paths[i];
316        Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
317        if (ass == NULL) {
318            ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
319            return false;
320        }
321        tables[i].add(ass);
322    }
323
324    return tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
325            targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
326}
327
328bool AssetManager::addDefaultAssets()
329{
330    const char* root = getenv("ANDROID_ROOT");
331    LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
332
333    String8 path(root);
334    path.appendPath(kSystemAssets);
335
336    return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
337}
338
339int32_t AssetManager::nextAssetPath(const int32_t cookie) const
340{
341    AutoMutex _l(mLock);
342    const size_t next = static_cast<size_t>(cookie) + 1;
343    return next > mAssetPaths.size() ? -1 : next;
344}
345
346String8 AssetManager::getAssetPath(const int32_t cookie) const
347{
348    AutoMutex _l(mLock);
349    const size_t which = static_cast<size_t>(cookie) - 1;
350    if (which < mAssetPaths.size()) {
351        return mAssetPaths[which].path;
352    }
353    return String8();
354}
355
356/*
357 * Set the current locale.  Use NULL to indicate no locale.
358 *
359 * Close and reopen Zip archives as appropriate, and reset cached
360 * information in the locale-specific sections of the tree.
361 */
362void AssetManager::setLocale(const char* locale)
363{
364    AutoMutex _l(mLock);
365    setLocaleLocked(locale);
366}
367
368
369static const char kFilPrefix[] = "fil";
370static const char kTlPrefix[] = "tl";
371
372// The sizes of the prefixes, excluding the 0 suffix.
373// char.
374static const int kFilPrefixLen = sizeof(kFilPrefix) - 1;
375static const int kTlPrefixLen = sizeof(kTlPrefix) - 1;
376
377void AssetManager::setLocaleLocked(const char* locale)
378{
379    if (mLocale != NULL) {
380        /* previously set, purge cached data */
381        purgeFileNameCacheLocked();
382        //mZipSet.purgeLocale();
383        delete[] mLocale;
384    }
385
386    // If we're attempting to set a locale that starts with "fil",
387    // we should convert it to "tl" for backwards compatibility since
388    // we've been using "tl" instead of "fil" prior to L.
389    //
390    // If the resource table already has entries for "fil", we use that
391    // instead of attempting a fallback.
392    if (strncmp(locale, kFilPrefix, kFilPrefixLen) == 0) {
393        Vector<String8> locales;
394        ResTable* res = mResources;
395        if (res != NULL) {
396            res->getLocales(&locales);
397        }
398        const size_t localesSize = locales.size();
399        bool hasFil = false;
400        for (size_t i = 0; i < localesSize; ++i) {
401            if (locales[i].find(kFilPrefix) == 0) {
402                hasFil = true;
403                break;
404            }
405        }
406
407
408        if (!hasFil) {
409            const size_t newLocaleLen = strlen(locale);
410            // This isn't a bug. We really do want mLocale to be 1 byte
411            // shorter than locale, because we're replacing "fil-" with
412            // "tl-".
413            mLocale = new char[newLocaleLen];
414            // Copy over "tl".
415            memcpy(mLocale, kTlPrefix, kTlPrefixLen);
416            // Copy the rest of |locale|, including the terminating '\0'.
417            memcpy(mLocale + kTlPrefixLen, locale + kFilPrefixLen,
418                   newLocaleLen - kFilPrefixLen + 1);
419            updateResourceParamsLocked();
420            return;
421        }
422    }
423
424    mLocale = strdupNew(locale);
425    updateResourceParamsLocked();
426}
427
428/*
429 * Set the current vendor.  Use NULL to indicate no vendor.
430 *
431 * Close and reopen Zip archives as appropriate, and reset cached
432 * information in the vendor-specific sections of the tree.
433 */
434void AssetManager::setVendor(const char* vendor)
435{
436    AutoMutex _l(mLock);
437
438    if (mVendor != NULL) {
439        /* previously set, purge cached data */
440        purgeFileNameCacheLocked();
441        //mZipSet.purgeVendor();
442        delete[] mVendor;
443    }
444    mVendor = strdupNew(vendor);
445}
446
447void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
448{
449    AutoMutex _l(mLock);
450    *mConfig = config;
451    if (locale) {
452        setLocaleLocked(locale);
453    } else if (config.language[0] != 0) {
454        char spec[RESTABLE_MAX_LOCALE_LEN];
455        config.getBcp47Locale(spec);
456        setLocaleLocked(spec);
457    } else {
458        updateResourceParamsLocked();
459    }
460}
461
462void AssetManager::getConfiguration(ResTable_config* outConfig) const
463{
464    AutoMutex _l(mLock);
465    *outConfig = *mConfig;
466}
467
468/*
469 * Open an asset.
470 *
471 * The data could be;
472 *  - In a file on disk (assetBase + fileName).
473 *  - In a compressed file on disk (assetBase + fileName.gz).
474 *  - In a Zip archive, uncompressed or compressed.
475 *
476 * It can be in a number of different directories and Zip archives.
477 * The search order is:
478 *  - [appname]
479 *    - locale + vendor
480 *    - "default" + vendor
481 *    - locale + "default"
482 *    - "default + "default"
483 *  - "common"
484 *    - (same as above)
485 *
486 * To find a particular file, we have to try up to eight paths with
487 * all three forms of data.
488 *
489 * We should probably reject requests for "illegal" filenames, e.g. those
490 * with illegal characters or "../" backward relative paths.
491 */
492Asset* AssetManager::open(const char* fileName, AccessMode mode)
493{
494    AutoMutex _l(mLock);
495
496    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
497
498
499    if (mCacheMode != CACHE_OFF && !mCacheValid)
500        loadFileNameCacheLocked();
501
502    String8 assetName(kAssetsRoot);
503    assetName.appendPath(fileName);
504
505    /*
506     * For each top-level asset path, search for the asset.
507     */
508
509    size_t i = mAssetPaths.size();
510    while (i > 0) {
511        i--;
512        ALOGV("Looking for asset '%s' in '%s'\n",
513                assetName.string(), mAssetPaths.itemAt(i).path.string());
514        Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
515        if (pAsset != NULL) {
516            return pAsset != kExcludedAsset ? pAsset : NULL;
517        }
518    }
519
520    return NULL;
521}
522
523/*
524 * Open a non-asset file as if it were an asset.
525 *
526 * The "fileName" is the partial path starting from the application
527 * name.
528 */
529Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
530{
531    AutoMutex _l(mLock);
532
533    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
534
535
536    if (mCacheMode != CACHE_OFF && !mCacheValid)
537        loadFileNameCacheLocked();
538
539    /*
540     * For each top-level asset path, search for the asset.
541     */
542
543    size_t i = mAssetPaths.size();
544    while (i > 0) {
545        i--;
546        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
547        Asset* pAsset = openNonAssetInPathLocked(
548            fileName, mode, mAssetPaths.itemAt(i));
549        if (pAsset != NULL) {
550            if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
551            return pAsset != kExcludedAsset ? pAsset : NULL;
552        }
553    }
554
555    return NULL;
556}
557
558Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
559{
560    const size_t which = static_cast<size_t>(cookie) - 1;
561
562    AutoMutex _l(mLock);
563
564    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
565
566    if (mCacheMode != CACHE_OFF && !mCacheValid)
567        loadFileNameCacheLocked();
568
569    if (which < mAssetPaths.size()) {
570        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
571                mAssetPaths.itemAt(which).path.string());
572        Asset* pAsset = openNonAssetInPathLocked(
573            fileName, mode, mAssetPaths.itemAt(which));
574        if (pAsset != NULL) {
575            return pAsset != kExcludedAsset ? pAsset : NULL;
576        }
577    }
578
579    return NULL;
580}
581
582/*
583 * Get the type of a file in the asset namespace.
584 *
585 * This currently only works for regular files.  All others (including
586 * directories) will return kFileTypeNonexistent.
587 */
588FileType AssetManager::getFileType(const char* fileName)
589{
590    Asset* pAsset = NULL;
591
592    /*
593     * Open the asset.  This is less efficient than simply finding the
594     * file, but it's not too bad (we don't uncompress or mmap data until
595     * the first read() call).
596     */
597    pAsset = open(fileName, Asset::ACCESS_STREAMING);
598    delete pAsset;
599
600    if (pAsset == NULL)
601        return kFileTypeNonexistent;
602    else
603        return kFileTypeRegular;
604}
605
606bool AssetManager::appendPathToResTable(const asset_path& ap, bool appAsLib) const {
607    // skip those ap's that correspond to system overlays
608    if (ap.isSystemOverlay) {
609        return true;
610    }
611
612    Asset* ass = NULL;
613    ResTable* sharedRes = NULL;
614    bool shared = true;
615    bool onlyEmptyResources = true;
616    ATRACE_NAME(ap.path.string());
617    Asset* idmap = openIdmapLocked(ap);
618    size_t nextEntryIdx = mResources->getTableCount();
619    ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
620    if (ap.type != kFileTypeDirectory) {
621        if (nextEntryIdx == 0) {
622            // The first item is typically the framework resources,
623            // which we want to avoid parsing every time.
624            sharedRes = const_cast<AssetManager*>(this)->
625                mZipSet.getZipResourceTable(ap.path);
626            if (sharedRes != NULL) {
627                // skip ahead the number of system overlay packages preloaded
628                nextEntryIdx = sharedRes->getTableCount();
629            }
630        }
631        if (sharedRes == NULL) {
632            ass = const_cast<AssetManager*>(this)->
633                mZipSet.getZipResourceTableAsset(ap.path);
634            if (ass == NULL) {
635                ALOGV("loading resource table %s\n", ap.path.string());
636                ass = const_cast<AssetManager*>(this)->
637                    openNonAssetInPathLocked("resources.arsc",
638                                             Asset::ACCESS_BUFFER,
639                                             ap);
640                if (ass != NULL && ass != kExcludedAsset) {
641                    ass = const_cast<AssetManager*>(this)->
642                        mZipSet.setZipResourceTableAsset(ap.path, ass);
643                }
644            }
645
646            if (nextEntryIdx == 0 && ass != NULL) {
647                // If this is the first resource table in the asset
648                // manager, then we are going to cache it so that we
649                // can quickly copy it out for others.
650                ALOGV("Creating shared resources for %s", ap.path.string());
651                sharedRes = new ResTable();
652                sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
653#ifdef __ANDROID__
654                const char* data = getenv("ANDROID_DATA");
655                LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
656                String8 overlaysListPath(data);
657                overlaysListPath.appendPath(kResourceCache);
658                overlaysListPath.appendPath("overlays.list");
659                addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
660#endif
661                sharedRes = const_cast<AssetManager*>(this)->
662                    mZipSet.setZipResourceTable(ap.path, sharedRes);
663            }
664        }
665    } else {
666        ALOGV("loading resource table %s\n", ap.path.string());
667        ass = const_cast<AssetManager*>(this)->
668            openNonAssetInPathLocked("resources.arsc",
669                                     Asset::ACCESS_BUFFER,
670                                     ap);
671        shared = false;
672    }
673
674    if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
675        ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
676        if (sharedRes != NULL) {
677            ALOGV("Copying existing resources for %s", ap.path.string());
678            mResources->add(sharedRes, ap.isSystemAsset);
679        } else {
680            ALOGV("Parsing resources for %s", ap.path.string());
681            mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
682        }
683        onlyEmptyResources = false;
684
685        if (!shared) {
686            delete ass;
687        }
688    } else {
689        ALOGV("Installing empty resources in to table %p\n", mResources);
690        mResources->addEmpty(nextEntryIdx + 1);
691    }
692
693    if (idmap != NULL) {
694        delete idmap;
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    ATRACE_CALL();
744    ResTable* res = mResources;
745    if (!res) {
746        return;
747    }
748
749    if (mLocale) {
750        mConfig->setBcp47Locale(mLocale);
751    } else {
752        mConfig->clearLocale();
753    }
754
755    res->setParameters(mConfig);
756}
757
758Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
759{
760    Asset* ass = NULL;
761    if (ap.idmap.size() != 0) {
762        ass = const_cast<AssetManager*>(this)->
763            openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
764        if (ass) {
765            ALOGV("loading idmap %s\n", ap.idmap.string());
766        } else {
767            ALOGW("failed to load idmap %s\n", ap.idmap.string());
768        }
769    }
770    return ass;
771}
772
773void AssetManager::addSystemOverlays(const char* pathOverlaysList,
774        const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
775{
776    FILE* fin = fopen(pathOverlaysList, "r");
777    if (fin == NULL) {
778        return;
779    }
780
781    char buf[1024];
782    while (fgets(buf, sizeof(buf), fin)) {
783        // format of each line:
784        //   <path to apk><space><path to idmap><newline>
785        char* space = strchr(buf, ' ');
786        char* newline = strchr(buf, '\n');
787        asset_path oap;
788
789        if (space == NULL || newline == NULL || newline < space) {
790            continue;
791        }
792
793        oap.path = String8(buf, space - buf);
794        oap.type = kFileTypeRegular;
795        oap.idmap = String8(space + 1, newline - space - 1);
796        oap.isSystemOverlay = true;
797
798        Asset* oass = const_cast<AssetManager*>(this)->
799            openNonAssetInPathLocked("resources.arsc",
800                    Asset::ACCESS_BUFFER,
801                    oap);
802
803        if (oass != NULL) {
804            Asset* oidmap = openIdmapLocked(oap);
805            offset++;
806            sharedRes->add(oass, oidmap, offset + 1, false);
807            const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
808            const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
809        }
810    }
811    fclose(fin);
812}
813
814const ResTable& AssetManager::getResources(bool required) const
815{
816    const ResTable* rt = getResTable(required);
817    return *rt;
818}
819
820bool AssetManager::isUpToDate()
821{
822    AutoMutex _l(mLock);
823    return mZipSet.isUpToDate();
824}
825
826void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
827{
828    ResTable* res = mResources;
829    if (res != NULL) {
830        res->getLocales(locales, includeSystemLocales);
831    }
832
833    const size_t numLocales = locales->size();
834    for (size_t i = 0; i < numLocales; ++i) {
835        const String8& localeStr = locales->itemAt(i);
836        if (localeStr.find(kTlPrefix) == 0) {
837            String8 replaced("fil");
838            replaced += (localeStr.string() + kTlPrefixLen);
839            locales->editItemAt(i) = replaced;
840        }
841    }
842}
843
844/*
845 * Open a non-asset file as if it were an asset, searching for it in the
846 * specified app.
847 *
848 * Pass in a NULL values for "appName" if the common app directory should
849 * be used.
850 */
851Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
852    const asset_path& ap)
853{
854    Asset* pAsset = NULL;
855
856    /* look at the filesystem on disk */
857    if (ap.type == kFileTypeDirectory) {
858        String8 path(ap.path);
859        path.appendPath(fileName);
860
861        pAsset = openAssetFromFileLocked(path, mode);
862
863        if (pAsset == NULL) {
864            /* try again, this time with ".gz" */
865            path.append(".gz");
866            pAsset = openAssetFromFileLocked(path, mode);
867        }
868
869        if (pAsset != NULL) {
870            //printf("FOUND NA '%s' on disk\n", fileName);
871            pAsset->setAssetSource(path);
872        }
873
874    /* look inside the zip file */
875    } else {
876        String8 path(fileName);
877
878        /* check the appropriate Zip file */
879        ZipFileRO* pZip = getZipFileLocked(ap);
880        if (pZip != NULL) {
881            //printf("GOT zip, checking NA '%s'\n", (const char*) path);
882            ZipEntryRO entry = pZip->findEntryByName(path.string());
883            if (entry != NULL) {
884                //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
885                pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
886                pZip->releaseEntry(entry);
887            }
888        }
889
890        if (pAsset != NULL) {
891            /* create a "source" name, for debug/display */
892            pAsset->setAssetSource(
893                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
894                                                String8(fileName)));
895        }
896    }
897
898    return pAsset;
899}
900
901/*
902 * Open an asset, searching for it in the directory hierarchy for the
903 * specified app.
904 *
905 * Pass in a NULL values for "appName" if the common app directory should
906 * be used.
907 */
908Asset* AssetManager::openInPathLocked(const char* fileName, AccessMode mode,
909    const asset_path& ap)
910{
911    Asset* pAsset = NULL;
912
913    /*
914     * Try various combinations of locale and vendor.
915     */
916    if (mLocale != NULL && mVendor != NULL)
917        pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, mVendor);
918    if (pAsset == NULL && mVendor != NULL)
919        pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, mVendor);
920    if (pAsset == NULL && mLocale != NULL)
921        pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, NULL);
922    if (pAsset == NULL)
923        pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, NULL);
924
925    return pAsset;
926}
927
928/*
929 * Open an asset, searching for it in the directory hierarchy for the
930 * specified locale and vendor.
931 *
932 * We also search in "app.jar".
933 *
934 * Pass in NULL values for "appName", "locale", and "vendor" if the
935 * defaults should be used.
936 */
937Asset* AssetManager::openInLocaleVendorLocked(const char* fileName, AccessMode mode,
938    const asset_path& ap, const char* locale, const char* vendor)
939{
940    Asset* pAsset = NULL;
941
942    if (ap.type == kFileTypeDirectory) {
943        if (mCacheMode == CACHE_OFF) {
944            /* look at the filesystem on disk */
945            String8 path(createPathNameLocked(ap, locale, vendor));
946            path.appendPath(fileName);
947
948            String8 excludeName(path);
949            excludeName.append(kExcludeExtension);
950            if (::getFileType(excludeName.string()) != kFileTypeNonexistent) {
951                /* say no more */
952                //printf("+++ excluding '%s'\n", (const char*) excludeName);
953                return kExcludedAsset;
954            }
955
956            pAsset = openAssetFromFileLocked(path, mode);
957
958            if (pAsset == NULL) {
959                /* try again, this time with ".gz" */
960                path.append(".gz");
961                pAsset = openAssetFromFileLocked(path, mode);
962            }
963
964            if (pAsset != NULL)
965                pAsset->setAssetSource(path);
966        } else {
967            /* find in cache */
968            String8 path(createPathNameLocked(ap, locale, vendor));
969            path.appendPath(fileName);
970
971            AssetDir::FileInfo tmpInfo;
972            bool found = false;
973
974            String8 excludeName(path);
975            excludeName.append(kExcludeExtension);
976
977            if (mCache.indexOf(excludeName) != NAME_NOT_FOUND) {
978                /* go no farther */
979                //printf("+++ Excluding '%s'\n", (const char*) excludeName);
980                return kExcludedAsset;
981            }
982
983            /*
984             * File compression extensions (".gz") don't get stored in the
985             * name cache, so we have to try both here.
986             */
987            if (mCache.indexOf(path) != NAME_NOT_FOUND) {
988                found = true;
989                pAsset = openAssetFromFileLocked(path, mode);
990                if (pAsset == NULL) {
991                    /* try again, this time with ".gz" */
992                    path.append(".gz");
993                    pAsset = openAssetFromFileLocked(path, mode);
994                }
995            }
996
997            if (pAsset != NULL)
998                pAsset->setAssetSource(path);
999
1000            /*
1001             * Don't continue the search into the Zip files.  Our cached info
1002             * said it was a file on disk; to be consistent with openDir()
1003             * we want to return the loose asset.  If the cached file gets
1004             * removed, we fail.
1005             *
1006             * The alternative is to update our cache when files get deleted,
1007             * or make some sort of "best effort" promise, but for now I'm
1008             * taking the hard line.
1009             */
1010            if (found) {
1011                if (pAsset == NULL)
1012                    ALOGD("Expected file not found: '%s'\n", path.string());
1013                return pAsset;
1014            }
1015        }
1016    }
1017
1018    /*
1019     * Either it wasn't found on disk or on the cached view of the disk.
1020     * Dig through the currently-opened set of Zip files.  If caching
1021     * is disabled, the Zip file may get reopened.
1022     */
1023    if (pAsset == NULL && ap.type == kFileTypeRegular) {
1024        String8 path;
1025
1026        path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1027        path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1028        path.appendPath(fileName);
1029
1030        /* check the appropriate Zip file */
1031        ZipFileRO* pZip = getZipFileLocked(ap);
1032        if (pZip != NULL) {
1033            //printf("GOT zip, checking '%s'\n", (const char*) path);
1034            ZipEntryRO entry = pZip->findEntryByName(path.string());
1035            if (entry != NULL) {
1036                //printf("FOUND in Zip file for %s/%s-%s\n",
1037                //    appName, locale, vendor);
1038                pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
1039                pZip->releaseEntry(entry);
1040            }
1041        }
1042
1043        if (pAsset != NULL) {
1044            /* create a "source" name, for debug/display */
1045            pAsset->setAssetSource(createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()),
1046                                                             String8(""), String8(fileName)));
1047        }
1048    }
1049
1050    return pAsset;
1051}
1052
1053/*
1054 * Create a "source name" for a file from a Zip archive.
1055 */
1056String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
1057    const String8& dirName, const String8& fileName)
1058{
1059    String8 sourceName("zip:");
1060    sourceName.append(zipFileName);
1061    sourceName.append(":");
1062    if (dirName.length() > 0) {
1063        sourceName.appendPath(dirName);
1064    }
1065    sourceName.appendPath(fileName);
1066    return sourceName;
1067}
1068
1069/*
1070 * Create a path to a loose asset (asset-base/app/locale/vendor).
1071 */
1072String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
1073    const char* vendor)
1074{
1075    String8 path(ap.path);
1076    path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1077    path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1078    return path;
1079}
1080
1081/*
1082 * Create a path to a loose asset (asset-base/app/rootDir).
1083 */
1084String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
1085{
1086    String8 path(ap.path);
1087    if (rootDir != NULL) path.appendPath(rootDir);
1088    return path;
1089}
1090
1091/*
1092 * Return a pointer to one of our open Zip archives.  Returns NULL if no
1093 * matching Zip file exists.
1094 *
1095 * Right now we have 2 possible Zip files (1 each in app/"common").
1096 *
1097 * If caching is set to CACHE_OFF, to get the expected behavior we
1098 * need to reopen the Zip file on every request.  That would be silly
1099 * and expensive, so instead we just check the file modification date.
1100 *
1101 * Pass in NULL values for "appName", "locale", and "vendor" if the
1102 * generics should be used.
1103 */
1104ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
1105{
1106    ALOGV("getZipFileLocked() in %p\n", this);
1107
1108    return mZipSet.getZip(ap.path);
1109}
1110
1111/*
1112 * Try to open an asset from a file on disk.
1113 *
1114 * If the file is compressed with gzip, we seek to the start of the
1115 * deflated data and pass that in (just like we would for a Zip archive).
1116 *
1117 * For uncompressed data, we may already have an mmap()ed version sitting
1118 * around.  If so, we want to hand that to the Asset instead.
1119 *
1120 * This returns NULL if the file doesn't exist, couldn't be opened, or
1121 * claims to be a ".gz" but isn't.
1122 */
1123Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
1124    AccessMode mode)
1125{
1126    Asset* pAsset = NULL;
1127
1128    if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
1129        //printf("TRYING '%s'\n", (const char*) pathName);
1130        pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
1131    } else {
1132        //printf("TRYING '%s'\n", (const char*) pathName);
1133        pAsset = Asset::createFromFile(pathName.string(), mode);
1134    }
1135
1136    return pAsset;
1137}
1138
1139/*
1140 * Given an entry in a Zip archive, create a new Asset object.
1141 *
1142 * If the entry is uncompressed, we may want to create or share a
1143 * slice of shared memory.
1144 */
1145Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
1146    const ZipEntryRO entry, AccessMode mode, const String8& entryName)
1147{
1148    Asset* pAsset = NULL;
1149
1150    // TODO: look for previously-created shared memory slice?
1151    uint16_t method;
1152    uint32_t uncompressedLen;
1153
1154    //printf("USING Zip '%s'\n", pEntry->getFileName());
1155
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,
1175            static_cast<size_t>(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, dirName.string(), NULL)) {
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 || nameBuf[dirNameLen] == '/')
1556        {
1557            const char* cp;
1558            const char* nextSlash;
1559
1560            cp = nameBuf + dirNameLen;
1561            if (dirNameLen != 0)
1562                cp++;       // advance past the '/'
1563
1564            nextSlash = strchr(cp, '/');
1565//xxx this may break if there are bare directory entries
1566            if (nextSlash == NULL) {
1567                /* this is a file in the requested directory */
1568
1569                info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1570
1571                info.setSourceName(
1572                    createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1573
1574                contents.add(info);
1575                //printf("FOUND: file '%s'\n", info.getFileName().string());
1576            } else {
1577                /* this is a subdir; add it if we don't already have it*/
1578                String8 subdirName(cp, nextSlash - cp);
1579                size_t j;
1580                size_t N = dirs.size();
1581
1582                for (j = 0; j < N; j++) {
1583                    if (subdirName == dirs[j]) {
1584                        break;
1585                    }
1586                }
1587                if (j == N) {
1588                    dirs.add(subdirName);
1589                }
1590
1591                //printf("FOUND: dir '%s'\n", subdirName.string());
1592            }
1593        }
1594    }
1595
1596    pZip->endIteration(iterationCookie);
1597
1598    /*
1599     * Add the set of unique directories.
1600     */
1601    for (int i = 0; i < (int) dirs.size(); i++) {
1602        info.set(dirs[i], kFileTypeDirectory);
1603        info.setSourceName(
1604            createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1605        contents.add(info);
1606    }
1607
1608    mergeInfoLocked(pMergedInfo, &contents);
1609
1610    return true;
1611}
1612
1613
1614/*
1615 * Merge two vectors of FileInfo.
1616 *
1617 * The merged contents will be stuffed into *pMergedInfo.
1618 *
1619 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1620 * we use the newer "pContents" entry.
1621 */
1622void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1623    const SortedVector<AssetDir::FileInfo>* pContents)
1624{
1625    /*
1626     * Merge what we found in this directory with what we found in
1627     * other places.
1628     *
1629     * Two basic approaches:
1630     * (1) Create a new array that holds the unique values of the two
1631     *     arrays.
1632     * (2) Take the elements from pContents and shove them into pMergedInfo.
1633     *
1634     * Because these are vectors of complex objects, moving elements around
1635     * inside the vector requires constructing new objects and allocating
1636     * storage for members.  With approach #1, we're always adding to the
1637     * end, whereas with #2 we could be inserting multiple elements at the
1638     * front of the vector.  Approach #1 requires a full copy of the
1639     * contents of pMergedInfo, but approach #2 requires the same copy for
1640     * every insertion at the front of pMergedInfo.
1641     *
1642     * (We should probably use a SortedVector interface that allows us to
1643     * just stuff items in, trusting us to maintain the sort order.)
1644     */
1645    SortedVector<AssetDir::FileInfo>* pNewSorted;
1646    int mergeMax, contMax;
1647    int mergeIdx, contIdx;
1648
1649    pNewSorted = new SortedVector<AssetDir::FileInfo>;
1650    mergeMax = pMergedInfo->size();
1651    contMax = pContents->size();
1652    mergeIdx = contIdx = 0;
1653
1654    while (mergeIdx < mergeMax || contIdx < contMax) {
1655        if (mergeIdx == mergeMax) {
1656            /* hit end of "merge" list, copy rest of "contents" */
1657            pNewSorted->add(pContents->itemAt(contIdx));
1658            contIdx++;
1659        } else if (contIdx == contMax) {
1660            /* hit end of "cont" list, copy rest of "merge" */
1661            pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1662            mergeIdx++;
1663        } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1664        {
1665            /* items are identical, add newer and advance both indices */
1666            pNewSorted->add(pContents->itemAt(contIdx));
1667            mergeIdx++;
1668            contIdx++;
1669        } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1670        {
1671            /* "merge" is lower, add that one */
1672            pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1673            mergeIdx++;
1674        } else {
1675            /* "cont" is lower, add that one */
1676            assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1677            pNewSorted->add(pContents->itemAt(contIdx));
1678            contIdx++;
1679        }
1680    }
1681
1682    /*
1683     * Overwrite the "merged" list with the new stuff.
1684     */
1685    *pMergedInfo = *pNewSorted;
1686    delete pNewSorted;
1687
1688#if 0       // for Vector, rather than SortedVector
1689    int i, j;
1690    for (i = pContents->size() -1; i >= 0; i--) {
1691        bool add = true;
1692
1693        for (j = pMergedInfo->size() -1; j >= 0; j--) {
1694            /* case-sensitive comparisons, to behave like UNIX fs */
1695            if (strcmp(pContents->itemAt(i).mFileName,
1696                       pMergedInfo->itemAt(j).mFileName) == 0)
1697            {
1698                /* match, don't add this entry */
1699                add = false;
1700                break;
1701            }
1702        }
1703
1704        if (add)
1705            pMergedInfo->add(pContents->itemAt(i));
1706    }
1707#endif
1708}
1709
1710
1711/*
1712 * Load all files into the file name cache.  We want to do this across
1713 * all combinations of { appname, locale, vendor }, performing a recursive
1714 * directory traversal.
1715 *
1716 * This is not the most efficient data structure.  Also, gathering the
1717 * information as we needed it (file-by-file or directory-by-directory)
1718 * would be faster.  However, on the actual device, 99% of the files will
1719 * live in Zip archives, so this list will be very small.  The trouble
1720 * is that we have to check the "loose" files first, so it's important
1721 * that we don't beat the filesystem silly looking for files that aren't
1722 * there.
1723 *
1724 * Note on thread safety: this is the only function that causes updates
1725 * to mCache, and anybody who tries to use it will call here if !mCacheValid,
1726 * so we need to employ a mutex here.
1727 */
1728void AssetManager::loadFileNameCacheLocked(void)
1729{
1730    assert(!mCacheValid);
1731    assert(mCache.size() == 0);
1732
1733#ifdef DO_TIMINGS   // need to link against -lrt for this now
1734    DurationTimer timer;
1735    timer.start();
1736#endif
1737
1738    fncScanLocked(&mCache, "");
1739
1740#ifdef DO_TIMINGS
1741    timer.stop();
1742    ALOGD("Cache scan took %.3fms\n",
1743        timer.durationUsecs() / 1000.0);
1744#endif
1745
1746#if 0
1747    int i;
1748    printf("CACHED FILE LIST (%d entries):\n", mCache.size());
1749    for (i = 0; i < (int) mCache.size(); i++) {
1750        printf(" %d: (%d) '%s'\n", i,
1751            mCache.itemAt(i).getFileType(),
1752            (const char*) mCache.itemAt(i).getFileName());
1753    }
1754#endif
1755
1756    mCacheValid = true;
1757}
1758
1759/*
1760 * Scan up to 8 versions of the specified directory.
1761 */
1762void AssetManager::fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1763    const char* dirName)
1764{
1765    size_t i = mAssetPaths.size();
1766    while (i > 0) {
1767        i--;
1768        const asset_path& ap = mAssetPaths.itemAt(i);
1769        fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, NULL, dirName);
1770        if (mLocale != NULL)
1771            fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, NULL, dirName);
1772        if (mVendor != NULL)
1773            fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, mVendor, dirName);
1774        if (mLocale != NULL && mVendor != NULL)
1775            fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, mVendor, dirName);
1776    }
1777}
1778
1779/*
1780 * Recursively scan this directory and all subdirs.
1781 *
1782 * This is similar to scanAndMergeDir, but we don't remove the .EXCLUDE
1783 * files, and we prepend the extended partial path to the filenames.
1784 */
1785bool AssetManager::fncScanAndMergeDirLocked(
1786    SortedVector<AssetDir::FileInfo>* pMergedInfo,
1787    const asset_path& ap, const char* locale, const char* vendor,
1788    const char* dirName)
1789{
1790    SortedVector<AssetDir::FileInfo>* pContents;
1791    String8 partialPath;
1792    String8 fullPath;
1793
1794    // XXX This is broken -- the filename cache needs to hold the base
1795    // asset path separately from its filename.
1796
1797    partialPath = createPathNameLocked(ap, locale, vendor);
1798    if (dirName[0] != '\0') {
1799        partialPath.appendPath(dirName);
1800    }
1801
1802    fullPath = partialPath;
1803    pContents = scanDirLocked(fullPath);
1804    if (pContents == NULL) {
1805        return false;       // directory did not exist
1806    }
1807
1808    /*
1809     * Scan all subdirectories of the current dir, merging what we find
1810     * into "pMergedInfo".
1811     */
1812    for (int i = 0; i < (int) pContents->size(); i++) {
1813        if (pContents->itemAt(i).getFileType() == kFileTypeDirectory) {
1814            String8 subdir(dirName);
1815            subdir.appendPath(pContents->itemAt(i).getFileName());
1816
1817            fncScanAndMergeDirLocked(pMergedInfo, ap, locale, vendor, subdir.string());
1818        }
1819    }
1820
1821    /*
1822     * To be consistent, we want entries for the root directory.  If
1823     * we're the root, add one now.
1824     */
1825    if (dirName[0] == '\0') {
1826        AssetDir::FileInfo tmpInfo;
1827
1828        tmpInfo.set(String8(""), kFileTypeDirectory);
1829        tmpInfo.setSourceName(createPathNameLocked(ap, locale, vendor));
1830        pContents->add(tmpInfo);
1831    }
1832
1833    /*
1834     * We want to prepend the extended partial path to every entry in
1835     * "pContents".  It's the same value for each entry, so this will
1836     * not change the sorting order of the vector contents.
1837     */
1838    for (int i = 0; i < (int) pContents->size(); i++) {
1839        const AssetDir::FileInfo& info = pContents->itemAt(i);
1840        pContents->editItemAt(i).setFileName(partialPath.appendPathCopy(info.getFileName()));
1841    }
1842
1843    mergeInfoLocked(pMergedInfo, pContents);
1844    delete pContents;
1845    return true;
1846}
1847
1848/*
1849 * Trash the cache.
1850 */
1851void AssetManager::purgeFileNameCacheLocked(void)
1852{
1853    mCacheValid = false;
1854    mCache.clear();
1855}
1856
1857/*
1858 * ===========================================================================
1859 *      AssetManager::SharedZip
1860 * ===========================================================================
1861 */
1862
1863
1864Mutex AssetManager::SharedZip::gLock;
1865DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1866
1867AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1868    : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1869      mResourceTableAsset(NULL), mResourceTable(NULL)
1870{
1871    if (kIsDebug) {
1872        ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1873    }
1874    ALOGV("+++ opening zip '%s'\n", mPath.string());
1875    mZipFile = ZipFileRO::open(mPath.string());
1876    if (mZipFile == NULL) {
1877        ALOGD("failed to open Zip archive '%s'\n", mPath.string());
1878    }
1879}
1880
1881sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1882        bool createIfNotPresent)
1883{
1884    AutoMutex _l(gLock);
1885    time_t modWhen = getFileModDate(path);
1886    sp<SharedZip> zip = gOpen.valueFor(path).promote();
1887    if (zip != NULL && zip->mModWhen == modWhen) {
1888        return zip;
1889    }
1890    if (zip == NULL && !createIfNotPresent) {
1891        return NULL;
1892    }
1893    zip = new SharedZip(path, modWhen);
1894    gOpen.add(path, zip);
1895    return zip;
1896
1897}
1898
1899ZipFileRO* AssetManager::SharedZip::getZip()
1900{
1901    return mZipFile;
1902}
1903
1904Asset* AssetManager::SharedZip::getResourceTableAsset()
1905{
1906    ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1907    return mResourceTableAsset;
1908}
1909
1910Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1911{
1912    {
1913        AutoMutex _l(gLock);
1914        if (mResourceTableAsset == NULL) {
1915            mResourceTableAsset = asset;
1916            // This is not thread safe the first time it is called, so
1917            // do it here with the global lock held.
1918            asset->getBuffer(true);
1919            return asset;
1920        }
1921    }
1922    delete asset;
1923    return mResourceTableAsset;
1924}
1925
1926ResTable* AssetManager::SharedZip::getResourceTable()
1927{
1928    ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1929    return mResourceTable;
1930}
1931
1932ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1933{
1934    {
1935        AutoMutex _l(gLock);
1936        if (mResourceTable == NULL) {
1937            mResourceTable = res;
1938            return res;
1939        }
1940    }
1941    delete res;
1942    return mResourceTable;
1943}
1944
1945bool AssetManager::SharedZip::isUpToDate()
1946{
1947    time_t modWhen = getFileModDate(mPath.string());
1948    return mModWhen == modWhen;
1949}
1950
1951void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1952{
1953    mOverlays.add(ap);
1954}
1955
1956bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1957{
1958    if (idx >= mOverlays.size()) {
1959        return false;
1960    }
1961    *out = mOverlays[idx];
1962    return true;
1963}
1964
1965AssetManager::SharedZip::~SharedZip()
1966{
1967    if (kIsDebug) {
1968        ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1969    }
1970    if (mResourceTable != NULL) {
1971        delete mResourceTable;
1972    }
1973    if (mResourceTableAsset != NULL) {
1974        delete mResourceTableAsset;
1975    }
1976    if (mZipFile != NULL) {
1977        delete mZipFile;
1978        ALOGV("Closed '%s'\n", mPath.string());
1979    }
1980}
1981
1982/*
1983 * ===========================================================================
1984 *      AssetManager::ZipSet
1985 * ===========================================================================
1986 */
1987
1988/*
1989 * Constructor.
1990 */
1991AssetManager::ZipSet::ZipSet(void)
1992{
1993}
1994
1995/*
1996 * Destructor.  Close any open archives.
1997 */
1998AssetManager::ZipSet::~ZipSet(void)
1999{
2000    size_t N = mZipFile.size();
2001    for (size_t i = 0; i < N; i++)
2002        closeZip(i);
2003}
2004
2005/*
2006 * Close a Zip file and reset the entry.
2007 */
2008void AssetManager::ZipSet::closeZip(int idx)
2009{
2010    mZipFile.editItemAt(idx) = NULL;
2011}
2012
2013
2014/*
2015 * Retrieve the appropriate Zip file from the set.
2016 */
2017ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
2018{
2019    int idx = getIndex(path);
2020    sp<SharedZip> zip = mZipFile[idx];
2021    if (zip == NULL) {
2022        zip = SharedZip::get(path);
2023        mZipFile.editItemAt(idx) = zip;
2024    }
2025    return zip->getZip();
2026}
2027
2028Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
2029{
2030    int idx = getIndex(path);
2031    sp<SharedZip> zip = mZipFile[idx];
2032    if (zip == NULL) {
2033        zip = SharedZip::get(path);
2034        mZipFile.editItemAt(idx) = zip;
2035    }
2036    return zip->getResourceTableAsset();
2037}
2038
2039Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
2040                                                 Asset* asset)
2041{
2042    int idx = getIndex(path);
2043    sp<SharedZip> zip = mZipFile[idx];
2044    // doesn't make sense to call before previously accessing.
2045    return zip->setResourceTableAsset(asset);
2046}
2047
2048ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
2049{
2050    int idx = getIndex(path);
2051    sp<SharedZip> zip = mZipFile[idx];
2052    if (zip == NULL) {
2053        zip = SharedZip::get(path);
2054        mZipFile.editItemAt(idx) = zip;
2055    }
2056    return zip->getResourceTable();
2057}
2058
2059ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
2060                                                    ResTable* res)
2061{
2062    int idx = getIndex(path);
2063    sp<SharedZip> zip = mZipFile[idx];
2064    // doesn't make sense to call before previously accessing.
2065    return zip->setResourceTable(res);
2066}
2067
2068/*
2069 * Generate the partial pathname for the specified archive.  The caller
2070 * gets to prepend the asset root directory.
2071 *
2072 * Returns something like "common/en-US-noogle.jar".
2073 */
2074/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
2075{
2076    return String8(zipPath);
2077}
2078
2079bool AssetManager::ZipSet::isUpToDate()
2080{
2081    const size_t N = mZipFile.size();
2082    for (size_t i=0; i<N; i++) {
2083        if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
2084            return false;
2085        }
2086    }
2087    return true;
2088}
2089
2090void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
2091{
2092    int idx = getIndex(path);
2093    sp<SharedZip> zip = mZipFile[idx];
2094    zip->addOverlay(overlay);
2095}
2096
2097bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
2098{
2099    sp<SharedZip> zip = SharedZip::get(path, false);
2100    if (zip == NULL) {
2101        return false;
2102    }
2103    return zip->getOverlay(idx, out);
2104}
2105
2106/*
2107 * Compute the zip file's index.
2108 *
2109 * "appName", "locale", and "vendor" should be set to NULL to indicate the
2110 * default directory.
2111 */
2112int AssetManager::ZipSet::getIndex(const String8& zip) const
2113{
2114    const size_t N = mZipPath.size();
2115    for (size_t i=0; i<N; i++) {
2116        if (mZipPath[i] == zip) {
2117            return i;
2118        }
2119    }
2120
2121    mZipPath.add(zip);
2122    mZipFile.add(NULL);
2123
2124    return mZipPath.size()-1;
2125}
2126