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