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