blob: 0b4d1acad1306b920e1bfd24626e3db3df790067 [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 }
Mårten Kongstad2b91c672011-05-05 10:40:42 +0200683 if (idmap != NULL) {
684 delete idmap;
685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 }
687
688 if (required && !rt) LOGW("Unable to find resources file resources.arsc");
689 if (!rt) {
690 mResources = rt = new ResTable();
691 }
692 return rt;
693}
694
695void AssetManager::updateResourceParamsLocked() const
696{
697 ResTable* res = mResources;
698 if (!res) {
699 return;
700 }
701
702 size_t llen = mLocale ? strlen(mLocale) : 0;
703 mConfig->language[0] = 0;
704 mConfig->language[1] = 0;
705 mConfig->country[0] = 0;
706 mConfig->country[1] = 0;
707 if (llen >= 2) {
708 mConfig->language[0] = mLocale[0];
709 mConfig->language[1] = mLocale[1];
710 }
711 if (llen >= 5) {
712 mConfig->country[0] = mLocale[3];
713 mConfig->country[1] = mLocale[4];
714 }
715 mConfig->size = sizeof(*mConfig);
716
717 res->setParameters(mConfig);
718}
719
Mårten Kongstad57f4b772011-03-17 14:13:41 +0100720Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
721{
722 Asset* ass = NULL;
723 if (ap.idmap.size() != 0) {
724 ass = const_cast<AssetManager*>(this)->
725 openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
726 if (ass) {
727 LOGV("loading idmap %s\n", ap.idmap.string());
728 } else {
729 LOGW("failed to load idmap %s\n", ap.idmap.string());
730 }
731 }
732 return ass;
733}
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735const ResTable& AssetManager::getResources(bool required) const
736{
737 const ResTable* rt = getResTable(required);
738 return *rt;
739}
740
741bool AssetManager::isUpToDate()
742{
743 AutoMutex _l(mLock);
744 return mZipSet.isUpToDate();
745}
746
747void AssetManager::getLocales(Vector<String8>* locales) const
748{
749 ResTable* res = mResources;
750 if (res != NULL) {
751 res->getLocales(locales);
752 }
753}
754
755/*
756 * Open a non-asset file as if it were an asset, searching for it in the
757 * specified app.
758 *
759 * Pass in a NULL values for "appName" if the common app directory should
760 * be used.
761 */
762Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
763 const asset_path& ap)
764{
765 Asset* pAsset = NULL;
766
767 /* look at the filesystem on disk */
768 if (ap.type == kFileTypeDirectory) {
769 String8 path(ap.path);
770 path.appendPath(fileName);
771
772 pAsset = openAssetFromFileLocked(path, mode);
773
774 if (pAsset == NULL) {
775 /* try again, this time with ".gz" */
776 path.append(".gz");
777 pAsset = openAssetFromFileLocked(path, mode);
778 }
779
780 if (pAsset != NULL) {
781 //printf("FOUND NA '%s' on disk\n", fileName);
782 pAsset->setAssetSource(path);
783 }
784
785 /* look inside the zip file */
786 } else {
787 String8 path(fileName);
788
789 /* check the appropriate Zip file */
790 ZipFileRO* pZip;
791 ZipEntryRO entry;
792
793 pZip = getZipFileLocked(ap);
794 if (pZip != NULL) {
795 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
796 entry = pZip->findEntryByName(path.string());
797 if (entry != NULL) {
798 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
799 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
800 }
801 }
802
803 if (pAsset != NULL) {
804 /* create a "source" name, for debug/display */
805 pAsset->setAssetSource(
806 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
807 String8(fileName)));
808 }
809 }
810
811 return pAsset;
812}
813
814/*
815 * Open an asset, searching for it in the directory hierarchy for the
816 * specified app.
817 *
818 * Pass in a NULL values for "appName" if the common app directory should
819 * be used.
820 */
821Asset* AssetManager::openInPathLocked(const char* fileName, AccessMode mode,
822 const asset_path& ap)
823{
824 Asset* pAsset = NULL;
825
826 /*
827 * Try various combinations of locale and vendor.
828 */
829 if (mLocale != NULL && mVendor != NULL)
830 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, mVendor);
831 if (pAsset == NULL && mVendor != NULL)
832 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, mVendor);
833 if (pAsset == NULL && mLocale != NULL)
834 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, NULL);
835 if (pAsset == NULL)
836 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, NULL);
837
838 return pAsset;
839}
840
841/*
842 * Open an asset, searching for it in the directory hierarchy for the
843 * specified locale and vendor.
844 *
845 * We also search in "app.jar".
846 *
847 * Pass in NULL values for "appName", "locale", and "vendor" if the
848 * defaults should be used.
849 */
850Asset* AssetManager::openInLocaleVendorLocked(const char* fileName, AccessMode mode,
851 const asset_path& ap, const char* locale, const char* vendor)
852{
853 Asset* pAsset = NULL;
854
855 if (ap.type == kFileTypeDirectory) {
856 if (mCacheMode == CACHE_OFF) {
857 /* look at the filesystem on disk */
858 String8 path(createPathNameLocked(ap, locale, vendor));
859 path.appendPath(fileName);
860
861 String8 excludeName(path);
862 excludeName.append(kExcludeExtension);
863 if (::getFileType(excludeName.string()) != kFileTypeNonexistent) {
864 /* say no more */
865 //printf("+++ excluding '%s'\n", (const char*) excludeName);
866 return kExcludedAsset;
867 }
868
869 pAsset = openAssetFromFileLocked(path, mode);
870
871 if (pAsset == NULL) {
872 /* try again, this time with ".gz" */
873 path.append(".gz");
874 pAsset = openAssetFromFileLocked(path, mode);
875 }
876
877 if (pAsset != NULL)
878 pAsset->setAssetSource(path);
879 } else {
880 /* find in cache */
881 String8 path(createPathNameLocked(ap, locale, vendor));
882 path.appendPath(fileName);
883
884 AssetDir::FileInfo tmpInfo;
885 bool found = false;
886
887 String8 excludeName(path);
888 excludeName.append(kExcludeExtension);
889
890 if (mCache.indexOf(excludeName) != NAME_NOT_FOUND) {
891 /* go no farther */
892 //printf("+++ Excluding '%s'\n", (const char*) excludeName);
893 return kExcludedAsset;
894 }
895
896 /*
897 * File compression extensions (".gz") don't get stored in the
898 * name cache, so we have to try both here.
899 */
900 if (mCache.indexOf(path) != NAME_NOT_FOUND) {
901 found = true;
902 pAsset = openAssetFromFileLocked(path, mode);
903 if (pAsset == NULL) {
904 /* try again, this time with ".gz" */
905 path.append(".gz");
906 pAsset = openAssetFromFileLocked(path, mode);
907 }
908 }
909
910 if (pAsset != NULL)
911 pAsset->setAssetSource(path);
912
913 /*
914 * Don't continue the search into the Zip files. Our cached info
915 * said it was a file on disk; to be consistent with openDir()
916 * we want to return the loose asset. If the cached file gets
917 * removed, we fail.
918 *
919 * The alternative is to update our cache when files get deleted,
920 * or make some sort of "best effort" promise, but for now I'm
921 * taking the hard line.
922 */
923 if (found) {
924 if (pAsset == NULL)
925 LOGD("Expected file not found: '%s'\n", path.string());
926 return pAsset;
927 }
928 }
929 }
930
931 /*
932 * Either it wasn't found on disk or on the cached view of the disk.
933 * Dig through the currently-opened set of Zip files. If caching
934 * is disabled, the Zip file may get reopened.
935 */
936 if (pAsset == NULL && ap.type == kFileTypeRegular) {
937 String8 path;
938
939 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
940 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
941 path.appendPath(fileName);
942
943 /* check the appropriate Zip file */
944 ZipFileRO* pZip;
945 ZipEntryRO entry;
946
947 pZip = getZipFileLocked(ap);
948 if (pZip != NULL) {
949 //printf("GOT zip, checking '%s'\n", (const char*) path);
950 entry = pZip->findEntryByName(path.string());
951 if (entry != NULL) {
952 //printf("FOUND in Zip file for %s/%s-%s\n",
953 // appName, locale, vendor);
954 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
955 }
956 }
957
958 if (pAsset != NULL) {
959 /* create a "source" name, for debug/display */
960 pAsset->setAssetSource(createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()),
961 String8(""), String8(fileName)));
962 }
963 }
964
965 return pAsset;
966}
967
968/*
969 * Create a "source name" for a file from a Zip archive.
970 */
971String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
972 const String8& dirName, const String8& fileName)
973{
974 String8 sourceName("zip:");
975 sourceName.append(zipFileName);
976 sourceName.append(":");
977 if (dirName.length() > 0) {
978 sourceName.appendPath(dirName);
979 }
980 sourceName.appendPath(fileName);
981 return sourceName;
982}
983
984/*
985 * Create a path to a loose asset (asset-base/app/locale/vendor).
986 */
987String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
988 const char* vendor)
989{
990 String8 path(ap.path);
991 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
992 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
993 return path;
994}
995
996/*
997 * Create a path to a loose asset (asset-base/app/rootDir).
998 */
999String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
1000{
1001 String8 path(ap.path);
1002 if (rootDir != NULL) path.appendPath(rootDir);
1003 return path;
1004}
1005
1006/*
1007 * Return a pointer to one of our open Zip archives. Returns NULL if no
1008 * matching Zip file exists.
1009 *
1010 * Right now we have 2 possible Zip files (1 each in app/"common").
1011 *
1012 * If caching is set to CACHE_OFF, to get the expected behavior we
1013 * need to reopen the Zip file on every request. That would be silly
1014 * and expensive, so instead we just check the file modification date.
1015 *
1016 * Pass in NULL values for "appName", "locale", and "vendor" if the
1017 * generics should be used.
1018 */
1019ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
1020{
1021 LOGV("getZipFileLocked() in %p\n", this);
1022
1023 return mZipSet.getZip(ap.path);
1024}
1025
1026/*
1027 * Try to open an asset from a file on disk.
1028 *
1029 * If the file is compressed with gzip, we seek to the start of the
1030 * deflated data and pass that in (just like we would for a Zip archive).
1031 *
1032 * For uncompressed data, we may already have an mmap()ed version sitting
1033 * around. If so, we want to hand that to the Asset instead.
1034 *
1035 * This returns NULL if the file doesn't exist, couldn't be opened, or
1036 * claims to be a ".gz" but isn't.
1037 */
1038Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
1039 AccessMode mode)
1040{
1041 Asset* pAsset = NULL;
1042
1043 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
1044 //printf("TRYING '%s'\n", (const char*) pathName);
1045 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
1046 } else {
1047 //printf("TRYING '%s'\n", (const char*) pathName);
1048 pAsset = Asset::createFromFile(pathName.string(), mode);
1049 }
1050
1051 return pAsset;
1052}
1053
1054/*
1055 * Given an entry in a Zip archive, create a new Asset object.
1056 *
1057 * If the entry is uncompressed, we may want to create or share a
1058 * slice of shared memory.
1059 */
1060Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
1061 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
1062{
1063 Asset* pAsset = NULL;
1064
1065 // TODO: look for previously-created shared memory slice?
1066 int method;
Kenny Root68246dc2010-04-22 18:28:29 -07001067 size_t uncompressedLen;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068
1069 //printf("USING Zip '%s'\n", pEntry->getFileName());
1070
1071 //pZipFile->getEntryInfo(entry, &method, &uncompressedLen, &compressedLen,
1072 // &offset);
1073 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
1074 NULL, NULL))
1075 {
1076 LOGW("getEntryInfo failed\n");
1077 return NULL;
1078 }
1079
1080 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
1081 if (dataMap == NULL) {
1082 LOGW("create map from entry failed\n");
1083 return NULL;
1084 }
1085
1086 if (method == ZipFileRO::kCompressStored) {
1087 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
1088 LOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
1089 dataMap->getFileName(), mode, pAsset);
1090 } else {
1091 pAsset = Asset::createFromCompressedMap(dataMap, method,
1092 uncompressedLen, mode);
1093 LOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
1094 dataMap->getFileName(), mode, pAsset);
1095 }
1096 if (pAsset == NULL) {
1097 /* unexpected */
1098 LOGW("create from segment failed\n");
1099 }
1100
1101 return pAsset;
1102}
1103
1104
1105
1106/*
1107 * Open a directory in the asset namespace.
1108 *
1109 * An "asset directory" is simply the combination of all files in all
1110 * locations, with ".gz" stripped for loose files. With app, locale, and
1111 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1112 *
1113 * Pass in "" for the root dir.
1114 */
1115AssetDir* AssetManager::openDir(const char* dirName)
1116{
1117 AutoMutex _l(mLock);
1118
1119 AssetDir* pDir = NULL;
1120 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1121
1122 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1123 assert(dirName != NULL);
1124
1125 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1126
1127 if (mCacheMode != CACHE_OFF && !mCacheValid)
1128 loadFileNameCacheLocked();
1129
1130 pDir = new AssetDir;
1131
1132 /*
1133 * Scan the various directories, merging what we find into a single
1134 * vector. We want to scan them in reverse priority order so that
1135 * the ".EXCLUDE" processing works correctly. Also, if we decide we
1136 * want to remember where the file is coming from, we'll get the right
1137 * version.
1138 *
1139 * We start with Zip archives, then do loose files.
1140 */
1141 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1142
1143 size_t i = mAssetPaths.size();
1144 while (i > 0) {
1145 i--;
1146 const asset_path& ap = mAssetPaths.itemAt(i);
1147 if (ap.type == kFileTypeRegular) {
1148 LOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1149 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1150 } else {
1151 LOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1152 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1153 }
1154 }
1155
1156#if 0
1157 printf("FILE LIST:\n");
1158 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1159 printf(" %d: (%d) '%s'\n", i,
1160 pMergedInfo->itemAt(i).getFileType(),
1161 (const char*) pMergedInfo->itemAt(i).getFileName());
1162 }
1163#endif
1164
1165 pDir->setFileList(pMergedInfo);
1166 return pDir;
1167}
1168
1169/*
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001170 * Open a directory in the non-asset namespace.
1171 *
1172 * An "asset directory" is simply the combination of all files in all
1173 * locations, with ".gz" stripped for loose files. With app, locale, and
1174 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1175 *
1176 * Pass in "" for the root dir.
1177 */
1178AssetDir* AssetManager::openNonAssetDir(void* cookie, const char* dirName)
1179{
1180 AutoMutex _l(mLock);
1181
1182 AssetDir* pDir = NULL;
1183 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1184
1185 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1186 assert(dirName != NULL);
1187
1188 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1189
1190 if (mCacheMode != CACHE_OFF && !mCacheValid)
1191 loadFileNameCacheLocked();
1192
1193 pDir = new AssetDir;
1194
1195 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1196
1197 const size_t which = ((size_t)cookie)-1;
1198
1199 if (which < mAssetPaths.size()) {
1200 const asset_path& ap = mAssetPaths.itemAt(which);
1201 if (ap.type == kFileTypeRegular) {
1202 LOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1203 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
1204 } else {
1205 LOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1206 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
1207 }
1208 }
1209
1210#if 0
1211 printf("FILE LIST:\n");
1212 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1213 printf(" %d: (%d) '%s'\n", i,
1214 pMergedInfo->itemAt(i).getFileType(),
1215 (const char*) pMergedInfo->itemAt(i).getFileName());
1216 }
1217#endif
1218
1219 pDir->setFileList(pMergedInfo);
1220 return pDir;
1221}
1222
1223/*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 * Scan the contents of the specified directory and merge them into the
1225 * "pMergedInfo" vector, removing previous entries if we find "exclude"
1226 * directives.
1227 *
1228 * Returns "false" if we found nothing to contribute.
1229 */
1230bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1231 const asset_path& ap, const char* rootDir, const char* dirName)
1232{
1233 SortedVector<AssetDir::FileInfo>* pContents;
1234 String8 path;
1235
1236 assert(pMergedInfo != NULL);
1237
1238 //printf("scanAndMergeDir: %s %s %s %s\n", appName, locale, vendor,dirName);
1239
1240 if (mCacheValid) {
1241 int i, start, count;
1242
1243 pContents = new SortedVector<AssetDir::FileInfo>;
1244
1245 /*
1246 * Get the basic partial path and find it in the cache. That's
1247 * the start point for the search.
1248 */
1249 path = createPathNameLocked(ap, rootDir);
1250 if (dirName[0] != '\0')
1251 path.appendPath(dirName);
1252
1253 start = mCache.indexOf(path);
1254 if (start == NAME_NOT_FOUND) {
1255 //printf("+++ not found in cache: dir '%s'\n", (const char*) path);
1256 delete pContents;
1257 return false;
1258 }
1259
1260 /*
1261 * The match string looks like "common/default/default/foo/bar/".
1262 * The '/' on the end ensures that we don't match on the directory
1263 * itself or on ".../foo/barfy/".
1264 */
1265 path.append("/");
1266
1267 count = mCache.size();
1268
1269 /*
1270 * Pick out the stuff in the current dir by examining the pathname.
1271 * It needs to match the partial pathname prefix, and not have a '/'
1272 * (fssep) anywhere after the prefix.
1273 */
1274 for (i = start+1; i < count; i++) {
1275 if (mCache[i].getFileName().length() > path.length() &&
1276 strncmp(mCache[i].getFileName().string(), path.string(), path.length()) == 0)
1277 {
1278 const char* name = mCache[i].getFileName().string();
1279 // XXX THIS IS BROKEN! Looks like we need to store the full
1280 // path prefix separately from the file path.
1281 if (strchr(name + path.length(), '/') == NULL) {
1282 /* grab it, reducing path to just the filename component */
1283 AssetDir::FileInfo tmp = mCache[i];
1284 tmp.setFileName(tmp.getFileName().getPathLeaf());
1285 pContents->add(tmp);
1286 }
1287 } else {
1288 /* no longer in the dir or its subdirs */
1289 break;
1290 }
1291
1292 }
1293 } else {
1294 path = createPathNameLocked(ap, rootDir);
1295 if (dirName[0] != '\0')
1296 path.appendPath(dirName);
1297 pContents = scanDirLocked(path);
1298 if (pContents == NULL)
1299 return false;
1300 }
1301
1302 // if we wanted to do an incremental cache fill, we would do it here
1303
1304 /*
1305 * Process "exclude" directives. If we find a filename that ends with
1306 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1307 * remove it if we find it. We also delete the "exclude" entry.
1308 */
1309 int i, count, exclExtLen;
1310
1311 count = pContents->size();
1312 exclExtLen = strlen(kExcludeExtension);
1313 for (i = 0; i < count; i++) {
1314 const char* name;
1315 int nameLen;
1316
1317 name = pContents->itemAt(i).getFileName().string();
1318 nameLen = strlen(name);
1319 if (nameLen > exclExtLen &&
1320 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1321 {
1322 String8 match(name, nameLen - exclExtLen);
1323 int matchIdx;
1324
1325 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1326 if (matchIdx > 0) {
1327 LOGV("Excluding '%s' [%s]\n",
1328 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1329 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1330 pMergedInfo->removeAt(matchIdx);
1331 } else {
1332 //printf("+++ no match on '%s'\n", (const char*) match);
1333 }
1334
1335 LOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1336 pContents->removeAt(i);
1337 i--; // adjust "for" loop
1338 count--; // and loop limit
1339 }
1340 }
1341
1342 mergeInfoLocked(pMergedInfo, pContents);
1343
1344 delete pContents;
1345
1346 return true;
1347}
1348
1349/*
1350 * Scan the contents of the specified directory, and stuff what we find
1351 * into a newly-allocated vector.
1352 *
1353 * Files ending in ".gz" will have their extensions removed.
1354 *
1355 * We should probably think about skipping files with "illegal" names,
1356 * e.g. illegal characters (/\:) or excessive length.
1357 *
1358 * Returns NULL if the specified directory doesn't exist.
1359 */
1360SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1361{
1362 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1363 DIR* dir;
1364 struct dirent* entry;
1365 FileType fileType;
1366
1367 LOGV("Scanning dir '%s'\n", path.string());
1368
1369 dir = opendir(path.string());
1370 if (dir == NULL)
1371 return NULL;
1372
1373 pContents = new SortedVector<AssetDir::FileInfo>;
1374
1375 while (1) {
1376 entry = readdir(dir);
1377 if (entry == NULL)
1378 break;
1379
1380 if (strcmp(entry->d_name, ".") == 0 ||
1381 strcmp(entry->d_name, "..") == 0)
1382 continue;
1383
1384#ifdef _DIRENT_HAVE_D_TYPE
1385 if (entry->d_type == DT_REG)
1386 fileType = kFileTypeRegular;
1387 else if (entry->d_type == DT_DIR)
1388 fileType = kFileTypeDirectory;
1389 else
1390 fileType = kFileTypeUnknown;
1391#else
1392 // stat the file
1393 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1394#endif
1395
1396 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1397 continue;
1398
1399 AssetDir::FileInfo info;
1400 info.set(String8(entry->d_name), fileType);
1401 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1402 info.setFileName(info.getFileName().getBasePath());
1403 info.setSourceName(path.appendPathCopy(info.getFileName()));
1404 pContents->add(info);
1405 }
1406
1407 closedir(dir);
1408 return pContents;
1409}
1410
1411/*
1412 * Scan the contents out of the specified Zip archive, and merge what we
1413 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1414 * we return immediately.
1415 *
1416 * Returns "false" if we found nothing to contribute.
1417 */
1418bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1419 const asset_path& ap, const char* rootDir, const char* baseDirName)
1420{
1421 ZipFileRO* pZip;
1422 Vector<String8> dirs;
1423 AssetDir::FileInfo info;
1424 SortedVector<AssetDir::FileInfo> contents;
1425 String8 sourceName, zipName, dirName;
1426
1427 pZip = mZipSet.getZip(ap.path);
1428 if (pZip == NULL) {
1429 LOGW("Failure opening zip %s\n", ap.path.string());
1430 return false;
1431 }
1432
1433 zipName = ZipSet::getPathName(ap.path.string());
1434
1435 /* convert "sounds" to "rootDir/sounds" */
1436 if (rootDir != NULL) dirName = rootDir;
1437 dirName.appendPath(baseDirName);
1438
1439 /*
1440 * Scan through the list of files, looking for a match. The files in
1441 * the Zip table of contents are not in sorted order, so we have to
1442 * process the entire list. We're looking for a string that begins
1443 * with the characters in "dirName", is followed by a '/', and has no
1444 * subsequent '/' in the stuff that follows.
1445 *
1446 * What makes this especially fun is that directories are not stored
1447 * explicitly in Zip archives, so we have to infer them from context.
1448 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1449 * to insert a directory called "sounds" into the list. We store
1450 * these in temporary vector so that we only return each one once.
1451 *
1452 * Name comparisons are case-sensitive to match UNIX filesystem
1453 * semantics.
1454 */
1455 int dirNameLen = dirName.length();
1456 for (int i = 0; i < pZip->getNumEntries(); i++) {
1457 ZipEntryRO entry;
1458 char nameBuf[256];
1459
1460 entry = pZip->findEntryByIndex(i);
1461 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1462 // TODO: fix this if we expect to have long names
1463 LOGE("ARGH: name too long?\n");
1464 continue;
1465 }
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001466 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 if (dirNameLen == 0 ||
1468 (strncmp(nameBuf, dirName.string(), dirNameLen) == 0 &&
1469 nameBuf[dirNameLen] == '/'))
1470 {
1471 const char* cp;
1472 const char* nextSlash;
1473
1474 cp = nameBuf + dirNameLen;
1475 if (dirNameLen != 0)
1476 cp++; // advance past the '/'
1477
1478 nextSlash = strchr(cp, '/');
1479//xxx this may break if there are bare directory entries
1480 if (nextSlash == NULL) {
1481 /* this is a file in the requested directory */
1482
1483 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1484
1485 info.setSourceName(
1486 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1487
1488 contents.add(info);
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001489 //printf("FOUND: file '%s'\n", info.getFileName().string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 } else {
1491 /* this is a subdir; add it if we don't already have it*/
1492 String8 subdirName(cp, nextSlash - cp);
1493 size_t j;
1494 size_t N = dirs.size();
1495
1496 for (j = 0; j < N; j++) {
1497 if (subdirName == dirs[j]) {
1498 break;
1499 }
1500 }
1501 if (j == N) {
1502 dirs.add(subdirName);
1503 }
1504
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001505 //printf("FOUND: dir '%s'\n", subdirName.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 }
1508 }
1509
1510 /*
1511 * Add the set of unique directories.
1512 */
1513 for (int i = 0; i < (int) dirs.size(); i++) {
1514 info.set(dirs[i], kFileTypeDirectory);
1515 info.setSourceName(
1516 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1517 contents.add(info);
1518 }
1519
1520 mergeInfoLocked(pMergedInfo, &contents);
1521
1522 return true;
1523}
1524
1525
1526/*
1527 * Merge two vectors of FileInfo.
1528 *
1529 * The merged contents will be stuffed into *pMergedInfo.
1530 *
1531 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1532 * we use the newer "pContents" entry.
1533 */
1534void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1535 const SortedVector<AssetDir::FileInfo>* pContents)
1536{
1537 /*
1538 * Merge what we found in this directory with what we found in
1539 * other places.
1540 *
1541 * Two basic approaches:
1542 * (1) Create a new array that holds the unique values of the two
1543 * arrays.
1544 * (2) Take the elements from pContents and shove them into pMergedInfo.
1545 *
1546 * Because these are vectors of complex objects, moving elements around
1547 * inside the vector requires constructing new objects and allocating
1548 * storage for members. With approach #1, we're always adding to the
1549 * end, whereas with #2 we could be inserting multiple elements at the
1550 * front of the vector. Approach #1 requires a full copy of the
1551 * contents of pMergedInfo, but approach #2 requires the same copy for
1552 * every insertion at the front of pMergedInfo.
1553 *
1554 * (We should probably use a SortedVector interface that allows us to
1555 * just stuff items in, trusting us to maintain the sort order.)
1556 */
1557 SortedVector<AssetDir::FileInfo>* pNewSorted;
1558 int mergeMax, contMax;
1559 int mergeIdx, contIdx;
1560
1561 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1562 mergeMax = pMergedInfo->size();
1563 contMax = pContents->size();
1564 mergeIdx = contIdx = 0;
1565
1566 while (mergeIdx < mergeMax || contIdx < contMax) {
1567 if (mergeIdx == mergeMax) {
1568 /* hit end of "merge" list, copy rest of "contents" */
1569 pNewSorted->add(pContents->itemAt(contIdx));
1570 contIdx++;
1571 } else if (contIdx == contMax) {
1572 /* hit end of "cont" list, copy rest of "merge" */
1573 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1574 mergeIdx++;
1575 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1576 {
1577 /* items are identical, add newer and advance both indices */
1578 pNewSorted->add(pContents->itemAt(contIdx));
1579 mergeIdx++;
1580 contIdx++;
1581 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1582 {
1583 /* "merge" is lower, add that one */
1584 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1585 mergeIdx++;
1586 } else {
1587 /* "cont" is lower, add that one */
1588 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1589 pNewSorted->add(pContents->itemAt(contIdx));
1590 contIdx++;
1591 }
1592 }
1593
1594 /*
1595 * Overwrite the "merged" list with the new stuff.
1596 */
1597 *pMergedInfo = *pNewSorted;
1598 delete pNewSorted;
1599
1600#if 0 // for Vector, rather than SortedVector
1601 int i, j;
1602 for (i = pContents->size() -1; i >= 0; i--) {
1603 bool add = true;
1604
1605 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1606 /* case-sensitive comparisons, to behave like UNIX fs */
1607 if (strcmp(pContents->itemAt(i).mFileName,
1608 pMergedInfo->itemAt(j).mFileName) == 0)
1609 {
1610 /* match, don't add this entry */
1611 add = false;
1612 break;
1613 }
1614 }
1615
1616 if (add)
1617 pMergedInfo->add(pContents->itemAt(i));
1618 }
1619#endif
1620}
1621
1622
1623/*
1624 * Load all files into the file name cache. We want to do this across
1625 * all combinations of { appname, locale, vendor }, performing a recursive
1626 * directory traversal.
1627 *
1628 * This is not the most efficient data structure. Also, gathering the
1629 * information as we needed it (file-by-file or directory-by-directory)
1630 * would be faster. However, on the actual device, 99% of the files will
1631 * live in Zip archives, so this list will be very small. The trouble
1632 * is that we have to check the "loose" files first, so it's important
1633 * that we don't beat the filesystem silly looking for files that aren't
1634 * there.
1635 *
1636 * Note on thread safety: this is the only function that causes updates
1637 * to mCache, and anybody who tries to use it will call here if !mCacheValid,
1638 * so we need to employ a mutex here.
1639 */
1640void AssetManager::loadFileNameCacheLocked(void)
1641{
1642 assert(!mCacheValid);
1643 assert(mCache.size() == 0);
1644
1645#ifdef DO_TIMINGS // need to link against -lrt for this now
1646 DurationTimer timer;
1647 timer.start();
1648#endif
1649
1650 fncScanLocked(&mCache, "");
1651
1652#ifdef DO_TIMINGS
1653 timer.stop();
1654 LOGD("Cache scan took %.3fms\n",
1655 timer.durationUsecs() / 1000.0);
1656#endif
1657
1658#if 0
1659 int i;
1660 printf("CACHED FILE LIST (%d entries):\n", mCache.size());
1661 for (i = 0; i < (int) mCache.size(); i++) {
1662 printf(" %d: (%d) '%s'\n", i,
1663 mCache.itemAt(i).getFileType(),
1664 (const char*) mCache.itemAt(i).getFileName());
1665 }
1666#endif
1667
1668 mCacheValid = true;
1669}
1670
1671/*
1672 * Scan up to 8 versions of the specified directory.
1673 */
1674void AssetManager::fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1675 const char* dirName)
1676{
1677 size_t i = mAssetPaths.size();
1678 while (i > 0) {
1679 i--;
1680 const asset_path& ap = mAssetPaths.itemAt(i);
1681 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, NULL, dirName);
1682 if (mLocale != NULL)
1683 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, NULL, dirName);
1684 if (mVendor != NULL)
1685 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, mVendor, dirName);
1686 if (mLocale != NULL && mVendor != NULL)
1687 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, mVendor, dirName);
1688 }
1689}
1690
1691/*
1692 * Recursively scan this directory and all subdirs.
1693 *
1694 * This is similar to scanAndMergeDir, but we don't remove the .EXCLUDE
1695 * files, and we prepend the extended partial path to the filenames.
1696 */
1697bool AssetManager::fncScanAndMergeDirLocked(
1698 SortedVector<AssetDir::FileInfo>* pMergedInfo,
1699 const asset_path& ap, const char* locale, const char* vendor,
1700 const char* dirName)
1701{
1702 SortedVector<AssetDir::FileInfo>* pContents;
1703 String8 partialPath;
1704 String8 fullPath;
1705
1706 // XXX This is broken -- the filename cache needs to hold the base
1707 // asset path separately from its filename.
1708
1709 partialPath = createPathNameLocked(ap, locale, vendor);
1710 if (dirName[0] != '\0') {
1711 partialPath.appendPath(dirName);
1712 }
1713
1714 fullPath = partialPath;
1715 pContents = scanDirLocked(fullPath);
1716 if (pContents == NULL) {
1717 return false; // directory did not exist
1718 }
1719
1720 /*
1721 * Scan all subdirectories of the current dir, merging what we find
1722 * into "pMergedInfo".
1723 */
1724 for (int i = 0; i < (int) pContents->size(); i++) {
1725 if (pContents->itemAt(i).getFileType() == kFileTypeDirectory) {
1726 String8 subdir(dirName);
1727 subdir.appendPath(pContents->itemAt(i).getFileName());
1728
1729 fncScanAndMergeDirLocked(pMergedInfo, ap, locale, vendor, subdir.string());
1730 }
1731 }
1732
1733 /*
1734 * To be consistent, we want entries for the root directory. If
1735 * we're the root, add one now.
1736 */
1737 if (dirName[0] == '\0') {
1738 AssetDir::FileInfo tmpInfo;
1739
1740 tmpInfo.set(String8(""), kFileTypeDirectory);
1741 tmpInfo.setSourceName(createPathNameLocked(ap, locale, vendor));
1742 pContents->add(tmpInfo);
1743 }
1744
1745 /*
1746 * We want to prepend the extended partial path to every entry in
1747 * "pContents". It's the same value for each entry, so this will
1748 * not change the sorting order of the vector contents.
1749 */
1750 for (int i = 0; i < (int) pContents->size(); i++) {
1751 const AssetDir::FileInfo& info = pContents->itemAt(i);
1752 pContents->editItemAt(i).setFileName(partialPath.appendPathCopy(info.getFileName()));
1753 }
1754
1755 mergeInfoLocked(pMergedInfo, pContents);
1756 return true;
1757}
1758
1759/*
1760 * Trash the cache.
1761 */
1762void AssetManager::purgeFileNameCacheLocked(void)
1763{
1764 mCacheValid = false;
1765 mCache.clear();
1766}
1767
1768/*
1769 * ===========================================================================
1770 * AssetManager::SharedZip
1771 * ===========================================================================
1772 */
1773
1774
1775Mutex AssetManager::SharedZip::gLock;
1776DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1777
1778AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
Dianne Hackborn78c40512009-07-06 11:07:40 -07001779 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1780 mResourceTableAsset(NULL), mResourceTable(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781{
1782 //LOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1783 mZipFile = new ZipFileRO;
1784 LOGV("+++ opening zip '%s'\n", mPath.string());
1785 if (mZipFile->open(mPath.string()) != NO_ERROR) {
1786 LOGD("failed to open Zip archive '%s'\n", mPath.string());
1787 delete mZipFile;
1788 mZipFile = NULL;
1789 }
1790}
1791
1792sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path)
1793{
1794 AutoMutex _l(gLock);
1795 time_t modWhen = getFileModDate(path);
1796 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1797 if (zip != NULL && zip->mModWhen == modWhen) {
1798 return zip;
1799 }
1800 zip = new SharedZip(path, modWhen);
1801 gOpen.add(path, zip);
1802 return zip;
1803
1804}
1805
1806ZipFileRO* AssetManager::SharedZip::getZip()
1807{
1808 return mZipFile;
1809}
1810
1811Asset* AssetManager::SharedZip::getResourceTableAsset()
1812{
1813 LOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1814 return mResourceTableAsset;
1815}
1816
1817Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1818{
1819 {
1820 AutoMutex _l(gLock);
1821 if (mResourceTableAsset == NULL) {
1822 mResourceTableAsset = asset;
1823 // This is not thread safe the first time it is called, so
1824 // do it here with the global lock held.
1825 asset->getBuffer(true);
1826 return asset;
1827 }
1828 }
1829 delete asset;
1830 return mResourceTableAsset;
1831}
1832
Dianne Hackborn78c40512009-07-06 11:07:40 -07001833ResTable* AssetManager::SharedZip::getResourceTable()
1834{
1835 LOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1836 return mResourceTable;
1837}
1838
1839ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1840{
1841 {
1842 AutoMutex _l(gLock);
1843 if (mResourceTable == NULL) {
1844 mResourceTable = res;
1845 return res;
1846 }
1847 }
1848 delete res;
1849 return mResourceTable;
1850}
1851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852bool AssetManager::SharedZip::isUpToDate()
1853{
1854 time_t modWhen = getFileModDate(mPath.string());
1855 return mModWhen == modWhen;
1856}
1857
1858AssetManager::SharedZip::~SharedZip()
1859{
1860 //LOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
Dianne Hackborn78c40512009-07-06 11:07:40 -07001861 if (mResourceTable != NULL) {
1862 delete mResourceTable;
1863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 if (mResourceTableAsset != NULL) {
1865 delete mResourceTableAsset;
1866 }
1867 if (mZipFile != NULL) {
1868 delete mZipFile;
1869 LOGV("Closed '%s'\n", mPath.string());
1870 }
1871}
1872
1873/*
1874 * ===========================================================================
1875 * AssetManager::ZipSet
1876 * ===========================================================================
1877 */
1878
1879/*
1880 * Constructor.
1881 */
1882AssetManager::ZipSet::ZipSet(void)
1883{
1884}
1885
1886/*
1887 * Destructor. Close any open archives.
1888 */
1889AssetManager::ZipSet::~ZipSet(void)
1890{
1891 size_t N = mZipFile.size();
1892 for (size_t i = 0; i < N; i++)
1893 closeZip(i);
1894}
1895
1896/*
1897 * Close a Zip file and reset the entry.
1898 */
1899void AssetManager::ZipSet::closeZip(int idx)
1900{
1901 mZipFile.editItemAt(idx) = NULL;
1902}
1903
1904
1905/*
1906 * Retrieve the appropriate Zip file from the set.
1907 */
1908ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1909{
1910 int idx = getIndex(path);
1911 sp<SharedZip> zip = mZipFile[idx];
1912 if (zip == NULL) {
1913 zip = SharedZip::get(path);
1914 mZipFile.editItemAt(idx) = zip;
1915 }
1916 return zip->getZip();
1917}
1918
Dianne Hackborn78c40512009-07-06 11:07:40 -07001919Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920{
1921 int idx = getIndex(path);
1922 sp<SharedZip> zip = mZipFile[idx];
1923 if (zip == NULL) {
1924 zip = SharedZip::get(path);
1925 mZipFile.editItemAt(idx) = zip;
1926 }
1927 return zip->getResourceTableAsset();
1928}
1929
Dianne Hackborn78c40512009-07-06 11:07:40 -07001930Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 Asset* asset)
1932{
1933 int idx = getIndex(path);
1934 sp<SharedZip> zip = mZipFile[idx];
1935 // doesn't make sense to call before previously accessing.
1936 return zip->setResourceTableAsset(asset);
1937}
1938
Dianne Hackborn78c40512009-07-06 11:07:40 -07001939ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
1940{
1941 int idx = getIndex(path);
1942 sp<SharedZip> zip = mZipFile[idx];
1943 if (zip == NULL) {
1944 zip = SharedZip::get(path);
1945 mZipFile.editItemAt(idx) = zip;
1946 }
1947 return zip->getResourceTable();
1948}
1949
1950ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
1951 ResTable* res)
1952{
1953 int idx = getIndex(path);
1954 sp<SharedZip> zip = mZipFile[idx];
1955 // doesn't make sense to call before previously accessing.
1956 return zip->setResourceTable(res);
1957}
1958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959/*
1960 * Generate the partial pathname for the specified archive. The caller
1961 * gets to prepend the asset root directory.
1962 *
1963 * Returns something like "common/en-US-noogle.jar".
1964 */
1965/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
1966{
1967 return String8(zipPath);
1968}
1969
1970bool AssetManager::ZipSet::isUpToDate()
1971{
1972 const size_t N = mZipFile.size();
1973 for (size_t i=0; i<N; i++) {
1974 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
1975 return false;
1976 }
1977 }
1978 return true;
1979}
1980
1981/*
1982 * Compute the zip file's index.
1983 *
1984 * "appName", "locale", and "vendor" should be set to NULL to indicate the
1985 * default directory.
1986 */
1987int AssetManager::ZipSet::getIndex(const String8& zip) const
1988{
1989 const size_t N = mZipPath.size();
1990 for (size_t i=0; i<N; i++) {
1991 if (mZipPath[i] == zip) {
1992 return i;
1993 }
1994 }
1995
1996 mZipPath.add(zip);
1997 mZipFile.add(NULL);
1998
1999 return mZipPath.size()-1;
2000}
2001