AssetManager.cpp revision 2e0d0f311100d8e0bb40d7d60b8498237f011f0c
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#ifndef _WIN32
39#include <sys/file.h>
40#endif
41
42#include <assert.h>
43#include <dirent.h>
44#include <errno.h>
45#include <string.h> // strerror
46#include <strings.h>
47
48#ifndef TEMP_FAILURE_RETRY
49/* Used to retry syscalls that can return EINTR. */
50#define TEMP_FAILURE_RETRY(exp) ({         \
51    typeof (exp) _rc;                      \
52    do {                                   \
53        _rc = (exp);                       \
54    } while (_rc == -1 && errno == EINTR); \
55    _rc; })
56#endif
57
58using namespace android;
59
60static const bool kIsDebug = false;
61
62static const char* kAssetsRoot = "assets";
63static const char* kAppZipName = NULL; //"classes.jar";
64static const char* kSystemAssets = "framework/framework-res.apk";
65static const char* kResourceCache = "resource-cache";
66
67static const char* kExcludeExtension = ".EXCLUDE";
68
69static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
70
71static volatile int32_t gCount = 0;
72
73const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
74const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
75const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
76const char* AssetManager::OVERLAY_THEME_DIR_PROPERTY = "ro.boot.vendor.overlay.theme";
77const char* AssetManager::OVERLAY_THEME_DIR_PERSIST_PROPERTY = "persist.vendor.overlay.theme";
78const char* AssetManager::TARGET_PACKAGE_NAME = "android";
79const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
80const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
81
82namespace {
83
84String8 idmapPathForPackagePath(const String8& pkgPath) {
85    const char* root = getenv("ANDROID_DATA");
86    LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
87    String8 path(root);
88    path.appendPath(kResourceCache);
89
90    char buf[256]; // 256 chars should be enough for anyone...
91    strncpy(buf, pkgPath.string(), 255);
92    buf[255] = '\0';
93    char* filename = buf;
94    while (*filename && *filename == '/') {
95        ++filename;
96    }
97    char* p = filename;
98    while (*p) {
99        if (*p == '/') {
100            *p = '@';
101        }
102        ++p;
103    }
104    path.appendPath(filename);
105    path.append("@idmap");
106
107    return path;
108}
109
110/*
111 * Like strdup(), but uses C++ "new" operator instead of malloc.
112 */
113static char* strdupNew(const char* str) {
114    char* newStr;
115    int len;
116
117    if (str == NULL)
118        return NULL;
119
120    len = strlen(str);
121    newStr = new char[len+1];
122    memcpy(newStr, str, len+1);
123
124    return newStr;
125}
126
127} // namespace
128
129/*
130 * ===========================================================================
131 *      AssetManager
132 * ===========================================================================
133 */
134
135int32_t AssetManager::getGlobalCount() {
136    return gCount;
137}
138
139AssetManager::AssetManager() :
140        mLocale(NULL), mResources(NULL), mConfig(new ResTable_config) {
141    int count = android_atomic_inc(&gCount) + 1;
142    if (kIsDebug) {
143        ALOGI("Creating AssetManager %p #%d\n", this, count);
144    }
145    memset(mConfig, 0, sizeof(ResTable_config));
146}
147
148AssetManager::~AssetManager() {
149    int count = android_atomic_dec(&gCount);
150    if (kIsDebug) {
151        ALOGI("Destroying AssetManager in %p #%d\n", this, count);
152    }
153
154    delete mConfig;
155    delete mResources;
156
157    // don't have a String class yet, so make sure we clean up
158    delete[] mLocale;
159}
160
161bool AssetManager::addAssetPath(
162        const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset) {
163    AutoMutex _l(mLock);
164
165    asset_path ap;
166
167    String8 realPath(path);
168    if (kAppZipName) {
169        realPath.appendPath(kAppZipName);
170    }
171    ap.type = ::getFileType(realPath.string());
172    if (ap.type == kFileTypeRegular) {
173        ap.path = realPath;
174    } else {
175        ap.path = path;
176        ap.type = ::getFileType(path.string());
177        if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
178            ALOGW("Asset path %s is neither a directory nor file (type=%d).",
179                 path.string(), (int)ap.type);
180            return false;
181        }
182    }
183
184    // Skip if we have it already.
185    for (size_t i=0; i<mAssetPaths.size(); i++) {
186        if (mAssetPaths[i].path == ap.path) {
187            if (cookie) {
188                *cookie = static_cast<int32_t>(i+1);
189            }
190            return true;
191        }
192    }
193
194    ALOGV("In %p Asset %s path: %s", this,
195         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
196
197    ap.isSystemAsset = isSystemAsset;
198    mAssetPaths.add(ap);
199
200    // new paths are always added at the end
201    if (cookie) {
202        *cookie = static_cast<int32_t>(mAssetPaths.size());
203    }
204
205    if (mResources != NULL) {
206        appendPathToResTable(ap, appAsLib);
207    }
208
209    return true;
210}
211
212bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
213{
214    const String8 idmapPath = idmapPathForPackagePath(packagePath);
215
216    AutoMutex _l(mLock);
217
218    for (size_t i = 0; i < mAssetPaths.size(); ++i) {
219        if (mAssetPaths[i].idmap == idmapPath) {
220           *cookie = static_cast<int32_t>(i + 1);
221            return true;
222         }
223     }
224
225    Asset* idmap = NULL;
226    if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
227        ALOGW("failed to open idmap file %s\n", idmapPath.string());
228        return false;
229    }
230
231    String8 targetPath;
232    String8 overlayPath;
233    if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
234                NULL, NULL, NULL, &targetPath, &overlayPath)) {
235        ALOGW("failed to read idmap file %s\n", idmapPath.string());
236        delete idmap;
237        return false;
238    }
239    delete idmap;
240
241    if (overlayPath != packagePath) {
242        ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
243                idmapPath.string(), packagePath.string(), overlayPath.string());
244        return false;
245    }
246    if (access(targetPath.string(), R_OK) != 0) {
247        ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
248        return false;
249    }
250    if (access(idmapPath.string(), R_OK) != 0) {
251        ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
252        return false;
253    }
254    if (access(overlayPath.string(), R_OK) != 0) {
255        ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
256        return false;
257    }
258
259    asset_path oap;
260    oap.path = overlayPath;
261    oap.type = ::getFileType(overlayPath.string());
262    oap.idmap = idmapPath;
263#if 0
264    ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
265            targetPath.string(), overlayPath.string(), idmapPath.string());
266#endif
267    mAssetPaths.add(oap);
268    *cookie = static_cast<int32_t>(mAssetPaths.size());
269
270    if (mResources != NULL) {
271        appendPathToResTable(oap);
272    }
273
274    return true;
275 }
276
277bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
278        uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
279{
280    AutoMutex _l(mLock);
281    const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
282    Asset* assets[2] = {NULL, NULL};
283    bool ret = false;
284    {
285        ResTable tables[2];
286
287        for (int i = 0; i < 2; ++i) {
288            asset_path ap;
289            ap.type = kFileTypeRegular;
290            ap.path = paths[i];
291            assets[i] = openNonAssetInPathLocked("resources.arsc",
292                    Asset::ACCESS_BUFFER, ap);
293            if (assets[i] == NULL) {
294                ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
295                goto exit;
296            }
297            if (tables[i].add(assets[i]) != NO_ERROR) {
298                ALOGW("failed to add %s to resource table", paths[i].string());
299                goto exit;
300            }
301        }
302        ret = tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
303                targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
304    }
305
306exit:
307    delete assets[0];
308    delete assets[1];
309    return ret;
310}
311
312bool AssetManager::addDefaultAssets()
313{
314    const char* root = getenv("ANDROID_ROOT");
315    LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
316
317    String8 path(root);
318    path.appendPath(kSystemAssets);
319
320    return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
321}
322
323int32_t AssetManager::nextAssetPath(const int32_t cookie) const
324{
325    AutoMutex _l(mLock);
326    const size_t next = static_cast<size_t>(cookie) + 1;
327    return next > mAssetPaths.size() ? -1 : next;
328}
329
330String8 AssetManager::getAssetPath(const int32_t cookie) const
331{
332    AutoMutex _l(mLock);
333    const size_t which = static_cast<size_t>(cookie) - 1;
334    if (which < mAssetPaths.size()) {
335        return mAssetPaths[which].path;
336    }
337    return String8();
338}
339
340void AssetManager::setLocaleLocked(const char* locale)
341{
342    if (mLocale != NULL) {
343        delete[] mLocale;
344    }
345
346    mLocale = strdupNew(locale);
347    updateResourceParamsLocked();
348}
349
350void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
351{
352    AutoMutex _l(mLock);
353    *mConfig = config;
354    if (locale) {
355        setLocaleLocked(locale);
356    } else if (config.language[0] != 0) {
357        char spec[RESTABLE_MAX_LOCALE_LEN];
358        config.getBcp47Locale(spec);
359        setLocaleLocked(spec);
360    } else {
361        updateResourceParamsLocked();
362    }
363}
364
365void AssetManager::getConfiguration(ResTable_config* outConfig) const
366{
367    AutoMutex _l(mLock);
368    *outConfig = *mConfig;
369}
370
371/*
372 * Open an asset.
373 *
374 * The data could be in any asset path. Each asset path could be:
375 *  - A directory on disk.
376 *  - A Zip archive, uncompressed or compressed.
377 *
378 * If the file is in a directory, it could have a .gz suffix, meaning it is compressed.
379 *
380 * We should probably reject requests for "illegal" filenames, e.g. those
381 * with illegal characters or "../" backward relative paths.
382 */
383Asset* AssetManager::open(const char* fileName, AccessMode mode)
384{
385    AutoMutex _l(mLock);
386
387    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
388
389    String8 assetName(kAssetsRoot);
390    assetName.appendPath(fileName);
391
392    /*
393     * For each top-level asset path, search for the asset.
394     */
395
396    size_t i = mAssetPaths.size();
397    while (i > 0) {
398        i--;
399        ALOGV("Looking for asset '%s' in '%s'\n",
400                assetName.string(), mAssetPaths.itemAt(i).path.string());
401        Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
402        if (pAsset != NULL) {
403            return pAsset != kExcludedAsset ? pAsset : NULL;
404        }
405    }
406
407    return NULL;
408}
409
410/*
411 * Open a non-asset file as if it were an asset.
412 *
413 * The "fileName" is the partial path starting from the application name.
414 */
415Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
416{
417    AutoMutex _l(mLock);
418
419    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
420
421    /*
422     * For each top-level asset path, search for the asset.
423     */
424
425    size_t i = mAssetPaths.size();
426    while (i > 0) {
427        i--;
428        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
429        Asset* pAsset = openNonAssetInPathLocked(
430            fileName, mode, mAssetPaths.itemAt(i));
431        if (pAsset != NULL) {
432            if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
433            return pAsset != kExcludedAsset ? pAsset : NULL;
434        }
435    }
436
437    return NULL;
438}
439
440Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
441{
442    const size_t which = static_cast<size_t>(cookie) - 1;
443
444    AutoMutex _l(mLock);
445
446    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
447
448    if (which < mAssetPaths.size()) {
449        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
450                mAssetPaths.itemAt(which).path.string());
451        Asset* pAsset = openNonAssetInPathLocked(
452            fileName, mode, mAssetPaths.itemAt(which));
453        if (pAsset != NULL) {
454            return pAsset != kExcludedAsset ? pAsset : NULL;
455        }
456    }
457
458    return NULL;
459}
460
461/*
462 * Get the type of a file in the asset namespace.
463 *
464 * This currently only works for regular files.  All others (including
465 * directories) will return kFileTypeNonexistent.
466 */
467FileType AssetManager::getFileType(const char* fileName)
468{
469    Asset* pAsset = NULL;
470
471    /*
472     * Open the asset.  This is less efficient than simply finding the
473     * file, but it's not too bad (we don't uncompress or mmap data until
474     * the first read() call).
475     */
476    pAsset = open(fileName, Asset::ACCESS_STREAMING);
477    delete pAsset;
478
479    if (pAsset == NULL) {
480        return kFileTypeNonexistent;
481    } else {
482        return kFileTypeRegular;
483    }
484}
485
486bool AssetManager::appendPathToResTable(const asset_path& ap, bool appAsLib) const {
487    Asset* ass = NULL;
488    ResTable* sharedRes = NULL;
489    bool shared = true;
490    bool onlyEmptyResources = true;
491    ATRACE_NAME(ap.path.string());
492    Asset* idmap = openIdmapLocked(ap);
493    size_t nextEntryIdx = mResources->getTableCount();
494    ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
495    if (ap.type != kFileTypeDirectory) {
496        if (nextEntryIdx == 0) {
497            // The first item is typically the framework resources,
498            // which we want to avoid parsing every time.
499            sharedRes = const_cast<AssetManager*>(this)->
500                mZipSet.getZipResourceTable(ap.path);
501            if (sharedRes != NULL) {
502                // skip ahead the number of system overlay packages preloaded
503                nextEntryIdx = sharedRes->getTableCount();
504            }
505        }
506        if (sharedRes == NULL) {
507            ass = const_cast<AssetManager*>(this)->
508                mZipSet.getZipResourceTableAsset(ap.path);
509            if (ass == NULL) {
510                ALOGV("loading resource table %s\n", ap.path.string());
511                ass = const_cast<AssetManager*>(this)->
512                    openNonAssetInPathLocked("resources.arsc",
513                                             Asset::ACCESS_BUFFER,
514                                             ap);
515                if (ass != NULL && ass != kExcludedAsset) {
516                    ass = const_cast<AssetManager*>(this)->
517                        mZipSet.setZipResourceTableAsset(ap.path, ass);
518                }
519            }
520
521            if (nextEntryIdx == 0 && ass != NULL) {
522                // If this is the first resource table in the asset
523                // manager, then we are going to cache it so that we
524                // can quickly copy it out for others.
525                ALOGV("Creating shared resources for %s", ap.path.string());
526                sharedRes = new ResTable();
527                sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
528                sharedRes = const_cast<AssetManager*>(this)->
529                    mZipSet.setZipResourceTable(ap.path, sharedRes);
530            }
531        }
532    } else {
533        ALOGV("loading resource table %s\n", ap.path.string());
534        ass = const_cast<AssetManager*>(this)->
535            openNonAssetInPathLocked("resources.arsc",
536                                     Asset::ACCESS_BUFFER,
537                                     ap);
538        shared = false;
539    }
540
541    if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
542        ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
543        if (sharedRes != NULL) {
544            ALOGV("Copying existing resources for %s", ap.path.string());
545            mResources->add(sharedRes, ap.isSystemAsset);
546        } else {
547            ALOGV("Parsing resources for %s", ap.path.string());
548            mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
549        }
550        onlyEmptyResources = false;
551
552        if (!shared) {
553            delete ass;
554        }
555    } else {
556        ALOGV("Installing empty resources in to table %p\n", mResources);
557        mResources->addEmpty(nextEntryIdx + 1);
558    }
559
560    if (idmap != NULL) {
561        delete idmap;
562    }
563    return onlyEmptyResources;
564}
565
566const ResTable* AssetManager::getResTable(bool required) const
567{
568    ResTable* rt = mResources;
569    if (rt) {
570        return rt;
571    }
572
573    // Iterate through all asset packages, collecting resources from each.
574
575    AutoMutex _l(mLock);
576
577    if (mResources != NULL) {
578        return mResources;
579    }
580
581    if (required) {
582        LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
583    }
584
585    mResources = new ResTable();
586    updateResourceParamsLocked();
587
588    bool onlyEmptyResources = true;
589    const size_t N = mAssetPaths.size();
590    for (size_t i=0; i<N; i++) {
591        bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
592        onlyEmptyResources = onlyEmptyResources && empty;
593    }
594
595    if (required && onlyEmptyResources) {
596        ALOGW("Unable to find resources file resources.arsc");
597        delete mResources;
598        mResources = NULL;
599    }
600
601    return mResources;
602}
603
604void AssetManager::updateResourceParamsLocked() const
605{
606    ATRACE_CALL();
607    ResTable* res = mResources;
608    if (!res) {
609        return;
610    }
611
612    if (mLocale) {
613        mConfig->setBcp47Locale(mLocale);
614    } else {
615        mConfig->clearLocale();
616    }
617
618    res->setParameters(mConfig);
619}
620
621Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
622{
623    Asset* ass = NULL;
624    if (ap.idmap.size() != 0) {
625        ass = const_cast<AssetManager*>(this)->
626            openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
627        if (ass) {
628            ALOGV("loading idmap %s\n", ap.idmap.string());
629        } else {
630            ALOGW("failed to load idmap %s\n", ap.idmap.string());
631        }
632    }
633    return ass;
634}
635
636const ResTable& AssetManager::getResources(bool required) const
637{
638    const ResTable* rt = getResTable(required);
639    return *rt;
640}
641
642bool AssetManager::isUpToDate()
643{
644    AutoMutex _l(mLock);
645    return mZipSet.isUpToDate();
646}
647
648void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
649{
650    ResTable* res = mResources;
651    if (res != NULL) {
652        res->getLocales(locales, includeSystemLocales, true /* mergeEquivalentLangs */);
653    }
654}
655
656/*
657 * Open a non-asset file as if it were an asset, searching for it in the
658 * specified app.
659 *
660 * Pass in a NULL values for "appName" if the common app directory should
661 * be used.
662 */
663Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
664    const asset_path& ap)
665{
666    Asset* pAsset = NULL;
667
668    /* look at the filesystem on disk */
669    if (ap.type == kFileTypeDirectory) {
670        String8 path(ap.path);
671        path.appendPath(fileName);
672
673        pAsset = openAssetFromFileLocked(path, mode);
674
675        if (pAsset == NULL) {
676            /* try again, this time with ".gz" */
677            path.append(".gz");
678            pAsset = openAssetFromFileLocked(path, mode);
679        }
680
681        if (pAsset != NULL) {
682            //printf("FOUND NA '%s' on disk\n", fileName);
683            pAsset->setAssetSource(path);
684        }
685
686    /* look inside the zip file */
687    } else {
688        String8 path(fileName);
689
690        /* check the appropriate Zip file */
691        ZipFileRO* pZip = getZipFileLocked(ap);
692        if (pZip != NULL) {
693            //printf("GOT zip, checking NA '%s'\n", (const char*) path);
694            ZipEntryRO entry = pZip->findEntryByName(path.string());
695            if (entry != NULL) {
696                //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
697                pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
698                pZip->releaseEntry(entry);
699            }
700        }
701
702        if (pAsset != NULL) {
703            /* create a "source" name, for debug/display */
704            pAsset->setAssetSource(
705                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
706                                                String8(fileName)));
707        }
708    }
709
710    return pAsset;
711}
712
713/*
714 * Create a "source name" for a file from a Zip archive.
715 */
716String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
717    const String8& dirName, const String8& fileName)
718{
719    String8 sourceName("zip:");
720    sourceName.append(zipFileName);
721    sourceName.append(":");
722    if (dirName.length() > 0) {
723        sourceName.appendPath(dirName);
724    }
725    sourceName.appendPath(fileName);
726    return sourceName;
727}
728
729/*
730 * Create a path to a loose asset (asset-base/app/rootDir).
731 */
732String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
733{
734    String8 path(ap.path);
735    if (rootDir != NULL) path.appendPath(rootDir);
736    return path;
737}
738
739/*
740 * Return a pointer to one of our open Zip archives.  Returns NULL if no
741 * matching Zip file exists.
742 */
743ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
744{
745    ALOGV("getZipFileLocked() in %p\n", this);
746
747    return mZipSet.getZip(ap.path);
748}
749
750/*
751 * Try to open an asset from a file on disk.
752 *
753 * If the file is compressed with gzip, we seek to the start of the
754 * deflated data and pass that in (just like we would for a Zip archive).
755 *
756 * For uncompressed data, we may already have an mmap()ed version sitting
757 * around.  If so, we want to hand that to the Asset instead.
758 *
759 * This returns NULL if the file doesn't exist, couldn't be opened, or
760 * claims to be a ".gz" but isn't.
761 */
762Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
763    AccessMode mode)
764{
765    Asset* pAsset = NULL;
766
767    if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
768        //printf("TRYING '%s'\n", (const char*) pathName);
769        pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
770    } else {
771        //printf("TRYING '%s'\n", (const char*) pathName);
772        pAsset = Asset::createFromFile(pathName.string(), mode);
773    }
774
775    return pAsset;
776}
777
778/*
779 * Given an entry in a Zip archive, create a new Asset object.
780 *
781 * If the entry is uncompressed, we may want to create or share a
782 * slice of shared memory.
783 */
784Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
785    const ZipEntryRO entry, AccessMode mode, const String8& entryName)
786{
787    Asset* pAsset = NULL;
788
789    // TODO: look for previously-created shared memory slice?
790    uint16_t method;
791    uint32_t uncompressedLen;
792
793    //printf("USING Zip '%s'\n", pEntry->getFileName());
794
795    if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
796            NULL, NULL))
797    {
798        ALOGW("getEntryInfo failed\n");
799        return NULL;
800    }
801
802    FileMap* dataMap = pZipFile->createEntryFileMap(entry);
803    if (dataMap == NULL) {
804        ALOGW("create map from entry failed\n");
805        return NULL;
806    }
807
808    if (method == ZipFileRO::kCompressStored) {
809        pAsset = Asset::createFromUncompressedMap(dataMap, mode);
810        ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
811                dataMap->getFileName(), mode, pAsset);
812    } else {
813        pAsset = Asset::createFromCompressedMap(dataMap,
814            static_cast<size_t>(uncompressedLen), mode);
815        ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
816                dataMap->getFileName(), mode, pAsset);
817    }
818    if (pAsset == NULL) {
819        /* unexpected */
820        ALOGW("create from segment failed\n");
821    }
822
823    return pAsset;
824}
825
826/*
827 * Open a directory in the asset namespace.
828 *
829 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
830 *
831 * Pass in "" for the root dir.
832 */
833AssetDir* AssetManager::openDir(const char* dirName)
834{
835    AutoMutex _l(mLock);
836
837    AssetDir* pDir = NULL;
838    SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
839
840    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
841    assert(dirName != NULL);
842
843    //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
844
845    pDir = new AssetDir;
846
847    /*
848     * Scan the various directories, merging what we find into a single
849     * vector.  We want to scan them in reverse priority order so that
850     * the ".EXCLUDE" processing works correctly.  Also, if we decide we
851     * want to remember where the file is coming from, we'll get the right
852     * version.
853     *
854     * We start with Zip archives, then do loose files.
855     */
856    pMergedInfo = new SortedVector<AssetDir::FileInfo>;
857
858    size_t i = mAssetPaths.size();
859    while (i > 0) {
860        i--;
861        const asset_path& ap = mAssetPaths.itemAt(i);
862        if (ap.type == kFileTypeRegular) {
863            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
864            scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
865        } else {
866            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
867            scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
868        }
869    }
870
871#if 0
872    printf("FILE LIST:\n");
873    for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
874        printf(" %d: (%d) '%s'\n", i,
875            pMergedInfo->itemAt(i).getFileType(),
876            (const char*) pMergedInfo->itemAt(i).getFileName());
877    }
878#endif
879
880    pDir->setFileList(pMergedInfo);
881    return pDir;
882}
883
884/*
885 * Open a directory in the non-asset namespace.
886 *
887 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
888 *
889 * Pass in "" for the root dir.
890 */
891AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
892{
893    AutoMutex _l(mLock);
894
895    AssetDir* pDir = NULL;
896    SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
897
898    LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
899    assert(dirName != NULL);
900
901    //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
902
903    pDir = new AssetDir;
904
905    pMergedInfo = new SortedVector<AssetDir::FileInfo>;
906
907    const size_t which = static_cast<size_t>(cookie) - 1;
908
909    if (which < mAssetPaths.size()) {
910        const asset_path& ap = mAssetPaths.itemAt(which);
911        if (ap.type == kFileTypeRegular) {
912            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
913            scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
914        } else {
915            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
916            scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
917        }
918    }
919
920#if 0
921    printf("FILE LIST:\n");
922    for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
923        printf(" %d: (%d) '%s'\n", i,
924            pMergedInfo->itemAt(i).getFileType(),
925            (const char*) pMergedInfo->itemAt(i).getFileName());
926    }
927#endif
928
929    pDir->setFileList(pMergedInfo);
930    return pDir;
931}
932
933/*
934 * Scan the contents of the specified directory and merge them into the
935 * "pMergedInfo" vector, removing previous entries if we find "exclude"
936 * directives.
937 *
938 * Returns "false" if we found nothing to contribute.
939 */
940bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
941    const asset_path& ap, const char* rootDir, const char* dirName)
942{
943    assert(pMergedInfo != NULL);
944
945    //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
946
947    String8 path = createPathNameLocked(ap, rootDir);
948    if (dirName[0] != '\0')
949        path.appendPath(dirName);
950
951    SortedVector<AssetDir::FileInfo>* pContents = scanDirLocked(path);
952    if (pContents == NULL)
953        return false;
954
955    // if we wanted to do an incremental cache fill, we would do it here
956
957    /*
958     * Process "exclude" directives.  If we find a filename that ends with
959     * ".EXCLUDE", we look for a matching entry in the "merged" set, and
960     * remove it if we find it.  We also delete the "exclude" entry.
961     */
962    int i, count, exclExtLen;
963
964    count = pContents->size();
965    exclExtLen = strlen(kExcludeExtension);
966    for (i = 0; i < count; i++) {
967        const char* name;
968        int nameLen;
969
970        name = pContents->itemAt(i).getFileName().string();
971        nameLen = strlen(name);
972        if (nameLen > exclExtLen &&
973            strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
974        {
975            String8 match(name, nameLen - exclExtLen);
976            int matchIdx;
977
978            matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
979            if (matchIdx > 0) {
980                ALOGV("Excluding '%s' [%s]\n",
981                    pMergedInfo->itemAt(matchIdx).getFileName().string(),
982                    pMergedInfo->itemAt(matchIdx).getSourceName().string());
983                pMergedInfo->removeAt(matchIdx);
984            } else {
985                //printf("+++ no match on '%s'\n", (const char*) match);
986            }
987
988            ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
989            pContents->removeAt(i);
990            i--;        // adjust "for" loop
991            count--;    //  and loop limit
992        }
993    }
994
995    mergeInfoLocked(pMergedInfo, pContents);
996
997    delete pContents;
998
999    return true;
1000}
1001
1002/*
1003 * Scan the contents of the specified directory, and stuff what we find
1004 * into a newly-allocated vector.
1005 *
1006 * Files ending in ".gz" will have their extensions removed.
1007 *
1008 * We should probably think about skipping files with "illegal" names,
1009 * e.g. illegal characters (/\:) or excessive length.
1010 *
1011 * Returns NULL if the specified directory doesn't exist.
1012 */
1013SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1014{
1015    SortedVector<AssetDir::FileInfo>* pContents = NULL;
1016    DIR* dir;
1017    struct dirent* entry;
1018    FileType fileType;
1019
1020    ALOGV("Scanning dir '%s'\n", path.string());
1021
1022    dir = opendir(path.string());
1023    if (dir == NULL)
1024        return NULL;
1025
1026    pContents = new SortedVector<AssetDir::FileInfo>;
1027
1028    while (1) {
1029        entry = readdir(dir);
1030        if (entry == NULL)
1031            break;
1032
1033        if (strcmp(entry->d_name, ".") == 0 ||
1034            strcmp(entry->d_name, "..") == 0)
1035            continue;
1036
1037#ifdef _DIRENT_HAVE_D_TYPE
1038        if (entry->d_type == DT_REG)
1039            fileType = kFileTypeRegular;
1040        else if (entry->d_type == DT_DIR)
1041            fileType = kFileTypeDirectory;
1042        else
1043            fileType = kFileTypeUnknown;
1044#else
1045        // stat the file
1046        fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1047#endif
1048
1049        if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1050            continue;
1051
1052        AssetDir::FileInfo info;
1053        info.set(String8(entry->d_name), fileType);
1054        if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1055            info.setFileName(info.getFileName().getBasePath());
1056        info.setSourceName(path.appendPathCopy(info.getFileName()));
1057        pContents->add(info);
1058    }
1059
1060    closedir(dir);
1061    return pContents;
1062}
1063
1064/*
1065 * Scan the contents out of the specified Zip archive, and merge what we
1066 * find into "pMergedInfo".  If the Zip archive in question doesn't exist,
1067 * we return immediately.
1068 *
1069 * Returns "false" if we found nothing to contribute.
1070 */
1071bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1072    const asset_path& ap, const char* rootDir, const char* baseDirName)
1073{
1074    ZipFileRO* pZip;
1075    Vector<String8> dirs;
1076    AssetDir::FileInfo info;
1077    SortedVector<AssetDir::FileInfo> contents;
1078    String8 sourceName, zipName, dirName;
1079
1080    pZip = mZipSet.getZip(ap.path);
1081    if (pZip == NULL) {
1082        ALOGW("Failure opening zip %s\n", ap.path.string());
1083        return false;
1084    }
1085
1086    zipName = ZipSet::getPathName(ap.path.string());
1087
1088    /* convert "sounds" to "rootDir/sounds" */
1089    if (rootDir != NULL) dirName = rootDir;
1090    dirName.appendPath(baseDirName);
1091
1092    /*
1093     * Scan through the list of files, looking for a match.  The files in
1094     * the Zip table of contents are not in sorted order, so we have to
1095     * process the entire list.  We're looking for a string that begins
1096     * with the characters in "dirName", is followed by a '/', and has no
1097     * subsequent '/' in the stuff that follows.
1098     *
1099     * What makes this especially fun is that directories are not stored
1100     * explicitly in Zip archives, so we have to infer them from context.
1101     * When we see "sounds/foo.wav" we have to leave a note to ourselves
1102     * to insert a directory called "sounds" into the list.  We store
1103     * these in temporary vector so that we only return each one once.
1104     *
1105     * Name comparisons are case-sensitive to match UNIX filesystem
1106     * semantics.
1107     */
1108    int dirNameLen = dirName.length();
1109    void *iterationCookie;
1110    if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
1111        ALOGW("ZipFileRO::startIteration returned false");
1112        return false;
1113    }
1114
1115    ZipEntryRO entry;
1116    while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
1117        char nameBuf[256];
1118
1119        if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1120            // TODO: fix this if we expect to have long names
1121            ALOGE("ARGH: name too long?\n");
1122            continue;
1123        }
1124        //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
1125        if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
1126        {
1127            const char* cp;
1128            const char* nextSlash;
1129
1130            cp = nameBuf + dirNameLen;
1131            if (dirNameLen != 0)
1132                cp++;       // advance past the '/'
1133
1134            nextSlash = strchr(cp, '/');
1135//xxx this may break if there are bare directory entries
1136            if (nextSlash == NULL) {
1137                /* this is a file in the requested directory */
1138
1139                info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1140
1141                info.setSourceName(
1142                    createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1143
1144                contents.add(info);
1145                //printf("FOUND: file '%s'\n", info.getFileName().string());
1146            } else {
1147                /* this is a subdir; add it if we don't already have it*/
1148                String8 subdirName(cp, nextSlash - cp);
1149                size_t j;
1150                size_t N = dirs.size();
1151
1152                for (j = 0; j < N; j++) {
1153                    if (subdirName == dirs[j]) {
1154                        break;
1155                    }
1156                }
1157                if (j == N) {
1158                    dirs.add(subdirName);
1159                }
1160
1161                //printf("FOUND: dir '%s'\n", subdirName.string());
1162            }
1163        }
1164    }
1165
1166    pZip->endIteration(iterationCookie);
1167
1168    /*
1169     * Add the set of unique directories.
1170     */
1171    for (int i = 0; i < (int) dirs.size(); i++) {
1172        info.set(dirs[i], kFileTypeDirectory);
1173        info.setSourceName(
1174            createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1175        contents.add(info);
1176    }
1177
1178    mergeInfoLocked(pMergedInfo, &contents);
1179
1180    return true;
1181}
1182
1183
1184/*
1185 * Merge two vectors of FileInfo.
1186 *
1187 * The merged contents will be stuffed into *pMergedInfo.
1188 *
1189 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1190 * we use the newer "pContents" entry.
1191 */
1192void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1193    const SortedVector<AssetDir::FileInfo>* pContents)
1194{
1195    /*
1196     * Merge what we found in this directory with what we found in
1197     * other places.
1198     *
1199     * Two basic approaches:
1200     * (1) Create a new array that holds the unique values of the two
1201     *     arrays.
1202     * (2) Take the elements from pContents and shove them into pMergedInfo.
1203     *
1204     * Because these are vectors of complex objects, moving elements around
1205     * inside the vector requires constructing new objects and allocating
1206     * storage for members.  With approach #1, we're always adding to the
1207     * end, whereas with #2 we could be inserting multiple elements at the
1208     * front of the vector.  Approach #1 requires a full copy of the
1209     * contents of pMergedInfo, but approach #2 requires the same copy for
1210     * every insertion at the front of pMergedInfo.
1211     *
1212     * (We should probably use a SortedVector interface that allows us to
1213     * just stuff items in, trusting us to maintain the sort order.)
1214     */
1215    SortedVector<AssetDir::FileInfo>* pNewSorted;
1216    int mergeMax, contMax;
1217    int mergeIdx, contIdx;
1218
1219    pNewSorted = new SortedVector<AssetDir::FileInfo>;
1220    mergeMax = pMergedInfo->size();
1221    contMax = pContents->size();
1222    mergeIdx = contIdx = 0;
1223
1224    while (mergeIdx < mergeMax || contIdx < contMax) {
1225        if (mergeIdx == mergeMax) {
1226            /* hit end of "merge" list, copy rest of "contents" */
1227            pNewSorted->add(pContents->itemAt(contIdx));
1228            contIdx++;
1229        } else if (contIdx == contMax) {
1230            /* hit end of "cont" list, copy rest of "merge" */
1231            pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1232            mergeIdx++;
1233        } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1234        {
1235            /* items are identical, add newer and advance both indices */
1236            pNewSorted->add(pContents->itemAt(contIdx));
1237            mergeIdx++;
1238            contIdx++;
1239        } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1240        {
1241            /* "merge" is lower, add that one */
1242            pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1243            mergeIdx++;
1244        } else {
1245            /* "cont" is lower, add that one */
1246            assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1247            pNewSorted->add(pContents->itemAt(contIdx));
1248            contIdx++;
1249        }
1250    }
1251
1252    /*
1253     * Overwrite the "merged" list with the new stuff.
1254     */
1255    *pMergedInfo = *pNewSorted;
1256    delete pNewSorted;
1257
1258#if 0       // for Vector, rather than SortedVector
1259    int i, j;
1260    for (i = pContents->size() -1; i >= 0; i--) {
1261        bool add = true;
1262
1263        for (j = pMergedInfo->size() -1; j >= 0; j--) {
1264            /* case-sensitive comparisons, to behave like UNIX fs */
1265            if (strcmp(pContents->itemAt(i).mFileName,
1266                       pMergedInfo->itemAt(j).mFileName) == 0)
1267            {
1268                /* match, don't add this entry */
1269                add = false;
1270                break;
1271            }
1272        }
1273
1274        if (add)
1275            pMergedInfo->add(pContents->itemAt(i));
1276    }
1277#endif
1278}
1279
1280/*
1281 * ===========================================================================
1282 *      AssetManager::SharedZip
1283 * ===========================================================================
1284 */
1285
1286
1287Mutex AssetManager::SharedZip::gLock;
1288DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1289
1290AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1291    : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1292      mResourceTableAsset(NULL), mResourceTable(NULL)
1293{
1294    if (kIsDebug) {
1295        ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1296    }
1297    ALOGV("+++ opening zip '%s'\n", mPath.string());
1298    mZipFile = ZipFileRO::open(mPath.string());
1299    if (mZipFile == NULL) {
1300        ALOGD("failed to open Zip archive '%s'\n", mPath.string());
1301    }
1302}
1303
1304sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1305        bool createIfNotPresent)
1306{
1307    AutoMutex _l(gLock);
1308    time_t modWhen = getFileModDate(path);
1309    sp<SharedZip> zip = gOpen.valueFor(path).promote();
1310    if (zip != NULL && zip->mModWhen == modWhen) {
1311        return zip;
1312    }
1313    if (zip == NULL && !createIfNotPresent) {
1314        return NULL;
1315    }
1316    zip = new SharedZip(path, modWhen);
1317    gOpen.add(path, zip);
1318    return zip;
1319
1320}
1321
1322ZipFileRO* AssetManager::SharedZip::getZip()
1323{
1324    return mZipFile;
1325}
1326
1327Asset* AssetManager::SharedZip::getResourceTableAsset()
1328{
1329    AutoMutex _l(gLock);
1330    ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1331    return mResourceTableAsset;
1332}
1333
1334Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1335{
1336    {
1337        AutoMutex _l(gLock);
1338        if (mResourceTableAsset == NULL) {
1339            // This is not thread safe the first time it is called, so
1340            // do it here with the global lock held.
1341            asset->getBuffer(true);
1342            mResourceTableAsset = asset;
1343            return asset;
1344        }
1345    }
1346    delete asset;
1347    return mResourceTableAsset;
1348}
1349
1350ResTable* AssetManager::SharedZip::getResourceTable()
1351{
1352    ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1353    return mResourceTable;
1354}
1355
1356ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1357{
1358    {
1359        AutoMutex _l(gLock);
1360        if (mResourceTable == NULL) {
1361            mResourceTable = res;
1362            return res;
1363        }
1364    }
1365    delete res;
1366    return mResourceTable;
1367}
1368
1369bool AssetManager::SharedZip::isUpToDate()
1370{
1371    time_t modWhen = getFileModDate(mPath.string());
1372    return mModWhen == modWhen;
1373}
1374
1375AssetManager::SharedZip::~SharedZip()
1376{
1377    if (kIsDebug) {
1378        ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1379    }
1380    if (mResourceTable != NULL) {
1381        delete mResourceTable;
1382    }
1383    if (mResourceTableAsset != NULL) {
1384        delete mResourceTableAsset;
1385    }
1386    if (mZipFile != NULL) {
1387        delete mZipFile;
1388        ALOGV("Closed '%s'\n", mPath.string());
1389    }
1390}
1391
1392/*
1393 * ===========================================================================
1394 *      AssetManager::ZipSet
1395 * ===========================================================================
1396 */
1397
1398/*
1399 * Destructor.  Close any open archives.
1400 */
1401AssetManager::ZipSet::~ZipSet(void)
1402{
1403    size_t N = mZipFile.size();
1404    for (size_t i = 0; i < N; i++)
1405        closeZip(i);
1406}
1407
1408/*
1409 * Close a Zip file and reset the entry.
1410 */
1411void AssetManager::ZipSet::closeZip(int idx)
1412{
1413    mZipFile.editItemAt(idx) = NULL;
1414}
1415
1416
1417/*
1418 * Retrieve the appropriate Zip file from the set.
1419 */
1420ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1421{
1422    int idx = getIndex(path);
1423    sp<SharedZip> zip = mZipFile[idx];
1424    if (zip == NULL) {
1425        zip = SharedZip::get(path);
1426        mZipFile.editItemAt(idx) = zip;
1427    }
1428    return zip->getZip();
1429}
1430
1431Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
1432{
1433    int idx = getIndex(path);
1434    sp<SharedZip> zip = mZipFile[idx];
1435    if (zip == NULL) {
1436        zip = SharedZip::get(path);
1437        mZipFile.editItemAt(idx) = zip;
1438    }
1439    return zip->getResourceTableAsset();
1440}
1441
1442Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
1443                                                 Asset* asset)
1444{
1445    int idx = getIndex(path);
1446    sp<SharedZip> zip = mZipFile[idx];
1447    // doesn't make sense to call before previously accessing.
1448    return zip->setResourceTableAsset(asset);
1449}
1450
1451ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
1452{
1453    int idx = getIndex(path);
1454    sp<SharedZip> zip = mZipFile[idx];
1455    if (zip == NULL) {
1456        zip = SharedZip::get(path);
1457        mZipFile.editItemAt(idx) = zip;
1458    }
1459    return zip->getResourceTable();
1460}
1461
1462ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
1463                                                    ResTable* res)
1464{
1465    int idx = getIndex(path);
1466    sp<SharedZip> zip = mZipFile[idx];
1467    // doesn't make sense to call before previously accessing.
1468    return zip->setResourceTable(res);
1469}
1470
1471/*
1472 * Generate the partial pathname for the specified archive.  The caller
1473 * gets to prepend the asset root directory.
1474 *
1475 * Returns something like "common/en-US-noogle.jar".
1476 */
1477/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
1478{
1479    return String8(zipPath);
1480}
1481
1482bool AssetManager::ZipSet::isUpToDate()
1483{
1484    const size_t N = mZipFile.size();
1485    for (size_t i=0; i<N; i++) {
1486        if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
1487            return false;
1488        }
1489    }
1490    return true;
1491}
1492
1493/*
1494 * Compute the zip file's index.
1495 *
1496 * "appName", "locale", and "vendor" should be set to NULL to indicate the
1497 * default directory.
1498 */
1499int AssetManager::ZipSet::getIndex(const String8& zip) const
1500{
1501    const size_t N = mZipPath.size();
1502    for (size_t i=0; i<N; i++) {
1503        if (mZipPath[i] == zip) {
1504            return i;
1505        }
1506    }
1507
1508    mZipPath.add(zip);
1509    mZipFile.add(NULL);
1510
1511    return mZipPath.size()-1;
1512}
1513