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