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