blob: 482dfc8933cf91c37284a8071d9b989e39c6c956 [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
369 // If we're attempting to set a locale that starts with "fil",
370 // we should convert it to "tl" for backwards compatibility since
371 // we've been using "tl" instead of "fil" prior to L.
372 //
373 // If the resource table already has entries for "fil", we use that
374 // instead of attempting a fallback.
375 if (strncmp(locale, kFilPrefix, kFilPrefixLen) == 0) {
376 Vector<String8> locales;
377 getLocales(&locales);
378 const size_t localesSize = locales.size();
379 bool hasFil = false;
380 for (size_t i = 0; i < localesSize; ++i) {
381 if (locales[i].find(kFilPrefix) == 0) {
382 hasFil = true;
383 break;
384 }
385 }
386
387
388 if (!hasFil) {
389 const size_t newLocaleLen = strlen(locale);
390 // This isn't a bug. We really do want mLocale to be 1 byte
391 // shorter than locale, because we're replacing "fil-" with
392 // "tl-".
393 mLocale = new char[newLocaleLen];
394 // Copy over "tl".
395 memcpy(mLocale, kTlPrefix, kTlPrefixLen);
396 // Copy the rest of |locale|, including the terminating '\0'.
397 memcpy(mLocale + kTlPrefixLen, locale + kFilPrefixLen,
398 newLocaleLen - kFilPrefixLen + 1);
399 updateResourceParamsLocked();
400 return;
401 }
402 }
403
404 mLocale = strdupNew(locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 updateResourceParamsLocked();
406}
407
408/*
409 * Set the current vendor. Use NULL to indicate no vendor.
410 *
411 * Close and reopen Zip archives as appropriate, and reset cached
412 * information in the vendor-specific sections of the tree.
413 */
414void AssetManager::setVendor(const char* vendor)
415{
416 AutoMutex _l(mLock);
417
418 if (mVendor != NULL) {
419 /* previously set, purge cached data */
420 purgeFileNameCacheLocked();
421 //mZipSet.purgeVendor();
422 delete[] mVendor;
423 }
424 mVendor = strdupNew(vendor);
425}
426
427void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
428{
429 AutoMutex _l(mLock);
430 *mConfig = config;
431 if (locale) {
432 setLocaleLocked(locale);
433 } else if (config.language[0] != 0) {
Narayan Kamath788fa412014-01-21 15:32:36 +0000434 char spec[RESTABLE_MAX_LOCALE_LEN];
435 config.getBcp47Locale(spec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 setLocaleLocked(spec);
437 } else {
438 updateResourceParamsLocked();
439 }
440}
441
Dianne Hackborn08d5b8f2010-08-04 11:12:40 -0700442void AssetManager::getConfiguration(ResTable_config* outConfig) const
443{
444 AutoMutex _l(mLock);
445 *outConfig = *mConfig;
446}
447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448/*
449 * Open an asset.
450 *
451 * The data could be;
452 * - In a file on disk (assetBase + fileName).
453 * - In a compressed file on disk (assetBase + fileName.gz).
454 * - In a Zip archive, uncompressed or compressed.
455 *
456 * It can be in a number of different directories and Zip archives.
457 * The search order is:
458 * - [appname]
459 * - locale + vendor
460 * - "default" + vendor
461 * - locale + "default"
462 * - "default + "default"
463 * - "common"
464 * - (same as above)
465 *
466 * To find a particular file, we have to try up to eight paths with
467 * all three forms of data.
468 *
469 * We should probably reject requests for "illegal" filenames, e.g. those
470 * with illegal characters or "../" backward relative paths.
471 */
472Asset* AssetManager::open(const char* fileName, AccessMode mode)
473{
474 AutoMutex _l(mLock);
475
476 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
477
478
479 if (mCacheMode != CACHE_OFF && !mCacheValid)
480 loadFileNameCacheLocked();
481
482 String8 assetName(kAssetsRoot);
483 assetName.appendPath(fileName);
484
485 /*
486 * For each top-level asset path, search for the asset.
487 */
488
489 size_t i = mAssetPaths.size();
490 while (i > 0) {
491 i--;
Steve Block71f2cf12011-10-20 11:56:00 +0100492 ALOGV("Looking for asset '%s' in '%s'\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 assetName.string(), mAssetPaths.itemAt(i).path.string());
494 Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
495 if (pAsset != NULL) {
496 return pAsset != kExcludedAsset ? pAsset : NULL;
497 }
498 }
499
500 return NULL;
501}
502
503/*
504 * Open a non-asset file as if it were an asset.
505 *
506 * The "fileName" is the partial path starting from the application
507 * name.
508 */
509Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode)
510{
511 AutoMutex _l(mLock);
512
513 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
514
515
516 if (mCacheMode != CACHE_OFF && !mCacheValid)
517 loadFileNameCacheLocked();
518
519 /*
520 * For each top-level asset path, search for the asset.
521 */
522
523 size_t i = mAssetPaths.size();
524 while (i > 0) {
525 i--;
Steve Block71f2cf12011-10-20 11:56:00 +0100526 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 -0800527 Asset* pAsset = openNonAssetInPathLocked(
528 fileName, mode, mAssetPaths.itemAt(i));
529 if (pAsset != NULL) {
530 return pAsset != kExcludedAsset ? pAsset : NULL;
531 }
532 }
533
534 return NULL;
535}
536
Narayan Kamath745d4ef2014-01-27 11:17:22 +0000537Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538{
Narayan Kamath745d4ef2014-01-27 11:17:22 +0000539 const size_t which = static_cast<size_t>(cookie) - 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540
541 AutoMutex _l(mLock);
542
543 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 if (mCacheMode != CACHE_OFF && !mCacheValid)
546 loadFileNameCacheLocked();
547
548 if (which < mAssetPaths.size()) {
Steve Block71f2cf12011-10-20 11:56:00 +0100549 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 mAssetPaths.itemAt(which).path.string());
551 Asset* pAsset = openNonAssetInPathLocked(
552 fileName, mode, mAssetPaths.itemAt(which));
553 if (pAsset != NULL) {
554 return pAsset != kExcludedAsset ? pAsset : NULL;
555 }
556 }
557
558 return NULL;
559}
560
561/*
562 * Get the type of a file in the asset namespace.
563 *
564 * This currently only works for regular files. All others (including
565 * directories) will return kFileTypeNonexistent.
566 */
567FileType AssetManager::getFileType(const char* fileName)
568{
569 Asset* pAsset = NULL;
570
571 /*
572 * Open the asset. This is less efficient than simply finding the
573 * file, but it's not too bad (we don't uncompress or mmap data until
574 * the first read() call).
575 */
576 pAsset = open(fileName, Asset::ACCESS_STREAMING);
577 delete pAsset;
578
579 if (pAsset == NULL)
580 return kFileTypeNonexistent;
581 else
582 return kFileTypeRegular;
583}
584
585const ResTable* AssetManager::getResTable(bool required) const
586{
587 ResTable* rt = mResources;
588 if (rt) {
589 return rt;
590 }
591
592 // Iterate through all asset packages, collecting resources from each.
593
594 AutoMutex _l(mLock);
595
596 if (mResources != NULL) {
597 return mResources;
598 }
599
600 if (required) {
601 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
602 }
603
604 if (mCacheMode != CACHE_OFF && !mCacheValid)
605 const_cast<AssetManager*>(this)->loadFileNameCacheLocked();
606
607 const size_t N = mAssetPaths.size();
608 for (size_t i=0; i<N; i++) {
609 Asset* ass = NULL;
Dianne Hackborn78c40512009-07-06 11:07:40 -0700610 ResTable* sharedRes = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 bool shared = true;
612 const asset_path& ap = mAssetPaths.itemAt(i);
Dianne Hackbornf7be4802013-04-12 14:52:58 -0700613 MY_TRACE_BEGIN(ap.path.string());
Mårten Kongstad57f4b772011-03-17 14:13:41 +0100614 Asset* idmap = openIdmapLocked(ap);
Steve Block71f2cf12011-10-20 11:56:00 +0100615 ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 if (ap.type != kFileTypeDirectory) {
Dianne Hackborn78c40512009-07-06 11:07:40 -0700617 if (i == 0) {
618 // The first item is typically the framework resources,
619 // which we want to avoid parsing every time.
620 sharedRes = const_cast<AssetManager*>(this)->
621 mZipSet.getZipResourceTable(ap.path);
Mårten Kongstad48d22322014-01-31 14:43:27 +0100622 if (sharedRes != NULL) {
623 // skip ahead the number of system overlay packages preloaded
624 i += sharedRes->getTableCount() - 1;
625 }
Dianne Hackborn78c40512009-07-06 11:07:40 -0700626 }
627 if (sharedRes == NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 ass = const_cast<AssetManager*>(this)->
Dianne Hackborn78c40512009-07-06 11:07:40 -0700629 mZipSet.getZipResourceTableAsset(ap.path);
630 if (ass == NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +0100631 ALOGV("loading resource table %s\n", ap.path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 ass = const_cast<AssetManager*>(this)->
Dianne Hackborn78c40512009-07-06 11:07:40 -0700633 openNonAssetInPathLocked("resources.arsc",
634 Asset::ACCESS_BUFFER,
635 ap);
636 if (ass != NULL && ass != kExcludedAsset) {
637 ass = const_cast<AssetManager*>(this)->
638 mZipSet.setZipResourceTableAsset(ap.path, ass);
639 }
640 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700641
Dianne Hackborn78c40512009-07-06 11:07:40 -0700642 if (i == 0 && ass != NULL) {
643 // If this is the first resource table in the asset
644 // manager, then we are going to cache it so that we
645 // can quickly copy it out for others.
Steve Block71f2cf12011-10-20 11:56:00 +0100646 ALOGV("Creating shared resources for %s", ap.path.string());
Dianne Hackborn78c40512009-07-06 11:07:40 -0700647 sharedRes = new ResTable();
Narayan Kamath7c4887f2014-01-27 17:32:37 +0000648 sharedRes->add(ass, i + 1, false, idmap);
Mårten Kongstad48d22322014-01-31 14:43:27 +0100649#ifdef HAVE_ANDROID_OS
650 const char* data = getenv("ANDROID_DATA");
651 LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
652 String8 overlaysListPath(data);
653 overlaysListPath.appendPath(kResourceCache);
654 overlaysListPath.appendPath("overlays.list");
655 addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, i);
656#endif
Dianne Hackborn78c40512009-07-06 11:07:40 -0700657 sharedRes = const_cast<AssetManager*>(this)->
658 mZipSet.setZipResourceTable(ap.path, sharedRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 }
660 }
661 } else {
Steve Block71f2cf12011-10-20 11:56:00 +0100662 ALOGV("loading resource table %s\n", ap.path.string());
Elliott Hughesc367d482013-10-29 13:12:55 -0700663 ass = const_cast<AssetManager*>(this)->
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 openNonAssetInPathLocked("resources.arsc",
665 Asset::ACCESS_BUFFER,
666 ap);
667 shared = false;
668 }
Dianne Hackborn78c40512009-07-06 11:07:40 -0700669 if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 if (rt == NULL) {
671 mResources = rt = new ResTable();
672 updateResourceParamsLocked();
673 }
Steve Block71f2cf12011-10-20 11:56:00 +0100674 ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
Dianne Hackborn78c40512009-07-06 11:07:40 -0700675 if (sharedRes != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +0100676 ALOGV("Copying existing resources for %s", ap.path.string());
Dianne Hackborn78c40512009-07-06 11:07:40 -0700677 rt->add(sharedRes);
678 } else {
Steve Block71f2cf12011-10-20 11:56:00 +0100679 ALOGV("Parsing resources for %s", ap.path.string());
Narayan Kamath7c4887f2014-01-27 17:32:37 +0000680 rt->add(ass, i + 1, !shared, idmap);
Dianne Hackborn78c40512009-07-06 11:07:40 -0700681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682
683 if (!shared) {
684 delete ass;
685 }
686 }
Mårten Kongstad2b91c672011-05-05 10:40:42 +0200687 if (idmap != NULL) {
688 delete idmap;
689 }
Dianne Hackbornf7be4802013-04-12 14:52:58 -0700690 MY_TRACE_END();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692
Steve Block8564c8d2012-01-05 23:22:43 +0000693 if (required && !rt) ALOGW("Unable to find resources file resources.arsc");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 if (!rt) {
695 mResources = rt = new ResTable();
696 }
697 return rt;
698}
699
700void AssetManager::updateResourceParamsLocked() const
701{
702 ResTable* res = mResources;
703 if (!res) {
704 return;
705 }
706
Narayan Kamath788fa412014-01-21 15:32:36 +0000707 if (mLocale) {
708 mConfig->setBcp47Locale(mLocale);
709 } else {
710 mConfig->clearLocale();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712
713 res->setParameters(mConfig);
714}
715
Mårten Kongstad57f4b772011-03-17 14:13:41 +0100716Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
717{
718 Asset* ass = NULL;
719 if (ap.idmap.size() != 0) {
720 ass = const_cast<AssetManager*>(this)->
721 openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
722 if (ass) {
Steve Block71f2cf12011-10-20 11:56:00 +0100723 ALOGV("loading idmap %s\n", ap.idmap.string());
Mårten Kongstad57f4b772011-03-17 14:13:41 +0100724 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000725 ALOGW("failed to load idmap %s\n", ap.idmap.string());
Mårten Kongstad57f4b772011-03-17 14:13:41 +0100726 }
727 }
728 return ass;
729}
730
Mårten Kongstad48d22322014-01-31 14:43:27 +0100731void AssetManager::addSystemOverlays(const char* pathOverlaysList,
732 const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
733{
734 FILE* fin = fopen(pathOverlaysList, "r");
735 if (fin == NULL) {
736 return;
737 }
738
739 char buf[1024];
740 while (fgets(buf, sizeof(buf), fin)) {
741 // format of each line:
742 // <path to apk><space><path to idmap><newline>
743 char* space = strchr(buf, ' ');
744 char* newline = strchr(buf, '\n');
745 asset_path oap;
746
747 if (space == NULL || newline == NULL || newline < space) {
748 continue;
749 }
750
751 oap.path = String8(buf, space - buf);
752 oap.type = kFileTypeRegular;
753 oap.idmap = String8(space + 1, newline - space - 1);
754
755 Asset* oass = const_cast<AssetManager*>(this)->
756 openNonAssetInPathLocked("resources.arsc",
757 Asset::ACCESS_BUFFER,
758 oap);
759
760 if (oass != NULL) {
761 Asset* oidmap = openIdmapLocked(oap);
762 offset++;
763 sharedRes->add(oass, offset + 1, false, oidmap);
764 const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
765 const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
766 }
767 }
768 fclose(fin);
769}
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771const ResTable& AssetManager::getResources(bool required) const
772{
773 const ResTable* rt = getResTable(required);
774 return *rt;
775}
776
777bool AssetManager::isUpToDate()
778{
779 AutoMutex _l(mLock);
780 return mZipSet.isUpToDate();
781}
782
783void AssetManager::getLocales(Vector<String8>* locales) const
784{
785 ResTable* res = mResources;
786 if (res != NULL) {
787 res->getLocales(locales);
788 }
Narayan Kamathe4345db2014-06-26 16:01:28 +0100789
790 const size_t numLocales = locales->size();
791 for (size_t i = 0; i < numLocales; ++i) {
792 const String8& localeStr = locales->itemAt(i);
793 if (localeStr.find(kTlPrefix) == 0) {
794 String8 replaced("fil");
795 replaced += (localeStr.string() + kTlPrefixLen);
796 locales->editItemAt(i) = replaced;
797 }
798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799}
800
801/*
802 * Open a non-asset file as if it were an asset, searching for it in the
803 * specified app.
804 *
805 * Pass in a NULL values for "appName" if the common app directory should
806 * be used.
807 */
808Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
809 const asset_path& ap)
810{
811 Asset* pAsset = NULL;
812
813 /* look at the filesystem on disk */
814 if (ap.type == kFileTypeDirectory) {
815 String8 path(ap.path);
816 path.appendPath(fileName);
817
818 pAsset = openAssetFromFileLocked(path, mode);
819
820 if (pAsset == NULL) {
821 /* try again, this time with ".gz" */
822 path.append(".gz");
823 pAsset = openAssetFromFileLocked(path, mode);
824 }
825
826 if (pAsset != NULL) {
827 //printf("FOUND NA '%s' on disk\n", fileName);
828 pAsset->setAssetSource(path);
829 }
830
831 /* look inside the zip file */
832 } else {
833 String8 path(fileName);
834
835 /* check the appropriate Zip file */
Narayan Kamathafd31e02013-12-03 13:16:03 +0000836 ZipFileRO* pZip = getZipFileLocked(ap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (pZip != NULL) {
838 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamathafd31e02013-12-03 13:16:03 +0000839 ZipEntryRO entry = pZip->findEntryByName(path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 if (entry != NULL) {
841 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
842 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamathafd31e02013-12-03 13:16:03 +0000843 pZip->releaseEntry(entry);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
846
847 if (pAsset != NULL) {
848 /* create a "source" name, for debug/display */
849 pAsset->setAssetSource(
850 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
851 String8(fileName)));
852 }
853 }
854
855 return pAsset;
856}
857
858/*
859 * Open an asset, searching for it in the directory hierarchy for the
860 * specified app.
861 *
862 * Pass in a NULL values for "appName" if the common app directory should
863 * be used.
864 */
865Asset* AssetManager::openInPathLocked(const char* fileName, AccessMode mode,
866 const asset_path& ap)
867{
868 Asset* pAsset = NULL;
869
870 /*
871 * Try various combinations of locale and vendor.
872 */
873 if (mLocale != NULL && mVendor != NULL)
874 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, mVendor);
875 if (pAsset == NULL && mVendor != NULL)
876 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, mVendor);
877 if (pAsset == NULL && mLocale != NULL)
878 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, NULL);
879 if (pAsset == NULL)
880 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, NULL);
881
882 return pAsset;
883}
884
885/*
886 * Open an asset, searching for it in the directory hierarchy for the
887 * specified locale and vendor.
888 *
889 * We also search in "app.jar".
890 *
891 * Pass in NULL values for "appName", "locale", and "vendor" if the
892 * defaults should be used.
893 */
894Asset* AssetManager::openInLocaleVendorLocked(const char* fileName, AccessMode mode,
895 const asset_path& ap, const char* locale, const char* vendor)
896{
897 Asset* pAsset = NULL;
898
899 if (ap.type == kFileTypeDirectory) {
900 if (mCacheMode == CACHE_OFF) {
901 /* look at the filesystem on disk */
902 String8 path(createPathNameLocked(ap, locale, vendor));
903 path.appendPath(fileName);
Elliott Hughesc367d482013-10-29 13:12:55 -0700904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 String8 excludeName(path);
906 excludeName.append(kExcludeExtension);
907 if (::getFileType(excludeName.string()) != kFileTypeNonexistent) {
908 /* say no more */
909 //printf("+++ excluding '%s'\n", (const char*) excludeName);
910 return kExcludedAsset;
911 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 pAsset = openAssetFromFileLocked(path, mode);
Elliott Hughesc367d482013-10-29 13:12:55 -0700914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 if (pAsset == NULL) {
916 /* try again, this time with ".gz" */
917 path.append(".gz");
918 pAsset = openAssetFromFileLocked(path, mode);
919 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (pAsset != NULL)
922 pAsset->setAssetSource(path);
923 } else {
924 /* find in cache */
925 String8 path(createPathNameLocked(ap, locale, vendor));
926 path.appendPath(fileName);
Elliott Hughesc367d482013-10-29 13:12:55 -0700927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 AssetDir::FileInfo tmpInfo;
929 bool found = false;
Elliott Hughesc367d482013-10-29 13:12:55 -0700930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 String8 excludeName(path);
932 excludeName.append(kExcludeExtension);
Elliott Hughesc367d482013-10-29 13:12:55 -0700933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 if (mCache.indexOf(excludeName) != NAME_NOT_FOUND) {
935 /* go no farther */
936 //printf("+++ Excluding '%s'\n", (const char*) excludeName);
937 return kExcludedAsset;
938 }
939
940 /*
941 * File compression extensions (".gz") don't get stored in the
942 * name cache, so we have to try both here.
943 */
944 if (mCache.indexOf(path) != NAME_NOT_FOUND) {
945 found = true;
946 pAsset = openAssetFromFileLocked(path, mode);
947 if (pAsset == NULL) {
948 /* try again, this time with ".gz" */
949 path.append(".gz");
950 pAsset = openAssetFromFileLocked(path, mode);
951 }
952 }
953
954 if (pAsset != NULL)
955 pAsset->setAssetSource(path);
956
957 /*
958 * Don't continue the search into the Zip files. Our cached info
959 * said it was a file on disk; to be consistent with openDir()
960 * we want to return the loose asset. If the cached file gets
961 * removed, we fail.
962 *
963 * The alternative is to update our cache when files get deleted,
964 * or make some sort of "best effort" promise, but for now I'm
965 * taking the hard line.
966 */
967 if (found) {
968 if (pAsset == NULL)
Steve Block5baa3a62011-12-20 16:23:08 +0000969 ALOGD("Expected file not found: '%s'\n", path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 return pAsset;
971 }
972 }
973 }
974
975 /*
976 * Either it wasn't found on disk or on the cached view of the disk.
977 * Dig through the currently-opened set of Zip files. If caching
978 * is disabled, the Zip file may get reopened.
979 */
980 if (pAsset == NULL && ap.type == kFileTypeRegular) {
981 String8 path;
982
983 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
984 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
985 path.appendPath(fileName);
986
987 /* check the appropriate Zip file */
Narayan Kamathafd31e02013-12-03 13:16:03 +0000988 ZipFileRO* pZip = getZipFileLocked(ap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (pZip != NULL) {
990 //printf("GOT zip, checking '%s'\n", (const char*) path);
Narayan Kamathafd31e02013-12-03 13:16:03 +0000991 ZipEntryRO entry = pZip->findEntryByName(path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 if (entry != NULL) {
993 //printf("FOUND in Zip file for %s/%s-%s\n",
994 // appName, locale, vendor);
995 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamathafd31e02013-12-03 13:16:03 +0000996 pZip->releaseEntry(entry);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998 }
999
1000 if (pAsset != NULL) {
1001 /* create a "source" name, for debug/display */
1002 pAsset->setAssetSource(createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()),
1003 String8(""), String8(fileName)));
1004 }
1005 }
1006
1007 return pAsset;
1008}
1009
1010/*
1011 * Create a "source name" for a file from a Zip archive.
1012 */
1013String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
1014 const String8& dirName, const String8& fileName)
1015{
1016 String8 sourceName("zip:");
1017 sourceName.append(zipFileName);
1018 sourceName.append(":");
1019 if (dirName.length() > 0) {
1020 sourceName.appendPath(dirName);
1021 }
1022 sourceName.appendPath(fileName);
1023 return sourceName;
1024}
1025
1026/*
1027 * Create a path to a loose asset (asset-base/app/locale/vendor).
1028 */
1029String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
1030 const char* vendor)
1031{
1032 String8 path(ap.path);
1033 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1034 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1035 return path;
1036}
1037
1038/*
1039 * Create a path to a loose asset (asset-base/app/rootDir).
1040 */
1041String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
1042{
1043 String8 path(ap.path);
1044 if (rootDir != NULL) path.appendPath(rootDir);
1045 return path;
1046}
1047
1048/*
1049 * Return a pointer to one of our open Zip archives. Returns NULL if no
1050 * matching Zip file exists.
1051 *
1052 * Right now we have 2 possible Zip files (1 each in app/"common").
1053 *
1054 * If caching is set to CACHE_OFF, to get the expected behavior we
1055 * need to reopen the Zip file on every request. That would be silly
1056 * and expensive, so instead we just check the file modification date.
1057 *
1058 * Pass in NULL values for "appName", "locale", and "vendor" if the
1059 * generics should be used.
1060 */
1061ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
1062{
Steve Block71f2cf12011-10-20 11:56:00 +01001063 ALOGV("getZipFileLocked() in %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064
1065 return mZipSet.getZip(ap.path);
1066}
1067
1068/*
1069 * Try to open an asset from a file on disk.
1070 *
1071 * If the file is compressed with gzip, we seek to the start of the
1072 * deflated data and pass that in (just like we would for a Zip archive).
1073 *
1074 * For uncompressed data, we may already have an mmap()ed version sitting
1075 * around. If so, we want to hand that to the Asset instead.
1076 *
1077 * This returns NULL if the file doesn't exist, couldn't be opened, or
1078 * claims to be a ".gz" but isn't.
1079 */
1080Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
1081 AccessMode mode)
1082{
1083 Asset* pAsset = NULL;
1084
1085 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
1086 //printf("TRYING '%s'\n", (const char*) pathName);
1087 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
1088 } else {
1089 //printf("TRYING '%s'\n", (const char*) pathName);
1090 pAsset = Asset::createFromFile(pathName.string(), mode);
1091 }
1092
1093 return pAsset;
1094}
1095
1096/*
1097 * Given an entry in a Zip archive, create a new Asset object.
1098 *
1099 * If the entry is uncompressed, we may want to create or share a
1100 * slice of shared memory.
1101 */
1102Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
1103 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
1104{
1105 Asset* pAsset = NULL;
1106
1107 // TODO: look for previously-created shared memory slice?
1108 int method;
Kenny Root68246dc2010-04-22 18:28:29 -07001109 size_t uncompressedLen;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110
1111 //printf("USING Zip '%s'\n", pEntry->getFileName());
1112
1113 //pZipFile->getEntryInfo(entry, &method, &uncompressedLen, &compressedLen,
1114 // &offset);
1115 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
1116 NULL, NULL))
1117 {
Steve Block8564c8d2012-01-05 23:22:43 +00001118 ALOGW("getEntryInfo failed\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 return NULL;
1120 }
1121
1122 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
1123 if (dataMap == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001124 ALOGW("create map from entry failed\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 return NULL;
1126 }
1127
1128 if (method == ZipFileRO::kCompressStored) {
1129 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
Steve Block71f2cf12011-10-20 11:56:00 +01001130 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 dataMap->getFileName(), mode, pAsset);
1132 } else {
1133 pAsset = Asset::createFromCompressedMap(dataMap, method,
1134 uncompressedLen, mode);
Steve Block71f2cf12011-10-20 11:56:00 +01001135 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 dataMap->getFileName(), mode, pAsset);
1137 }
1138 if (pAsset == NULL) {
1139 /* unexpected */
Steve Block8564c8d2012-01-05 23:22:43 +00001140 ALOGW("create from segment failed\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142
1143 return pAsset;
1144}
1145
1146
1147
1148/*
1149 * Open a directory in the asset namespace.
1150 *
1151 * An "asset directory" is simply the combination of all files in all
1152 * locations, with ".gz" stripped for loose files. With app, locale, and
1153 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1154 *
1155 * Pass in "" for the root dir.
1156 */
1157AssetDir* AssetManager::openDir(const char* dirName)
1158{
1159 AutoMutex _l(mLock);
1160
1161 AssetDir* pDir = NULL;
1162 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1163
1164 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1165 assert(dirName != NULL);
1166
1167 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1168
1169 if (mCacheMode != CACHE_OFF && !mCacheValid)
1170 loadFileNameCacheLocked();
1171
1172 pDir = new AssetDir;
1173
1174 /*
1175 * Scan the various directories, merging what we find into a single
1176 * vector. We want to scan them in reverse priority order so that
1177 * the ".EXCLUDE" processing works correctly. Also, if we decide we
1178 * want to remember where the file is coming from, we'll get the right
1179 * version.
1180 *
1181 * We start with Zip archives, then do loose files.
1182 */
1183 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1184
1185 size_t i = mAssetPaths.size();
1186 while (i > 0) {
1187 i--;
1188 const asset_path& ap = mAssetPaths.itemAt(i);
1189 if (ap.type == kFileTypeRegular) {
Steve Block71f2cf12011-10-20 11:56:00 +01001190 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1192 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001193 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1195 }
1196 }
1197
1198#if 0
1199 printf("FILE LIST:\n");
1200 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1201 printf(" %d: (%d) '%s'\n", i,
1202 pMergedInfo->itemAt(i).getFileType(),
1203 (const char*) pMergedInfo->itemAt(i).getFileName());
1204 }
1205#endif
1206
1207 pDir->setFileList(pMergedInfo);
1208 return pDir;
1209}
1210
1211/*
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001212 * Open a directory in the non-asset namespace.
1213 *
1214 * An "asset directory" is simply the combination of all files in all
1215 * locations, with ".gz" stripped for loose files. With app, locale, and
1216 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1217 *
1218 * Pass in "" for the root dir.
1219 */
Narayan Kamath745d4ef2014-01-27 11:17:22 +00001220AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001221{
1222 AutoMutex _l(mLock);
1223
1224 AssetDir* pDir = NULL;
1225 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1226
1227 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1228 assert(dirName != NULL);
1229
1230 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1231
1232 if (mCacheMode != CACHE_OFF && !mCacheValid)
1233 loadFileNameCacheLocked();
1234
1235 pDir = new AssetDir;
1236
1237 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1238
Narayan Kamath745d4ef2014-01-27 11:17:22 +00001239 const size_t which = static_cast<size_t>(cookie) - 1;
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001240
1241 if (which < mAssetPaths.size()) {
1242 const asset_path& ap = mAssetPaths.itemAt(which);
1243 if (ap.type == kFileTypeRegular) {
Steve Block71f2cf12011-10-20 11:56:00 +01001244 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001245 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
1246 } else {
Steve Block71f2cf12011-10-20 11:56:00 +01001247 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001248 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
1249 }
1250 }
1251
1252#if 0
1253 printf("FILE LIST:\n");
1254 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1255 printf(" %d: (%d) '%s'\n", i,
1256 pMergedInfo->itemAt(i).getFileType(),
1257 (const char*) pMergedInfo->itemAt(i).getFileName());
1258 }
1259#endif
1260
1261 pDir->setFileList(pMergedInfo);
1262 return pDir;
1263}
1264
1265/*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 * Scan the contents of the specified directory and merge them into the
1267 * "pMergedInfo" vector, removing previous entries if we find "exclude"
1268 * directives.
1269 *
1270 * Returns "false" if we found nothing to contribute.
1271 */
1272bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1273 const asset_path& ap, const char* rootDir, const char* dirName)
1274{
1275 SortedVector<AssetDir::FileInfo>* pContents;
1276 String8 path;
1277
1278 assert(pMergedInfo != NULL);
1279
1280 //printf("scanAndMergeDir: %s %s %s %s\n", appName, locale, vendor,dirName);
1281
1282 if (mCacheValid) {
1283 int i, start, count;
1284
1285 pContents = new SortedVector<AssetDir::FileInfo>;
1286
1287 /*
1288 * Get the basic partial path and find it in the cache. That's
1289 * the start point for the search.
1290 */
1291 path = createPathNameLocked(ap, rootDir);
1292 if (dirName[0] != '\0')
1293 path.appendPath(dirName);
1294
1295 start = mCache.indexOf(path);
1296 if (start == NAME_NOT_FOUND) {
1297 //printf("+++ not found in cache: dir '%s'\n", (const char*) path);
1298 delete pContents;
1299 return false;
1300 }
1301
1302 /*
1303 * The match string looks like "common/default/default/foo/bar/".
1304 * The '/' on the end ensures that we don't match on the directory
1305 * itself or on ".../foo/barfy/".
1306 */
1307 path.append("/");
1308
1309 count = mCache.size();
1310
1311 /*
1312 * Pick out the stuff in the current dir by examining the pathname.
1313 * It needs to match the partial pathname prefix, and not have a '/'
1314 * (fssep) anywhere after the prefix.
1315 */
1316 for (i = start+1; i < count; i++) {
1317 if (mCache[i].getFileName().length() > path.length() &&
1318 strncmp(mCache[i].getFileName().string(), path.string(), path.length()) == 0)
1319 {
1320 const char* name = mCache[i].getFileName().string();
1321 // XXX THIS IS BROKEN! Looks like we need to store the full
1322 // path prefix separately from the file path.
1323 if (strchr(name + path.length(), '/') == NULL) {
1324 /* grab it, reducing path to just the filename component */
1325 AssetDir::FileInfo tmp = mCache[i];
1326 tmp.setFileName(tmp.getFileName().getPathLeaf());
1327 pContents->add(tmp);
1328 }
1329 } else {
1330 /* no longer in the dir or its subdirs */
1331 break;
1332 }
1333
1334 }
1335 } else {
1336 path = createPathNameLocked(ap, rootDir);
1337 if (dirName[0] != '\0')
1338 path.appendPath(dirName);
1339 pContents = scanDirLocked(path);
1340 if (pContents == NULL)
1341 return false;
1342 }
1343
1344 // if we wanted to do an incremental cache fill, we would do it here
1345
1346 /*
1347 * Process "exclude" directives. If we find a filename that ends with
1348 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1349 * remove it if we find it. We also delete the "exclude" entry.
1350 */
1351 int i, count, exclExtLen;
1352
1353 count = pContents->size();
1354 exclExtLen = strlen(kExcludeExtension);
1355 for (i = 0; i < count; i++) {
1356 const char* name;
1357 int nameLen;
1358
1359 name = pContents->itemAt(i).getFileName().string();
1360 nameLen = strlen(name);
1361 if (nameLen > exclExtLen &&
1362 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1363 {
1364 String8 match(name, nameLen - exclExtLen);
1365 int matchIdx;
1366
1367 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1368 if (matchIdx > 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001369 ALOGV("Excluding '%s' [%s]\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1371 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1372 pMergedInfo->removeAt(matchIdx);
1373 } else {
1374 //printf("+++ no match on '%s'\n", (const char*) match);
1375 }
1376
Steve Block5baa3a62011-12-20 16:23:08 +00001377 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 pContents->removeAt(i);
1379 i--; // adjust "for" loop
1380 count--; // and loop limit
1381 }
1382 }
1383
1384 mergeInfoLocked(pMergedInfo, pContents);
1385
1386 delete pContents;
1387
1388 return true;
1389}
1390
1391/*
1392 * Scan the contents of the specified directory, and stuff what we find
1393 * into a newly-allocated vector.
1394 *
1395 * Files ending in ".gz" will have their extensions removed.
1396 *
1397 * We should probably think about skipping files with "illegal" names,
1398 * e.g. illegal characters (/\:) or excessive length.
1399 *
1400 * Returns NULL if the specified directory doesn't exist.
1401 */
1402SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1403{
1404 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1405 DIR* dir;
1406 struct dirent* entry;
1407 FileType fileType;
1408
Steve Block71f2cf12011-10-20 11:56:00 +01001409 ALOGV("Scanning dir '%s'\n", path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410
1411 dir = opendir(path.string());
1412 if (dir == NULL)
1413 return NULL;
1414
1415 pContents = new SortedVector<AssetDir::FileInfo>;
1416
1417 while (1) {
1418 entry = readdir(dir);
1419 if (entry == NULL)
1420 break;
1421
1422 if (strcmp(entry->d_name, ".") == 0 ||
1423 strcmp(entry->d_name, "..") == 0)
1424 continue;
1425
1426#ifdef _DIRENT_HAVE_D_TYPE
1427 if (entry->d_type == DT_REG)
1428 fileType = kFileTypeRegular;
1429 else if (entry->d_type == DT_DIR)
1430 fileType = kFileTypeDirectory;
1431 else
1432 fileType = kFileTypeUnknown;
1433#else
1434 // stat the file
1435 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1436#endif
1437
1438 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1439 continue;
1440
1441 AssetDir::FileInfo info;
1442 info.set(String8(entry->d_name), fileType);
1443 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1444 info.setFileName(info.getFileName().getBasePath());
1445 info.setSourceName(path.appendPathCopy(info.getFileName()));
1446 pContents->add(info);
1447 }
1448
1449 closedir(dir);
1450 return pContents;
1451}
1452
1453/*
1454 * Scan the contents out of the specified Zip archive, and merge what we
1455 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1456 * we return immediately.
1457 *
1458 * Returns "false" if we found nothing to contribute.
1459 */
1460bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1461 const asset_path& ap, const char* rootDir, const char* baseDirName)
1462{
1463 ZipFileRO* pZip;
1464 Vector<String8> dirs;
1465 AssetDir::FileInfo info;
1466 SortedVector<AssetDir::FileInfo> contents;
1467 String8 sourceName, zipName, dirName;
1468
1469 pZip = mZipSet.getZip(ap.path);
1470 if (pZip == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001471 ALOGW("Failure opening zip %s\n", ap.path.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 return false;
1473 }
1474
1475 zipName = ZipSet::getPathName(ap.path.string());
1476
1477 /* convert "sounds" to "rootDir/sounds" */
1478 if (rootDir != NULL) dirName = rootDir;
1479 dirName.appendPath(baseDirName);
1480
1481 /*
1482 * Scan through the list of files, looking for a match. The files in
1483 * the Zip table of contents are not in sorted order, so we have to
1484 * process the entire list. We're looking for a string that begins
1485 * with the characters in "dirName", is followed by a '/', and has no
1486 * subsequent '/' in the stuff that follows.
1487 *
1488 * What makes this especially fun is that directories are not stored
1489 * explicitly in Zip archives, so we have to infer them from context.
1490 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1491 * to insert a directory called "sounds" into the list. We store
1492 * these in temporary vector so that we only return each one once.
1493 *
1494 * Name comparisons are case-sensitive to match UNIX filesystem
1495 * semantics.
1496 */
1497 int dirNameLen = dirName.length();
Narayan Kamathafd31e02013-12-03 13:16:03 +00001498 void *iterationCookie;
1499 if (!pZip->startIteration(&iterationCookie)) {
1500 ALOGW("ZipFileRO::startIteration returned false");
1501 return false;
1502 }
1503
1504 ZipEntryRO entry;
1505 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 char nameBuf[256];
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1509 // TODO: fix this if we expect to have long names
Steve Block3762c312012-01-06 19:20:56 +00001510 ALOGE("ARGH: name too long?\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 continue;
1512 }
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001513 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 if (dirNameLen == 0 ||
1515 (strncmp(nameBuf, dirName.string(), dirNameLen) == 0 &&
1516 nameBuf[dirNameLen] == '/'))
1517 {
1518 const char* cp;
1519 const char* nextSlash;
1520
1521 cp = nameBuf + dirNameLen;
1522 if (dirNameLen != 0)
1523 cp++; // advance past the '/'
1524
1525 nextSlash = strchr(cp, '/');
1526//xxx this may break if there are bare directory entries
1527 if (nextSlash == NULL) {
1528 /* this is a file in the requested directory */
1529
1530 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1531
1532 info.setSourceName(
1533 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1534
1535 contents.add(info);
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001536 //printf("FOUND: file '%s'\n", info.getFileName().string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 } else {
1538 /* this is a subdir; add it if we don't already have it*/
1539 String8 subdirName(cp, nextSlash - cp);
1540 size_t j;
1541 size_t N = dirs.size();
1542
1543 for (j = 0; j < N; j++) {
1544 if (subdirName == dirs[j]) {
1545 break;
1546 }
1547 }
1548 if (j == N) {
1549 dirs.add(subdirName);
1550 }
1551
Dianne Hackbornbb9ea302009-05-18 15:22:00 -07001552 //printf("FOUND: dir '%s'\n", subdirName.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554 }
1555 }
1556
Narayan Kamathafd31e02013-12-03 13:16:03 +00001557 pZip->endIteration(iterationCookie);
1558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 /*
1560 * Add the set of unique directories.
1561 */
1562 for (int i = 0; i < (int) dirs.size(); i++) {
1563 info.set(dirs[i], kFileTypeDirectory);
1564 info.setSourceName(
1565 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1566 contents.add(info);
1567 }
1568
1569 mergeInfoLocked(pMergedInfo, &contents);
1570
1571 return true;
1572}
1573
1574
1575/*
1576 * Merge two vectors of FileInfo.
1577 *
1578 * The merged contents will be stuffed into *pMergedInfo.
1579 *
1580 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1581 * we use the newer "pContents" entry.
1582 */
1583void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1584 const SortedVector<AssetDir::FileInfo>* pContents)
1585{
1586 /*
1587 * Merge what we found in this directory with what we found in
1588 * other places.
1589 *
1590 * Two basic approaches:
1591 * (1) Create a new array that holds the unique values of the two
1592 * arrays.
1593 * (2) Take the elements from pContents and shove them into pMergedInfo.
1594 *
1595 * Because these are vectors of complex objects, moving elements around
1596 * inside the vector requires constructing new objects and allocating
1597 * storage for members. With approach #1, we're always adding to the
1598 * end, whereas with #2 we could be inserting multiple elements at the
1599 * front of the vector. Approach #1 requires a full copy of the
1600 * contents of pMergedInfo, but approach #2 requires the same copy for
1601 * every insertion at the front of pMergedInfo.
1602 *
1603 * (We should probably use a SortedVector interface that allows us to
1604 * just stuff items in, trusting us to maintain the sort order.)
1605 */
1606 SortedVector<AssetDir::FileInfo>* pNewSorted;
1607 int mergeMax, contMax;
1608 int mergeIdx, contIdx;
1609
1610 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1611 mergeMax = pMergedInfo->size();
1612 contMax = pContents->size();
1613 mergeIdx = contIdx = 0;
1614
1615 while (mergeIdx < mergeMax || contIdx < contMax) {
1616 if (mergeIdx == mergeMax) {
1617 /* hit end of "merge" list, copy rest of "contents" */
1618 pNewSorted->add(pContents->itemAt(contIdx));
1619 contIdx++;
1620 } else if (contIdx == contMax) {
1621 /* hit end of "cont" list, copy rest of "merge" */
1622 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1623 mergeIdx++;
1624 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1625 {
1626 /* items are identical, add newer and advance both indices */
1627 pNewSorted->add(pContents->itemAt(contIdx));
1628 mergeIdx++;
1629 contIdx++;
1630 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1631 {
1632 /* "merge" is lower, add that one */
1633 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1634 mergeIdx++;
1635 } else {
1636 /* "cont" is lower, add that one */
1637 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1638 pNewSorted->add(pContents->itemAt(contIdx));
1639 contIdx++;
1640 }
1641 }
1642
1643 /*
1644 * Overwrite the "merged" list with the new stuff.
1645 */
1646 *pMergedInfo = *pNewSorted;
1647 delete pNewSorted;
1648
1649#if 0 // for Vector, rather than SortedVector
1650 int i, j;
1651 for (i = pContents->size() -1; i >= 0; i--) {
1652 bool add = true;
1653
1654 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1655 /* case-sensitive comparisons, to behave like UNIX fs */
1656 if (strcmp(pContents->itemAt(i).mFileName,
1657 pMergedInfo->itemAt(j).mFileName) == 0)
1658 {
1659 /* match, don't add this entry */
1660 add = false;
1661 break;
1662 }
1663 }
1664
1665 if (add)
1666 pMergedInfo->add(pContents->itemAt(i));
1667 }
1668#endif
1669}
1670
1671
1672/*
1673 * Load all files into the file name cache. We want to do this across
1674 * all combinations of { appname, locale, vendor }, performing a recursive
1675 * directory traversal.
1676 *
1677 * This is not the most efficient data structure. Also, gathering the
1678 * information as we needed it (file-by-file or directory-by-directory)
1679 * would be faster. However, on the actual device, 99% of the files will
1680 * live in Zip archives, so this list will be very small. The trouble
1681 * is that we have to check the "loose" files first, so it's important
1682 * that we don't beat the filesystem silly looking for files that aren't
1683 * there.
1684 *
1685 * Note on thread safety: this is the only function that causes updates
1686 * to mCache, and anybody who tries to use it will call here if !mCacheValid,
1687 * so we need to employ a mutex here.
1688 */
1689void AssetManager::loadFileNameCacheLocked(void)
1690{
1691 assert(!mCacheValid);
1692 assert(mCache.size() == 0);
1693
1694#ifdef DO_TIMINGS // need to link against -lrt for this now
1695 DurationTimer timer;
1696 timer.start();
1697#endif
1698
1699 fncScanLocked(&mCache, "");
1700
1701#ifdef DO_TIMINGS
1702 timer.stop();
Steve Block5baa3a62011-12-20 16:23:08 +00001703 ALOGD("Cache scan took %.3fms\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 timer.durationUsecs() / 1000.0);
1705#endif
1706
1707#if 0
1708 int i;
1709 printf("CACHED FILE LIST (%d entries):\n", mCache.size());
1710 for (i = 0; i < (int) mCache.size(); i++) {
1711 printf(" %d: (%d) '%s'\n", i,
1712 mCache.itemAt(i).getFileType(),
1713 (const char*) mCache.itemAt(i).getFileName());
1714 }
1715#endif
1716
1717 mCacheValid = true;
1718}
1719
1720/*
1721 * Scan up to 8 versions of the specified directory.
1722 */
1723void AssetManager::fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1724 const char* dirName)
1725{
1726 size_t i = mAssetPaths.size();
1727 while (i > 0) {
1728 i--;
1729 const asset_path& ap = mAssetPaths.itemAt(i);
1730 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, NULL, dirName);
1731 if (mLocale != NULL)
1732 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, NULL, dirName);
1733 if (mVendor != NULL)
1734 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, mVendor, dirName);
1735 if (mLocale != NULL && mVendor != NULL)
1736 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, mVendor, dirName);
1737 }
1738}
1739
1740/*
1741 * Recursively scan this directory and all subdirs.
1742 *
1743 * This is similar to scanAndMergeDir, but we don't remove the .EXCLUDE
1744 * files, and we prepend the extended partial path to the filenames.
1745 */
1746bool AssetManager::fncScanAndMergeDirLocked(
1747 SortedVector<AssetDir::FileInfo>* pMergedInfo,
1748 const asset_path& ap, const char* locale, const char* vendor,
1749 const char* dirName)
1750{
1751 SortedVector<AssetDir::FileInfo>* pContents;
1752 String8 partialPath;
1753 String8 fullPath;
1754
1755 // XXX This is broken -- the filename cache needs to hold the base
1756 // asset path separately from its filename.
Elliott Hughesc367d482013-10-29 13:12:55 -07001757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 partialPath = createPathNameLocked(ap, locale, vendor);
1759 if (dirName[0] != '\0') {
1760 partialPath.appendPath(dirName);
1761 }
1762
1763 fullPath = partialPath;
1764 pContents = scanDirLocked(fullPath);
1765 if (pContents == NULL) {
1766 return false; // directory did not exist
1767 }
1768
1769 /*
1770 * Scan all subdirectories of the current dir, merging what we find
1771 * into "pMergedInfo".
1772 */
1773 for (int i = 0; i < (int) pContents->size(); i++) {
1774 if (pContents->itemAt(i).getFileType() == kFileTypeDirectory) {
1775 String8 subdir(dirName);
1776 subdir.appendPath(pContents->itemAt(i).getFileName());
1777
1778 fncScanAndMergeDirLocked(pMergedInfo, ap, locale, vendor, subdir.string());
1779 }
1780 }
1781
1782 /*
1783 * To be consistent, we want entries for the root directory. If
1784 * we're the root, add one now.
1785 */
1786 if (dirName[0] == '\0') {
1787 AssetDir::FileInfo tmpInfo;
1788
1789 tmpInfo.set(String8(""), kFileTypeDirectory);
1790 tmpInfo.setSourceName(createPathNameLocked(ap, locale, vendor));
1791 pContents->add(tmpInfo);
1792 }
1793
1794 /*
1795 * We want to prepend the extended partial path to every entry in
1796 * "pContents". It's the same value for each entry, so this will
1797 * not change the sorting order of the vector contents.
1798 */
1799 for (int i = 0; i < (int) pContents->size(); i++) {
1800 const AssetDir::FileInfo& info = pContents->itemAt(i);
1801 pContents->editItemAt(i).setFileName(partialPath.appendPathCopy(info.getFileName()));
1802 }
1803
1804 mergeInfoLocked(pMergedInfo, pContents);
sean_lu7c57d232014-06-16 15:11:29 +08001805 delete pContents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 return true;
1807}
1808
1809/*
1810 * Trash the cache.
1811 */
1812void AssetManager::purgeFileNameCacheLocked(void)
1813{
1814 mCacheValid = false;
1815 mCache.clear();
1816}
1817
1818/*
1819 * ===========================================================================
1820 * AssetManager::SharedZip
1821 * ===========================================================================
1822 */
1823
1824
1825Mutex AssetManager::SharedZip::gLock;
1826DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1827
1828AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
Dianne Hackborn78c40512009-07-06 11:07:40 -07001829 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1830 mResourceTableAsset(NULL), mResourceTable(NULL)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831{
Steve Block6215d3f2012-01-04 20:05:49 +00001832 //ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
Steve Block71f2cf12011-10-20 11:56:00 +01001833 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamathafd31e02013-12-03 13:16:03 +00001834 mZipFile = ZipFileRO::open(mPath.string());
1835 if (mZipFile == NULL) {
Steve Block5baa3a62011-12-20 16:23:08 +00001836 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 }
1838}
1839
Mårten Kongstad48d22322014-01-31 14:43:27 +01001840sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1841 bool createIfNotPresent)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842{
1843 AutoMutex _l(gLock);
1844 time_t modWhen = getFileModDate(path);
1845 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1846 if (zip != NULL && zip->mModWhen == modWhen) {
1847 return zip;
1848 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001849 if (zip == NULL && !createIfNotPresent) {
1850 return NULL;
1851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 zip = new SharedZip(path, modWhen);
1853 gOpen.add(path, zip);
1854 return zip;
1855
1856}
1857
1858ZipFileRO* AssetManager::SharedZip::getZip()
1859{
1860 return mZipFile;
1861}
1862
1863Asset* AssetManager::SharedZip::getResourceTableAsset()
1864{
Steve Block71f2cf12011-10-20 11:56:00 +01001865 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 return mResourceTableAsset;
1867}
1868
1869Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1870{
1871 {
1872 AutoMutex _l(gLock);
1873 if (mResourceTableAsset == NULL) {
1874 mResourceTableAsset = asset;
1875 // This is not thread safe the first time it is called, so
1876 // do it here with the global lock held.
1877 asset->getBuffer(true);
1878 return asset;
1879 }
1880 }
1881 delete asset;
1882 return mResourceTableAsset;
1883}
1884
Dianne Hackborn78c40512009-07-06 11:07:40 -07001885ResTable* AssetManager::SharedZip::getResourceTable()
1886{
Steve Block71f2cf12011-10-20 11:56:00 +01001887 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
Dianne Hackborn78c40512009-07-06 11:07:40 -07001888 return mResourceTable;
1889}
1890
1891ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1892{
1893 {
1894 AutoMutex _l(gLock);
1895 if (mResourceTable == NULL) {
1896 mResourceTable = res;
1897 return res;
1898 }
1899 }
1900 delete res;
1901 return mResourceTable;
1902}
1903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904bool AssetManager::SharedZip::isUpToDate()
1905{
1906 time_t modWhen = getFileModDate(mPath.string());
1907 return mModWhen == modWhen;
1908}
1909
Mårten Kongstad48d22322014-01-31 14:43:27 +01001910void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1911{
1912 mOverlays.add(ap);
1913}
1914
1915bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1916{
1917 if (idx >= mOverlays.size()) {
1918 return false;
1919 }
1920 *out = mOverlays[idx];
1921 return true;
1922}
1923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924AssetManager::SharedZip::~SharedZip()
1925{
Steve Block6215d3f2012-01-04 20:05:49 +00001926 //ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
Dianne Hackborn78c40512009-07-06 11:07:40 -07001927 if (mResourceTable != NULL) {
1928 delete mResourceTable;
1929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 if (mResourceTableAsset != NULL) {
1931 delete mResourceTableAsset;
1932 }
1933 if (mZipFile != NULL) {
1934 delete mZipFile;
Steve Block71f2cf12011-10-20 11:56:00 +01001935 ALOGV("Closed '%s'\n", mPath.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937}
1938
1939/*
1940 * ===========================================================================
1941 * AssetManager::ZipSet
1942 * ===========================================================================
1943 */
1944
1945/*
1946 * Constructor.
1947 */
1948AssetManager::ZipSet::ZipSet(void)
1949{
1950}
1951
1952/*
1953 * Destructor. Close any open archives.
1954 */
1955AssetManager::ZipSet::~ZipSet(void)
1956{
1957 size_t N = mZipFile.size();
1958 for (size_t i = 0; i < N; i++)
1959 closeZip(i);
1960}
1961
1962/*
1963 * Close a Zip file and reset the entry.
1964 */
1965void AssetManager::ZipSet::closeZip(int idx)
1966{
1967 mZipFile.editItemAt(idx) = NULL;
1968}
1969
1970
1971/*
1972 * Retrieve the appropriate Zip file from the set.
1973 */
1974ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1975{
1976 int idx = getIndex(path);
1977 sp<SharedZip> zip = mZipFile[idx];
1978 if (zip == NULL) {
1979 zip = SharedZip::get(path);
1980 mZipFile.editItemAt(idx) = zip;
1981 }
1982 return zip->getZip();
1983}
1984
Dianne Hackborn78c40512009-07-06 11:07:40 -07001985Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986{
1987 int idx = getIndex(path);
1988 sp<SharedZip> zip = mZipFile[idx];
1989 if (zip == NULL) {
1990 zip = SharedZip::get(path);
1991 mZipFile.editItemAt(idx) = zip;
1992 }
1993 return zip->getResourceTableAsset();
1994}
1995
Dianne Hackborn78c40512009-07-06 11:07:40 -07001996Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 Asset* asset)
1998{
1999 int idx = getIndex(path);
2000 sp<SharedZip> zip = mZipFile[idx];
2001 // doesn't make sense to call before previously accessing.
2002 return zip->setResourceTableAsset(asset);
2003}
2004
Dianne Hackborn78c40512009-07-06 11:07:40 -07002005ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
2006{
2007 int idx = getIndex(path);
2008 sp<SharedZip> zip = mZipFile[idx];
2009 if (zip == NULL) {
2010 zip = SharedZip::get(path);
2011 mZipFile.editItemAt(idx) = zip;
2012 }
2013 return zip->getResourceTable();
2014}
2015
2016ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
2017 ResTable* res)
2018{
2019 int idx = getIndex(path);
2020 sp<SharedZip> zip = mZipFile[idx];
2021 // doesn't make sense to call before previously accessing.
2022 return zip->setResourceTable(res);
2023}
2024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025/*
2026 * Generate the partial pathname for the specified archive. The caller
2027 * gets to prepend the asset root directory.
2028 *
2029 * Returns something like "common/en-US-noogle.jar".
2030 */
2031/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
2032{
2033 return String8(zipPath);
2034}
2035
2036bool AssetManager::ZipSet::isUpToDate()
2037{
2038 const size_t N = mZipFile.size();
2039 for (size_t i=0; i<N; i++) {
2040 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
2041 return false;
2042 }
2043 }
2044 return true;
2045}
2046
Mårten Kongstad48d22322014-01-31 14:43:27 +01002047void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
2048{
2049 int idx = getIndex(path);
2050 sp<SharedZip> zip = mZipFile[idx];
2051 zip->addOverlay(overlay);
2052}
2053
2054bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
2055{
2056 sp<SharedZip> zip = SharedZip::get(path, false);
2057 if (zip == NULL) {
2058 return false;
2059 }
2060 return zip->getOverlay(idx, out);
2061}
2062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063/*
2064 * Compute the zip file's index.
2065 *
2066 * "appName", "locale", and "vendor" should be set to NULL to indicate the
2067 * default directory.
2068 */
2069int AssetManager::ZipSet::getIndex(const String8& zip) const
2070{
2071 const size_t N = mZipPath.size();
2072 for (size_t i=0; i<N; i++) {
2073 if (mZipPath[i] == zip) {
2074 return i;
2075 }
2076 }
2077
2078 mZipPath.add(zip);
2079 mZipFile.add(NULL);
2080
2081 return mZipPath.size()-1;
2082}