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