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