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