blob: a1f78589b8046dc6b56bf1cff04d205c553e4c1b [file] [log] [blame]
Adam Lesinski16c4d152014-01-24 13:27:13 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Provide access to read-only assets.
19//
20
21#define LOG_TAG "asset"
22#define ATRACE_TAG ATRACE_TAG_RESOURCES
23//#define LOG_NDEBUG 0
24
25#include <androidfw/Asset.h>
26#include <androidfw/AssetDir.h>
27#include <androidfw/AssetManager.h>
28#include <androidfw/misc.h>
29#include <androidfw/ResourceTypes.h>
30#include <androidfw/ZipFileRO.h>
31#include <utils/Atomic.h>
32#include <utils/Log.h>
33#include <utils/String8.h>
34#include <utils/String8.h>
35#include <utils/threads.h>
36#include <utils/Timers.h>
37#ifdef HAVE_ANDROID_OS
38#include <cutils/trace.h>
39#endif
40
41#include <assert.h>
42#include <dirent.h>
43#include <errno.h>
Mårten Kongstad48d22322014-01-31 14:43:27 +010044#include <string.h> // strerror
Adam Lesinski16c4d152014-01-24 13:27:13 -080045#include <strings.h>
Adam Lesinski16c4d152014-01-24 13:27:13 -080046
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
56
57#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
65using 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";
Adam Lesinskide898ff2014-01-29 18:20:45 -080077static const char* kAndroidManifest = "AndroidManifest.xml";
Adam Lesinski16c4d152014-01-24 13:27:13 -080078
79static const char* kExcludeExtension = ".EXCLUDE";
80
81static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
82
83static volatile int32_t gCount = 0;
84
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010085const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
Mårten Kongstad48d22322014-01-31 14:43:27 +010086const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
87const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
88const char* AssetManager::TARGET_PACKAGE_NAME = "android";
89const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
90const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010091
Adam Lesinski16c4d152014-01-24 13:27:13 -080092namespace {
Adam Lesinski16c4d152014-01-24 13:27:13 -080093 String8 idmapPathForPackagePath(const String8& pkgPath)
94 {
95 const char* root = getenv("ANDROID_DATA");
96 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
97 String8 path(root);
Mårten Kongstad48d22322014-01-31 14:43:27 +010098 path.appendPath(kResourceCache);
Adam Lesinski16c4d152014-01-24 13:27:13 -080099
100 char buf[256]; // 256 chars should be enough for anyone...
101 strncpy(buf, pkgPath.string(), 255);
102 buf[255] = '\0';
103 char* filename = buf;
104 while (*filename && *filename == '/') {
105 ++filename;
106 }
107 char* p = filename;
108 while (*p) {
109 if (*p == '/') {
110 *p = '@';
111 }
112 ++p;
113 }
114 path.appendPath(filename);
115 path.append("@idmap");
116
117 return path;
118 }
119
120 /*
121 * Like strdup(), but uses C++ "new" operator instead of malloc.
122 */
123 static char* strdupNew(const char* str)
124 {
125 char* newStr;
126 int len;
127
128 if (str == NULL)
129 return NULL;
130
131 len = strlen(str);
132 newStr = new char[len+1];
133 memcpy(newStr, str, len+1);
134
135 return newStr;
136 }
137}
138
139/*
140 * ===========================================================================
141 * AssetManager
142 * ===========================================================================
143 */
144
145int32_t AssetManager::getGlobalCount()
146{
147 return gCount;
148}
149
150AssetManager::AssetManager(CacheMode cacheMode)
151 : mLocale(NULL), mVendor(NULL),
152 mResources(NULL), mConfig(new ResTable_config),
153 mCacheMode(cacheMode), mCacheValid(false)
154{
155 int count = android_atomic_inc(&gCount)+1;
156 //ALOGI("Creating AssetManager %p #%d\n", this, count);
157 memset(mConfig, 0, sizeof(ResTable_config));
158}
159
160AssetManager::~AssetManager(void)
161{
162 int count = android_atomic_dec(&gCount);
163 //ALOGI("Destroying AssetManager in %p #%d\n", this, count);
164
165 delete mConfig;
166 delete mResources;
167
168 // don't have a String class yet, so make sure we clean up
169 delete[] mLocale;
170 delete[] mVendor;
171}
172
Narayan Kamatha0c62602014-01-24 13:51:51 +0000173bool AssetManager::addAssetPath(const String8& path, int32_t* cookie)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800174{
175 AutoMutex _l(mLock);
176
177 asset_path ap;
178
179 String8 realPath(path);
180 if (kAppZipName) {
181 realPath.appendPath(kAppZipName);
182 }
183 ap.type = ::getFileType(realPath.string());
184 if (ap.type == kFileTypeRegular) {
185 ap.path = realPath;
186 } else {
187 ap.path = path;
188 ap.type = ::getFileType(path.string());
189 if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
190 ALOGW("Asset path %s is neither a directory nor file (type=%d).",
191 path.string(), (int)ap.type);
192 return false;
193 }
194 }
195
196 // Skip if we have it already.
197 for (size_t i=0; i<mAssetPaths.size(); i++) {
198 if (mAssetPaths[i].path == ap.path) {
199 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000200 *cookie = static_cast<int32_t>(i+1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800201 }
202 return true;
203 }
204 }
205
206 ALOGV("In %p Asset %s path: %s", this,
207 ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
208
Adam Lesinskide898ff2014-01-29 18:20:45 -0800209 // Check that the path has an AndroidManifest.xml
210 Asset* manifestAsset = const_cast<AssetManager*>(this)->openNonAssetInPathLocked(
211 kAndroidManifest, Asset::ACCESS_BUFFER, ap);
212 if (manifestAsset == NULL) {
213 // This asset path does not contain any resources.
214 delete manifestAsset;
215 return false;
216 }
217 delete manifestAsset;
218
Adam Lesinski16c4d152014-01-24 13:27:13 -0800219 mAssetPaths.add(ap);
220
221 // new paths are always added at the end
222 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000223 *cookie = static_cast<int32_t>(mAssetPaths.size());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800224 }
225
Mårten Kongstad48d22322014-01-31 14:43:27 +0100226#ifdef HAVE_ANDROID_OS
227 // Load overlays, if any
228 asset_path oap;
229 for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
230 mAssetPaths.add(oap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800231 }
Mårten Kongstad48d22322014-01-31 14:43:27 +0100232#endif
Adam Lesinski16c4d152014-01-24 13:27:13 -0800233
Martin Kosiba7df36252014-01-16 16:25:56 +0000234 if (mResources != NULL) {
235 appendPathToResTable(ap);
236 }
237
Adam Lesinski16c4d152014-01-24 13:27:13 -0800238 return true;
239}
240
Mårten Kongstad48d22322014-01-31 14:43:27 +0100241bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
242{
243 const String8 idmapPath = idmapPathForPackagePath(packagePath);
244
245 AutoMutex _l(mLock);
246
247 for (size_t i = 0; i < mAssetPaths.size(); ++i) {
248 if (mAssetPaths[i].idmap == idmapPath) {
249 *cookie = static_cast<int32_t>(i + 1);
250 return true;
251 }
252 }
253
254 Asset* idmap = NULL;
255 if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
256 ALOGW("failed to open idmap file %s\n", idmapPath.string());
257 return false;
258 }
259
260 String8 targetPath;
261 String8 overlayPath;
262 if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700263 NULL, NULL, NULL, &targetPath, &overlayPath)) {
Mårten Kongstad48d22322014-01-31 14:43:27 +0100264 ALOGW("failed to read idmap file %s\n", idmapPath.string());
265 delete idmap;
266 return false;
267 }
268 delete idmap;
269
270 if (overlayPath != packagePath) {
271 ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
272 idmapPath.string(), packagePath.string(), overlayPath.string());
273 return false;
274 }
275 if (access(targetPath.string(), R_OK) != 0) {
276 ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
277 return false;
278 }
279 if (access(idmapPath.string(), R_OK) != 0) {
280 ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
281 return false;
282 }
283 if (access(overlayPath.string(), R_OK) != 0) {
284 ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
285 return false;
286 }
287
288 asset_path oap;
289 oap.path = overlayPath;
290 oap.type = ::getFileType(overlayPath.string());
291 oap.idmap = idmapPath;
292#if 0
293 ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
294 targetPath.string(), overlayPath.string(), idmapPath.string());
295#endif
296 mAssetPaths.add(oap);
297 *cookie = static_cast<int32_t>(mAssetPaths.size());
298
Mårten Kongstad30113132014-11-07 10:52:17 +0100299 if (mResources != NULL) {
300 appendPathToResTable(oap);
301 }
302
Mårten Kongstad48d22322014-01-31 14:43:27 +0100303 return true;
304 }
305
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100306bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
Dianne Hackborn32bb5fa2014-02-11 13:56:21 -0800307 uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100308{
309 AutoMutex _l(mLock);
310 const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
311 ResTable tables[2];
312
313 for (int i = 0; i < 2; ++i) {
314 asset_path ap;
315 ap.type = kFileTypeRegular;
316 ap.path = paths[i];
317 Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
318 if (ass == NULL) {
319 ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
320 return false;
321 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700322 tables[i].add(ass);
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100323 }
324
325 return tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
326 targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
327}
328
Adam Lesinski16c4d152014-01-24 13:27:13 -0800329bool AssetManager::addDefaultAssets()
330{
331 const char* root = getenv("ANDROID_ROOT");
332 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
333
334 String8 path(root);
335 path.appendPath(kSystemAssets);
336
337 return addAssetPath(path, NULL);
338}
339
Narayan Kamatha0c62602014-01-24 13:51:51 +0000340int32_t AssetManager::nextAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800341{
342 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000343 const size_t next = static_cast<size_t>(cookie) + 1;
344 return next > mAssetPaths.size() ? -1 : next;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800345}
346
Narayan Kamatha0c62602014-01-24 13:51:51 +0000347String8 AssetManager::getAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800348{
349 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000350 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800351 if (which < mAssetPaths.size()) {
352 return mAssetPaths[which].path;
353 }
354 return String8();
355}
356
357/*
358 * Set the current locale. Use NULL to indicate no locale.
359 *
360 * Close and reopen Zip archives as appropriate, and reset cached
361 * information in the locale-specific sections of the tree.
362 */
363void AssetManager::setLocale(const char* locale)
364{
365 AutoMutex _l(mLock);
366 setLocaleLocked(locale);
367}
368
Narayan Kamathe4345db2014-06-26 16:01:28 +0100369
370static const char kFilPrefix[] = "fil";
371static const char kTlPrefix[] = "tl";
372
373// The sizes of the prefixes, excluding the 0 suffix.
374// char.
375static const int kFilPrefixLen = sizeof(kFilPrefix) - 1;
376static const int kTlPrefixLen = sizeof(kTlPrefix) - 1;
377
Adam Lesinski16c4d152014-01-24 13:27:13 -0800378void AssetManager::setLocaleLocked(const char* locale)
379{
380 if (mLocale != NULL) {
381 /* previously set, purge cached data */
382 purgeFileNameCacheLocked();
383 //mZipSet.purgeLocale();
384 delete[] mLocale;
385 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700386
Narayan Kamathe4345db2014-06-26 16:01:28 +0100387 // If we're attempting to set a locale that starts with "fil",
388 // we should convert it to "tl" for backwards compatibility since
389 // we've been using "tl" instead of "fil" prior to L.
390 //
391 // If the resource table already has entries for "fil", we use that
392 // instead of attempting a fallback.
393 if (strncmp(locale, kFilPrefix, kFilPrefixLen) == 0) {
394 Vector<String8> locales;
Narayan Kamathfec51062014-07-05 15:33:28 +0100395 ResTable* res = mResources;
396 if (res != NULL) {
397 res->getLocales(&locales);
398 }
Narayan Kamathe4345db2014-06-26 16:01:28 +0100399 const size_t localesSize = locales.size();
400 bool hasFil = false;
401 for (size_t i = 0; i < localesSize; ++i) {
402 if (locales[i].find(kFilPrefix) == 0) {
403 hasFil = true;
404 break;
405 }
406 }
407
408
409 if (!hasFil) {
410 const size_t newLocaleLen = strlen(locale);
411 // This isn't a bug. We really do want mLocale to be 1 byte
412 // shorter than locale, because we're replacing "fil-" with
413 // "tl-".
414 mLocale = new char[newLocaleLen];
415 // Copy over "tl".
416 memcpy(mLocale, kTlPrefix, kTlPrefixLen);
417 // Copy the rest of |locale|, including the terminating '\0'.
418 memcpy(mLocale + kTlPrefixLen, locale + kFilPrefixLen,
419 newLocaleLen - kFilPrefixLen + 1);
420 updateResourceParamsLocked();
421 return;
422 }
423 }
424
Adam Lesinski16c4d152014-01-24 13:27:13 -0800425 mLocale = strdupNew(locale);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800426 updateResourceParamsLocked();
427}
428
429/*
430 * Set the current vendor. Use NULL to indicate no vendor.
431 *
432 * Close and reopen Zip archives as appropriate, and reset cached
433 * information in the vendor-specific sections of the tree.
434 */
435void AssetManager::setVendor(const char* vendor)
436{
437 AutoMutex _l(mLock);
438
439 if (mVendor != NULL) {
440 /* previously set, purge cached data */
441 purgeFileNameCacheLocked();
442 //mZipSet.purgeVendor();
443 delete[] mVendor;
444 }
445 mVendor = strdupNew(vendor);
446}
447
448void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
449{
450 AutoMutex _l(mLock);
451 *mConfig = config;
452 if (locale) {
453 setLocaleLocked(locale);
454 } else if (config.language[0] != 0) {
Narayan Kamath91447d82014-01-21 15:32:36 +0000455 char spec[RESTABLE_MAX_LOCALE_LEN];
456 config.getBcp47Locale(spec);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800457 setLocaleLocked(spec);
458 } else {
459 updateResourceParamsLocked();
460 }
461}
462
463void AssetManager::getConfiguration(ResTable_config* outConfig) const
464{
465 AutoMutex _l(mLock);
466 *outConfig = *mConfig;
467}
468
469/*
470 * Open an asset.
471 *
472 * The data could be;
473 * - In a file on disk (assetBase + fileName).
474 * - In a compressed file on disk (assetBase + fileName.gz).
475 * - In a Zip archive, uncompressed or compressed.
476 *
477 * It can be in a number of different directories and Zip archives.
478 * The search order is:
479 * - [appname]
480 * - locale + vendor
481 * - "default" + vendor
482 * - locale + "default"
483 * - "default + "default"
484 * - "common"
485 * - (same as above)
486 *
487 * To find a particular file, we have to try up to eight paths with
488 * all three forms of data.
489 *
490 * We should probably reject requests for "illegal" filenames, e.g. those
491 * with illegal characters or "../" backward relative paths.
492 */
493Asset* AssetManager::open(const char* fileName, AccessMode mode)
494{
495 AutoMutex _l(mLock);
496
497 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
498
499
500 if (mCacheMode != CACHE_OFF && !mCacheValid)
501 loadFileNameCacheLocked();
502
503 String8 assetName(kAssetsRoot);
504 assetName.appendPath(fileName);
505
506 /*
507 * For each top-level asset path, search for the asset.
508 */
509
510 size_t i = mAssetPaths.size();
511 while (i > 0) {
512 i--;
513 ALOGV("Looking for asset '%s' in '%s'\n",
514 assetName.string(), mAssetPaths.itemAt(i).path.string());
515 Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
516 if (pAsset != NULL) {
517 return pAsset != kExcludedAsset ? pAsset : NULL;
518 }
519 }
520
521 return NULL;
522}
523
524/*
525 * Open a non-asset file as if it were an asset.
526 *
527 * The "fileName" is the partial path starting from the application
528 * name.
529 */
Adam Lesinskide898ff2014-01-29 18:20:45 -0800530Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800531{
532 AutoMutex _l(mLock);
533
534 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
535
536
537 if (mCacheMode != CACHE_OFF && !mCacheValid)
538 loadFileNameCacheLocked();
539
540 /*
541 * For each top-level asset path, search for the asset.
542 */
543
544 size_t i = mAssetPaths.size();
545 while (i > 0) {
546 i--;
547 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
548 Asset* pAsset = openNonAssetInPathLocked(
549 fileName, mode, mAssetPaths.itemAt(i));
550 if (pAsset != NULL) {
Adam Lesinskide898ff2014-01-29 18:20:45 -0800551 if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800552 return pAsset != kExcludedAsset ? pAsset : NULL;
553 }
554 }
555
556 return NULL;
557}
558
Narayan Kamatha0c62602014-01-24 13:51:51 +0000559Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800560{
Narayan Kamatha0c62602014-01-24 13:51:51 +0000561 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800562
563 AutoMutex _l(mLock);
564
565 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
566
Adam Lesinski16c4d152014-01-24 13:27:13 -0800567 if (mCacheMode != CACHE_OFF && !mCacheValid)
568 loadFileNameCacheLocked();
569
570 if (which < mAssetPaths.size()) {
571 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
572 mAssetPaths.itemAt(which).path.string());
573 Asset* pAsset = openNonAssetInPathLocked(
574 fileName, mode, mAssetPaths.itemAt(which));
575 if (pAsset != NULL) {
576 return pAsset != kExcludedAsset ? pAsset : NULL;
577 }
578 }
579
580 return NULL;
581}
582
583/*
584 * Get the type of a file in the asset namespace.
585 *
586 * This currently only works for regular files. All others (including
587 * directories) will return kFileTypeNonexistent.
588 */
589FileType AssetManager::getFileType(const char* fileName)
590{
591 Asset* pAsset = NULL;
592
593 /*
594 * Open the asset. This is less efficient than simply finding the
595 * file, but it's not too bad (we don't uncompress or mmap data until
596 * the first read() call).
597 */
598 pAsset = open(fileName, Asset::ACCESS_STREAMING);
599 delete pAsset;
600
601 if (pAsset == NULL)
602 return kFileTypeNonexistent;
603 else
604 return kFileTypeRegular;
605}
606
Martin Kosiba7df36252014-01-16 16:25:56 +0000607bool AssetManager::appendPathToResTable(const asset_path& ap) const {
608 Asset* ass = NULL;
609 ResTable* sharedRes = NULL;
610 bool shared = true;
611 bool onlyEmptyResources = true;
612 MY_TRACE_BEGIN(ap.path.string());
613 Asset* idmap = openIdmapLocked(ap);
614 size_t nextEntryIdx = mResources->getTableCount();
615 ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
616 if (ap.type != kFileTypeDirectory) {
617 if (nextEntryIdx == 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);
622 if (sharedRes != NULL) {
623 // skip ahead the number of system overlay packages preloaded
624 nextEntryIdx = sharedRes->getTableCount();
625 }
626 }
627 if (sharedRes == NULL) {
628 ass = const_cast<AssetManager*>(this)->
629 mZipSet.getZipResourceTableAsset(ap.path);
630 if (ass == NULL) {
631 ALOGV("loading resource table %s\n", ap.path.string());
632 ass = const_cast<AssetManager*>(this)->
633 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 }
641
642 if (nextEntryIdx == 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.
646 ALOGV("Creating shared resources for %s", ap.path.string());
647 sharedRes = new ResTable();
648 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
649#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, nextEntryIdx);
656#endif
657 sharedRes = const_cast<AssetManager*>(this)->
658 mZipSet.setZipResourceTable(ap.path, sharedRes);
659 }
660 }
661 } else {
662 ALOGV("loading resource table %s\n", ap.path.string());
663 ass = const_cast<AssetManager*>(this)->
664 openNonAssetInPathLocked("resources.arsc",
665 Asset::ACCESS_BUFFER,
666 ap);
667 shared = false;
668 }
669
670 if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
671 ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
672 if (sharedRes != NULL) {
673 ALOGV("Copying existing resources for %s", ap.path.string());
674 mResources->add(sharedRes);
675 } else {
676 ALOGV("Parsing resources for %s", ap.path.string());
677 mResources->add(ass, idmap, nextEntryIdx + 1, !shared);
678 }
679 onlyEmptyResources = false;
680
681 if (!shared) {
682 delete ass;
683 }
684 } else {
685 ALOGV("Installing empty resources in to table %p\n", mResources);
686 mResources->addEmpty(nextEntryIdx + 1);
687 }
688
689 if (idmap != NULL) {
690 delete idmap;
691 }
692 MY_TRACE_END();
693
694 return onlyEmptyResources;
695}
696
Adam Lesinski16c4d152014-01-24 13:27:13 -0800697const ResTable* AssetManager::getResTable(bool required) const
698{
699 ResTable* rt = mResources;
700 if (rt) {
701 return rt;
702 }
703
704 // Iterate through all asset packages, collecting resources from each.
705
706 AutoMutex _l(mLock);
707
708 if (mResources != NULL) {
709 return mResources;
710 }
711
712 if (required) {
713 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
714 }
715
Adam Lesinskide898ff2014-01-29 18:20:45 -0800716 if (mCacheMode != CACHE_OFF && !mCacheValid) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800717 const_cast<AssetManager*>(this)->loadFileNameCacheLocked();
Adam Lesinskide898ff2014-01-29 18:20:45 -0800718 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800719
Adam Lesinskide898ff2014-01-29 18:20:45 -0800720 mResources = new ResTable();
721 updateResourceParamsLocked();
722
723 bool onlyEmptyResources = true;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800724 const size_t N = mAssetPaths.size();
725 for (size_t i=0; i<N; i++) {
Martin Kosiba7df36252014-01-16 16:25:56 +0000726 bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
727 onlyEmptyResources = onlyEmptyResources && empty;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800728 }
729
Adam Lesinskide898ff2014-01-29 18:20:45 -0800730 if (required && onlyEmptyResources) {
731 ALOGW("Unable to find resources file resources.arsc");
732 delete mResources;
733 mResources = NULL;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800734 }
Adam Lesinskide898ff2014-01-29 18:20:45 -0800735
736 return mResources;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800737}
738
739void AssetManager::updateResourceParamsLocked() const
740{
741 ResTable* res = mResources;
742 if (!res) {
743 return;
744 }
745
Narayan Kamath91447d82014-01-21 15:32:36 +0000746 if (mLocale) {
747 mConfig->setBcp47Locale(mLocale);
748 } else {
749 mConfig->clearLocale();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800750 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800751
752 res->setParameters(mConfig);
753}
754
755Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
756{
757 Asset* ass = NULL;
758 if (ap.idmap.size() != 0) {
759 ass = const_cast<AssetManager*>(this)->
760 openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
761 if (ass) {
762 ALOGV("loading idmap %s\n", ap.idmap.string());
763 } else {
764 ALOGW("failed to load idmap %s\n", ap.idmap.string());
765 }
766 }
767 return ass;
768}
769
Mårten Kongstad48d22322014-01-31 14:43:27 +0100770void AssetManager::addSystemOverlays(const char* pathOverlaysList,
771 const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
772{
773 FILE* fin = fopen(pathOverlaysList, "r");
774 if (fin == NULL) {
775 return;
776 }
777
778 char buf[1024];
779 while (fgets(buf, sizeof(buf), fin)) {
780 // format of each line:
781 // <path to apk><space><path to idmap><newline>
782 char* space = strchr(buf, ' ');
783 char* newline = strchr(buf, '\n');
784 asset_path oap;
785
786 if (space == NULL || newline == NULL || newline < space) {
787 continue;
788 }
789
790 oap.path = String8(buf, space - buf);
791 oap.type = kFileTypeRegular;
792 oap.idmap = String8(space + 1, newline - space - 1);
793
794 Asset* oass = const_cast<AssetManager*>(this)->
795 openNonAssetInPathLocked("resources.arsc",
796 Asset::ACCESS_BUFFER,
797 oap);
798
799 if (oass != NULL) {
800 Asset* oidmap = openIdmapLocked(oap);
801 offset++;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700802 sharedRes->add(oass, oidmap, offset + 1, false);
Mårten Kongstad48d22322014-01-31 14:43:27 +0100803 const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
804 const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
805 }
806 }
807 fclose(fin);
808}
809
Adam Lesinski16c4d152014-01-24 13:27:13 -0800810const ResTable& AssetManager::getResources(bool required) const
811{
812 const ResTable* rt = getResTable(required);
813 return *rt;
814}
815
816bool AssetManager::isUpToDate()
817{
818 AutoMutex _l(mLock);
819 return mZipSet.isUpToDate();
820}
821
822void AssetManager::getLocales(Vector<String8>* locales) const
823{
824 ResTable* res = mResources;
825 if (res != NULL) {
826 res->getLocales(locales);
827 }
Narayan Kamathe4345db2014-06-26 16:01:28 +0100828
829 const size_t numLocales = locales->size();
830 for (size_t i = 0; i < numLocales; ++i) {
831 const String8& localeStr = locales->itemAt(i);
832 if (localeStr.find(kTlPrefix) == 0) {
833 String8 replaced("fil");
834 replaced += (localeStr.string() + kTlPrefixLen);
835 locales->editItemAt(i) = replaced;
836 }
837 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800838}
839
840/*
841 * Open a non-asset file as if it were an asset, searching for it in the
842 * specified app.
843 *
844 * Pass in a NULL values for "appName" if the common app directory should
845 * be used.
846 */
847Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
848 const asset_path& ap)
849{
850 Asset* pAsset = NULL;
851
852 /* look at the filesystem on disk */
853 if (ap.type == kFileTypeDirectory) {
854 String8 path(ap.path);
855 path.appendPath(fileName);
856
857 pAsset = openAssetFromFileLocked(path, mode);
858
859 if (pAsset == NULL) {
860 /* try again, this time with ".gz" */
861 path.append(".gz");
862 pAsset = openAssetFromFileLocked(path, mode);
863 }
864
865 if (pAsset != NULL) {
866 //printf("FOUND NA '%s' on disk\n", fileName);
867 pAsset->setAssetSource(path);
868 }
869
870 /* look inside the zip file */
871 } else {
872 String8 path(fileName);
873
874 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +0000875 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800876 if (pZip != NULL) {
877 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000878 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800879 if (entry != NULL) {
880 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
881 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000882 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800883 }
884 }
885
886 if (pAsset != NULL) {
887 /* create a "source" name, for debug/display */
888 pAsset->setAssetSource(
889 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
890 String8(fileName)));
891 }
892 }
893
894 return pAsset;
895}
896
897/*
898 * Open an asset, searching for it in the directory hierarchy for the
899 * specified app.
900 *
901 * Pass in a NULL values for "appName" if the common app directory should
902 * be used.
903 */
904Asset* AssetManager::openInPathLocked(const char* fileName, AccessMode mode,
905 const asset_path& ap)
906{
907 Asset* pAsset = NULL;
908
909 /*
910 * Try various combinations of locale and vendor.
911 */
912 if (mLocale != NULL && mVendor != NULL)
913 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, mVendor);
914 if (pAsset == NULL && mVendor != NULL)
915 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, mVendor);
916 if (pAsset == NULL && mLocale != NULL)
917 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, NULL);
918 if (pAsset == NULL)
919 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, NULL);
920
921 return pAsset;
922}
923
924/*
925 * Open an asset, searching for it in the directory hierarchy for the
926 * specified locale and vendor.
927 *
928 * We also search in "app.jar".
929 *
930 * Pass in NULL values for "appName", "locale", and "vendor" if the
931 * defaults should be used.
932 */
933Asset* AssetManager::openInLocaleVendorLocked(const char* fileName, AccessMode mode,
934 const asset_path& ap, const char* locale, const char* vendor)
935{
936 Asset* pAsset = NULL;
937
938 if (ap.type == kFileTypeDirectory) {
939 if (mCacheMode == CACHE_OFF) {
940 /* look at the filesystem on disk */
941 String8 path(createPathNameLocked(ap, locale, vendor));
942 path.appendPath(fileName);
943
944 String8 excludeName(path);
945 excludeName.append(kExcludeExtension);
946 if (::getFileType(excludeName.string()) != kFileTypeNonexistent) {
947 /* say no more */
948 //printf("+++ excluding '%s'\n", (const char*) excludeName);
949 return kExcludedAsset;
950 }
951
952 pAsset = openAssetFromFileLocked(path, mode);
953
954 if (pAsset == NULL) {
955 /* try again, this time with ".gz" */
956 path.append(".gz");
957 pAsset = openAssetFromFileLocked(path, mode);
958 }
959
960 if (pAsset != NULL)
961 pAsset->setAssetSource(path);
962 } else {
963 /* find in cache */
964 String8 path(createPathNameLocked(ap, locale, vendor));
965 path.appendPath(fileName);
966
967 AssetDir::FileInfo tmpInfo;
968 bool found = false;
969
970 String8 excludeName(path);
971 excludeName.append(kExcludeExtension);
972
973 if (mCache.indexOf(excludeName) != NAME_NOT_FOUND) {
974 /* go no farther */
975 //printf("+++ Excluding '%s'\n", (const char*) excludeName);
976 return kExcludedAsset;
977 }
978
979 /*
980 * File compression extensions (".gz") don't get stored in the
981 * name cache, so we have to try both here.
982 */
983 if (mCache.indexOf(path) != NAME_NOT_FOUND) {
984 found = true;
985 pAsset = openAssetFromFileLocked(path, mode);
986 if (pAsset == NULL) {
987 /* try again, this time with ".gz" */
988 path.append(".gz");
989 pAsset = openAssetFromFileLocked(path, mode);
990 }
991 }
992
993 if (pAsset != NULL)
994 pAsset->setAssetSource(path);
995
996 /*
997 * Don't continue the search into the Zip files. Our cached info
998 * said it was a file on disk; to be consistent with openDir()
999 * we want to return the loose asset. If the cached file gets
1000 * removed, we fail.
1001 *
1002 * The alternative is to update our cache when files get deleted,
1003 * or make some sort of "best effort" promise, but for now I'm
1004 * taking the hard line.
1005 */
1006 if (found) {
1007 if (pAsset == NULL)
1008 ALOGD("Expected file not found: '%s'\n", path.string());
1009 return pAsset;
1010 }
1011 }
1012 }
1013
1014 /*
1015 * Either it wasn't found on disk or on the cached view of the disk.
1016 * Dig through the currently-opened set of Zip files. If caching
1017 * is disabled, the Zip file may get reopened.
1018 */
1019 if (pAsset == NULL && ap.type == kFileTypeRegular) {
1020 String8 path;
1021
1022 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1023 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1024 path.appendPath(fileName);
1025
1026 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +00001027 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001028 if (pZip != NULL) {
1029 //printf("GOT zip, checking '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +00001030 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001031 if (entry != NULL) {
1032 //printf("FOUND in Zip file for %s/%s-%s\n",
1033 // appName, locale, vendor);
1034 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +00001035 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001036 }
1037 }
1038
1039 if (pAsset != NULL) {
1040 /* create a "source" name, for debug/display */
1041 pAsset->setAssetSource(createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()),
1042 String8(""), String8(fileName)));
1043 }
1044 }
1045
1046 return pAsset;
1047}
1048
1049/*
1050 * Create a "source name" for a file from a Zip archive.
1051 */
1052String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
1053 const String8& dirName, const String8& fileName)
1054{
1055 String8 sourceName("zip:");
1056 sourceName.append(zipFileName);
1057 sourceName.append(":");
1058 if (dirName.length() > 0) {
1059 sourceName.appendPath(dirName);
1060 }
1061 sourceName.appendPath(fileName);
1062 return sourceName;
1063}
1064
1065/*
1066 * Create a path to a loose asset (asset-base/app/locale/vendor).
1067 */
1068String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
1069 const char* vendor)
1070{
1071 String8 path(ap.path);
1072 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1073 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1074 return path;
1075}
1076
1077/*
1078 * Create a path to a loose asset (asset-base/app/rootDir).
1079 */
1080String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
1081{
1082 String8 path(ap.path);
1083 if (rootDir != NULL) path.appendPath(rootDir);
1084 return path;
1085}
1086
1087/*
1088 * Return a pointer to one of our open Zip archives. Returns NULL if no
1089 * matching Zip file exists.
1090 *
1091 * Right now we have 2 possible Zip files (1 each in app/"common").
1092 *
1093 * If caching is set to CACHE_OFF, to get the expected behavior we
1094 * need to reopen the Zip file on every request. That would be silly
1095 * and expensive, so instead we just check the file modification date.
1096 *
1097 * Pass in NULL values for "appName", "locale", and "vendor" if the
1098 * generics should be used.
1099 */
1100ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
1101{
1102 ALOGV("getZipFileLocked() in %p\n", this);
1103
1104 return mZipSet.getZip(ap.path);
1105}
1106
1107/*
1108 * Try to open an asset from a file on disk.
1109 *
1110 * If the file is compressed with gzip, we seek to the start of the
1111 * deflated data and pass that in (just like we would for a Zip archive).
1112 *
1113 * For uncompressed data, we may already have an mmap()ed version sitting
1114 * around. If so, we want to hand that to the Asset instead.
1115 *
1116 * This returns NULL if the file doesn't exist, couldn't be opened, or
1117 * claims to be a ".gz" but isn't.
1118 */
1119Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
1120 AccessMode mode)
1121{
1122 Asset* pAsset = NULL;
1123
1124 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
1125 //printf("TRYING '%s'\n", (const char*) pathName);
1126 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
1127 } else {
1128 //printf("TRYING '%s'\n", (const char*) pathName);
1129 pAsset = Asset::createFromFile(pathName.string(), mode);
1130 }
1131
1132 return pAsset;
1133}
1134
1135/*
1136 * Given an entry in a Zip archive, create a new Asset object.
1137 *
1138 * If the entry is uncompressed, we may want to create or share a
1139 * slice of shared memory.
1140 */
1141Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
1142 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
1143{
1144 Asset* pAsset = NULL;
1145
1146 // TODO: look for previously-created shared memory slice?
1147 int method;
1148 size_t uncompressedLen;
1149
1150 //printf("USING Zip '%s'\n", pEntry->getFileName());
1151
1152 //pZipFile->getEntryInfo(entry, &method, &uncompressedLen, &compressedLen,
1153 // &offset);
1154 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
1155 NULL, NULL))
1156 {
1157 ALOGW("getEntryInfo failed\n");
1158 return NULL;
1159 }
1160
1161 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
1162 if (dataMap == NULL) {
1163 ALOGW("create map from entry failed\n");
1164 return NULL;
1165 }
1166
1167 if (method == ZipFileRO::kCompressStored) {
1168 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
1169 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
1170 dataMap->getFileName(), mode, pAsset);
1171 } else {
1172 pAsset = Asset::createFromCompressedMap(dataMap, method,
1173 uncompressedLen, mode);
1174 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
1175 dataMap->getFileName(), mode, pAsset);
1176 }
1177 if (pAsset == NULL) {
1178 /* unexpected */
1179 ALOGW("create from segment failed\n");
1180 }
1181
1182 return pAsset;
1183}
1184
1185
1186
1187/*
1188 * Open a directory in the asset namespace.
1189 *
1190 * An "asset directory" is simply the combination of all files in all
1191 * locations, with ".gz" stripped for loose files. With app, locale, and
1192 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1193 *
1194 * Pass in "" for the root dir.
1195 */
1196AssetDir* AssetManager::openDir(const char* dirName)
1197{
1198 AutoMutex _l(mLock);
1199
1200 AssetDir* pDir = NULL;
1201 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1202
1203 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1204 assert(dirName != NULL);
1205
1206 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1207
1208 if (mCacheMode != CACHE_OFF && !mCacheValid)
1209 loadFileNameCacheLocked();
1210
1211 pDir = new AssetDir;
1212
1213 /*
1214 * Scan the various directories, merging what we find into a single
1215 * vector. We want to scan them in reverse priority order so that
1216 * the ".EXCLUDE" processing works correctly. Also, if we decide we
1217 * want to remember where the file is coming from, we'll get the right
1218 * version.
1219 *
1220 * We start with Zip archives, then do loose files.
1221 */
1222 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1223
1224 size_t i = mAssetPaths.size();
1225 while (i > 0) {
1226 i--;
1227 const asset_path& ap = mAssetPaths.itemAt(i);
1228 if (ap.type == kFileTypeRegular) {
1229 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1230 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1231 } else {
1232 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1233 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1234 }
1235 }
1236
1237#if 0
1238 printf("FILE LIST:\n");
1239 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1240 printf(" %d: (%d) '%s'\n", i,
1241 pMergedInfo->itemAt(i).getFileType(),
1242 (const char*) pMergedInfo->itemAt(i).getFileName());
1243 }
1244#endif
1245
1246 pDir->setFileList(pMergedInfo);
1247 return pDir;
1248}
1249
1250/*
1251 * Open a directory in the non-asset namespace.
1252 *
1253 * An "asset directory" is simply the combination of all files in all
1254 * locations, with ".gz" stripped for loose files. With app, locale, and
1255 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1256 *
1257 * Pass in "" for the root dir.
1258 */
Narayan Kamatha0c62602014-01-24 13:51:51 +00001259AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001260{
1261 AutoMutex _l(mLock);
1262
1263 AssetDir* pDir = NULL;
1264 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1265
1266 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1267 assert(dirName != NULL);
1268
1269 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1270
1271 if (mCacheMode != CACHE_OFF && !mCacheValid)
1272 loadFileNameCacheLocked();
1273
1274 pDir = new AssetDir;
1275
1276 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1277
Narayan Kamatha0c62602014-01-24 13:51:51 +00001278 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001279
1280 if (which < mAssetPaths.size()) {
1281 const asset_path& ap = mAssetPaths.itemAt(which);
1282 if (ap.type == kFileTypeRegular) {
1283 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1284 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
1285 } else {
1286 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1287 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
1288 }
1289 }
1290
1291#if 0
1292 printf("FILE LIST:\n");
1293 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1294 printf(" %d: (%d) '%s'\n", i,
1295 pMergedInfo->itemAt(i).getFileType(),
1296 (const char*) pMergedInfo->itemAt(i).getFileName());
1297 }
1298#endif
1299
1300 pDir->setFileList(pMergedInfo);
1301 return pDir;
1302}
1303
1304/*
1305 * Scan the contents of the specified directory and merge them into the
1306 * "pMergedInfo" vector, removing previous entries if we find "exclude"
1307 * directives.
1308 *
1309 * Returns "false" if we found nothing to contribute.
1310 */
1311bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1312 const asset_path& ap, const char* rootDir, const char* dirName)
1313{
1314 SortedVector<AssetDir::FileInfo>* pContents;
1315 String8 path;
1316
1317 assert(pMergedInfo != NULL);
1318
1319 //printf("scanAndMergeDir: %s %s %s %s\n", appName, locale, vendor,dirName);
1320
1321 if (mCacheValid) {
1322 int i, start, count;
1323
1324 pContents = new SortedVector<AssetDir::FileInfo>;
1325
1326 /*
1327 * Get the basic partial path and find it in the cache. That's
1328 * the start point for the search.
1329 */
1330 path = createPathNameLocked(ap, rootDir);
1331 if (dirName[0] != '\0')
1332 path.appendPath(dirName);
1333
1334 start = mCache.indexOf(path);
1335 if (start == NAME_NOT_FOUND) {
1336 //printf("+++ not found in cache: dir '%s'\n", (const char*) path);
1337 delete pContents;
1338 return false;
1339 }
1340
1341 /*
1342 * The match string looks like "common/default/default/foo/bar/".
1343 * The '/' on the end ensures that we don't match on the directory
1344 * itself or on ".../foo/barfy/".
1345 */
1346 path.append("/");
1347
1348 count = mCache.size();
1349
1350 /*
1351 * Pick out the stuff in the current dir by examining the pathname.
1352 * It needs to match the partial pathname prefix, and not have a '/'
1353 * (fssep) anywhere after the prefix.
1354 */
1355 for (i = start+1; i < count; i++) {
1356 if (mCache[i].getFileName().length() > path.length() &&
1357 strncmp(mCache[i].getFileName().string(), path.string(), path.length()) == 0)
1358 {
1359 const char* name = mCache[i].getFileName().string();
1360 // XXX THIS IS BROKEN! Looks like we need to store the full
1361 // path prefix separately from the file path.
1362 if (strchr(name + path.length(), '/') == NULL) {
1363 /* grab it, reducing path to just the filename component */
1364 AssetDir::FileInfo tmp = mCache[i];
1365 tmp.setFileName(tmp.getFileName().getPathLeaf());
1366 pContents->add(tmp);
1367 }
1368 } else {
1369 /* no longer in the dir or its subdirs */
1370 break;
1371 }
1372
1373 }
1374 } else {
1375 path = createPathNameLocked(ap, rootDir);
1376 if (dirName[0] != '\0')
1377 path.appendPath(dirName);
1378 pContents = scanDirLocked(path);
1379 if (pContents == NULL)
1380 return false;
1381 }
1382
1383 // if we wanted to do an incremental cache fill, we would do it here
1384
1385 /*
1386 * Process "exclude" directives. If we find a filename that ends with
1387 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1388 * remove it if we find it. We also delete the "exclude" entry.
1389 */
1390 int i, count, exclExtLen;
1391
1392 count = pContents->size();
1393 exclExtLen = strlen(kExcludeExtension);
1394 for (i = 0; i < count; i++) {
1395 const char* name;
1396 int nameLen;
1397
1398 name = pContents->itemAt(i).getFileName().string();
1399 nameLen = strlen(name);
1400 if (nameLen > exclExtLen &&
1401 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1402 {
1403 String8 match(name, nameLen - exclExtLen);
1404 int matchIdx;
1405
1406 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1407 if (matchIdx > 0) {
1408 ALOGV("Excluding '%s' [%s]\n",
1409 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1410 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1411 pMergedInfo->removeAt(matchIdx);
1412 } else {
1413 //printf("+++ no match on '%s'\n", (const char*) match);
1414 }
1415
1416 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1417 pContents->removeAt(i);
1418 i--; // adjust "for" loop
1419 count--; // and loop limit
1420 }
1421 }
1422
1423 mergeInfoLocked(pMergedInfo, pContents);
1424
1425 delete pContents;
1426
1427 return true;
1428}
1429
1430/*
1431 * Scan the contents of the specified directory, and stuff what we find
1432 * into a newly-allocated vector.
1433 *
1434 * Files ending in ".gz" will have their extensions removed.
1435 *
1436 * We should probably think about skipping files with "illegal" names,
1437 * e.g. illegal characters (/\:) or excessive length.
1438 *
1439 * Returns NULL if the specified directory doesn't exist.
1440 */
1441SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1442{
1443 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1444 DIR* dir;
1445 struct dirent* entry;
1446 FileType fileType;
1447
1448 ALOGV("Scanning dir '%s'\n", path.string());
1449
1450 dir = opendir(path.string());
1451 if (dir == NULL)
1452 return NULL;
1453
1454 pContents = new SortedVector<AssetDir::FileInfo>;
1455
1456 while (1) {
1457 entry = readdir(dir);
1458 if (entry == NULL)
1459 break;
1460
1461 if (strcmp(entry->d_name, ".") == 0 ||
1462 strcmp(entry->d_name, "..") == 0)
1463 continue;
1464
1465#ifdef _DIRENT_HAVE_D_TYPE
1466 if (entry->d_type == DT_REG)
1467 fileType = kFileTypeRegular;
1468 else if (entry->d_type == DT_DIR)
1469 fileType = kFileTypeDirectory;
1470 else
1471 fileType = kFileTypeUnknown;
1472#else
1473 // stat the file
1474 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1475#endif
1476
1477 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1478 continue;
1479
1480 AssetDir::FileInfo info;
1481 info.set(String8(entry->d_name), fileType);
1482 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1483 info.setFileName(info.getFileName().getBasePath());
1484 info.setSourceName(path.appendPathCopy(info.getFileName()));
1485 pContents->add(info);
1486 }
1487
1488 closedir(dir);
1489 return pContents;
1490}
1491
1492/*
1493 * Scan the contents out of the specified Zip archive, and merge what we
1494 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1495 * we return immediately.
1496 *
1497 * Returns "false" if we found nothing to contribute.
1498 */
1499bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1500 const asset_path& ap, const char* rootDir, const char* baseDirName)
1501{
1502 ZipFileRO* pZip;
1503 Vector<String8> dirs;
1504 AssetDir::FileInfo info;
1505 SortedVector<AssetDir::FileInfo> contents;
1506 String8 sourceName, zipName, dirName;
1507
1508 pZip = mZipSet.getZip(ap.path);
1509 if (pZip == NULL) {
1510 ALOGW("Failure opening zip %s\n", ap.path.string());
1511 return false;
1512 }
1513
1514 zipName = ZipSet::getPathName(ap.path.string());
1515
1516 /* convert "sounds" to "rootDir/sounds" */
1517 if (rootDir != NULL) dirName = rootDir;
1518 dirName.appendPath(baseDirName);
1519
1520 /*
1521 * Scan through the list of files, looking for a match. The files in
1522 * the Zip table of contents are not in sorted order, so we have to
1523 * process the entire list. We're looking for a string that begins
1524 * with the characters in "dirName", is followed by a '/', and has no
1525 * subsequent '/' in the stuff that follows.
1526 *
1527 * What makes this especially fun is that directories are not stored
1528 * explicitly in Zip archives, so we have to infer them from context.
1529 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1530 * to insert a directory called "sounds" into the list. We store
1531 * these in temporary vector so that we only return each one once.
1532 *
1533 * Name comparisons are case-sensitive to match UNIX filesystem
1534 * semantics.
1535 */
1536 int dirNameLen = dirName.length();
Narayan Kamath560566d2013-12-03 13:16:03 +00001537 void *iterationCookie;
1538 if (!pZip->startIteration(&iterationCookie)) {
1539 ALOGW("ZipFileRO::startIteration returned false");
1540 return false;
1541 }
1542
1543 ZipEntryRO entry;
1544 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001545 char nameBuf[256];
1546
Adam Lesinski16c4d152014-01-24 13:27:13 -08001547 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1548 // TODO: fix this if we expect to have long names
1549 ALOGE("ARGH: name too long?\n");
1550 continue;
1551 }
1552 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
1553 if (dirNameLen == 0 ||
1554 (strncmp(nameBuf, dirName.string(), dirNameLen) == 0 &&
1555 nameBuf[dirNameLen] == '/'))
1556 {
1557 const char* cp;
1558 const char* nextSlash;
1559
1560 cp = nameBuf + dirNameLen;
1561 if (dirNameLen != 0)
1562 cp++; // advance past the '/'
1563
1564 nextSlash = strchr(cp, '/');
1565//xxx this may break if there are bare directory entries
1566 if (nextSlash == NULL) {
1567 /* this is a file in the requested directory */
1568
1569 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1570
1571 info.setSourceName(
1572 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1573
1574 contents.add(info);
1575 //printf("FOUND: file '%s'\n", info.getFileName().string());
1576 } else {
1577 /* this is a subdir; add it if we don't already have it*/
1578 String8 subdirName(cp, nextSlash - cp);
1579 size_t j;
1580 size_t N = dirs.size();
1581
1582 for (j = 0; j < N; j++) {
1583 if (subdirName == dirs[j]) {
1584 break;
1585 }
1586 }
1587 if (j == N) {
1588 dirs.add(subdirName);
1589 }
1590
1591 //printf("FOUND: dir '%s'\n", subdirName.string());
1592 }
1593 }
1594 }
1595
Narayan Kamath560566d2013-12-03 13:16:03 +00001596 pZip->endIteration(iterationCookie);
1597
Adam Lesinski16c4d152014-01-24 13:27:13 -08001598 /*
1599 * Add the set of unique directories.
1600 */
1601 for (int i = 0; i < (int) dirs.size(); i++) {
1602 info.set(dirs[i], kFileTypeDirectory);
1603 info.setSourceName(
1604 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1605 contents.add(info);
1606 }
1607
1608 mergeInfoLocked(pMergedInfo, &contents);
1609
1610 return true;
1611}
1612
1613
1614/*
1615 * Merge two vectors of FileInfo.
1616 *
1617 * The merged contents will be stuffed into *pMergedInfo.
1618 *
1619 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1620 * we use the newer "pContents" entry.
1621 */
1622void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1623 const SortedVector<AssetDir::FileInfo>* pContents)
1624{
1625 /*
1626 * Merge what we found in this directory with what we found in
1627 * other places.
1628 *
1629 * Two basic approaches:
1630 * (1) Create a new array that holds the unique values of the two
1631 * arrays.
1632 * (2) Take the elements from pContents and shove them into pMergedInfo.
1633 *
1634 * Because these are vectors of complex objects, moving elements around
1635 * inside the vector requires constructing new objects and allocating
1636 * storage for members. With approach #1, we're always adding to the
1637 * end, whereas with #2 we could be inserting multiple elements at the
1638 * front of the vector. Approach #1 requires a full copy of the
1639 * contents of pMergedInfo, but approach #2 requires the same copy for
1640 * every insertion at the front of pMergedInfo.
1641 *
1642 * (We should probably use a SortedVector interface that allows us to
1643 * just stuff items in, trusting us to maintain the sort order.)
1644 */
1645 SortedVector<AssetDir::FileInfo>* pNewSorted;
1646 int mergeMax, contMax;
1647 int mergeIdx, contIdx;
1648
1649 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1650 mergeMax = pMergedInfo->size();
1651 contMax = pContents->size();
1652 mergeIdx = contIdx = 0;
1653
1654 while (mergeIdx < mergeMax || contIdx < contMax) {
1655 if (mergeIdx == mergeMax) {
1656 /* hit end of "merge" list, copy rest of "contents" */
1657 pNewSorted->add(pContents->itemAt(contIdx));
1658 contIdx++;
1659 } else if (contIdx == contMax) {
1660 /* hit end of "cont" list, copy rest of "merge" */
1661 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1662 mergeIdx++;
1663 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1664 {
1665 /* items are identical, add newer and advance both indices */
1666 pNewSorted->add(pContents->itemAt(contIdx));
1667 mergeIdx++;
1668 contIdx++;
1669 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1670 {
1671 /* "merge" is lower, add that one */
1672 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1673 mergeIdx++;
1674 } else {
1675 /* "cont" is lower, add that one */
1676 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1677 pNewSorted->add(pContents->itemAt(contIdx));
1678 contIdx++;
1679 }
1680 }
1681
1682 /*
1683 * Overwrite the "merged" list with the new stuff.
1684 */
1685 *pMergedInfo = *pNewSorted;
1686 delete pNewSorted;
1687
1688#if 0 // for Vector, rather than SortedVector
1689 int i, j;
1690 for (i = pContents->size() -1; i >= 0; i--) {
1691 bool add = true;
1692
1693 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1694 /* case-sensitive comparisons, to behave like UNIX fs */
1695 if (strcmp(pContents->itemAt(i).mFileName,
1696 pMergedInfo->itemAt(j).mFileName) == 0)
1697 {
1698 /* match, don't add this entry */
1699 add = false;
1700 break;
1701 }
1702 }
1703
1704 if (add)
1705 pMergedInfo->add(pContents->itemAt(i));
1706 }
1707#endif
1708}
1709
1710
1711/*
1712 * Load all files into the file name cache. We want to do this across
1713 * all combinations of { appname, locale, vendor }, performing a recursive
1714 * directory traversal.
1715 *
1716 * This is not the most efficient data structure. Also, gathering the
1717 * information as we needed it (file-by-file or directory-by-directory)
1718 * would be faster. However, on the actual device, 99% of the files will
1719 * live in Zip archives, so this list will be very small. The trouble
1720 * is that we have to check the "loose" files first, so it's important
1721 * that we don't beat the filesystem silly looking for files that aren't
1722 * there.
1723 *
1724 * Note on thread safety: this is the only function that causes updates
1725 * to mCache, and anybody who tries to use it will call here if !mCacheValid,
1726 * so we need to employ a mutex here.
1727 */
1728void AssetManager::loadFileNameCacheLocked(void)
1729{
1730 assert(!mCacheValid);
1731 assert(mCache.size() == 0);
1732
1733#ifdef DO_TIMINGS // need to link against -lrt for this now
1734 DurationTimer timer;
1735 timer.start();
1736#endif
1737
1738 fncScanLocked(&mCache, "");
1739
1740#ifdef DO_TIMINGS
1741 timer.stop();
1742 ALOGD("Cache scan took %.3fms\n",
1743 timer.durationUsecs() / 1000.0);
1744#endif
1745
1746#if 0
1747 int i;
1748 printf("CACHED FILE LIST (%d entries):\n", mCache.size());
1749 for (i = 0; i < (int) mCache.size(); i++) {
1750 printf(" %d: (%d) '%s'\n", i,
1751 mCache.itemAt(i).getFileType(),
1752 (const char*) mCache.itemAt(i).getFileName());
1753 }
1754#endif
1755
1756 mCacheValid = true;
1757}
1758
1759/*
1760 * Scan up to 8 versions of the specified directory.
1761 */
1762void AssetManager::fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1763 const char* dirName)
1764{
1765 size_t i = mAssetPaths.size();
1766 while (i > 0) {
1767 i--;
1768 const asset_path& ap = mAssetPaths.itemAt(i);
1769 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, NULL, dirName);
1770 if (mLocale != NULL)
1771 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, NULL, dirName);
1772 if (mVendor != NULL)
1773 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, mVendor, dirName);
1774 if (mLocale != NULL && mVendor != NULL)
1775 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, mVendor, dirName);
1776 }
1777}
1778
1779/*
1780 * Recursively scan this directory and all subdirs.
1781 *
1782 * This is similar to scanAndMergeDir, but we don't remove the .EXCLUDE
1783 * files, and we prepend the extended partial path to the filenames.
1784 */
1785bool AssetManager::fncScanAndMergeDirLocked(
1786 SortedVector<AssetDir::FileInfo>* pMergedInfo,
1787 const asset_path& ap, const char* locale, const char* vendor,
1788 const char* dirName)
1789{
1790 SortedVector<AssetDir::FileInfo>* pContents;
1791 String8 partialPath;
1792 String8 fullPath;
1793
1794 // XXX This is broken -- the filename cache needs to hold the base
1795 // asset path separately from its filename.
1796
1797 partialPath = createPathNameLocked(ap, locale, vendor);
1798 if (dirName[0] != '\0') {
1799 partialPath.appendPath(dirName);
1800 }
1801
1802 fullPath = partialPath;
1803 pContents = scanDirLocked(fullPath);
1804 if (pContents == NULL) {
1805 return false; // directory did not exist
1806 }
1807
1808 /*
1809 * Scan all subdirectories of the current dir, merging what we find
1810 * into "pMergedInfo".
1811 */
1812 for (int i = 0; i < (int) pContents->size(); i++) {
1813 if (pContents->itemAt(i).getFileType() == kFileTypeDirectory) {
1814 String8 subdir(dirName);
1815 subdir.appendPath(pContents->itemAt(i).getFileName());
1816
1817 fncScanAndMergeDirLocked(pMergedInfo, ap, locale, vendor, subdir.string());
1818 }
1819 }
1820
1821 /*
1822 * To be consistent, we want entries for the root directory. If
1823 * we're the root, add one now.
1824 */
1825 if (dirName[0] == '\0') {
1826 AssetDir::FileInfo tmpInfo;
1827
1828 tmpInfo.set(String8(""), kFileTypeDirectory);
1829 tmpInfo.setSourceName(createPathNameLocked(ap, locale, vendor));
1830 pContents->add(tmpInfo);
1831 }
1832
1833 /*
1834 * We want to prepend the extended partial path to every entry in
1835 * "pContents". It's the same value for each entry, so this will
1836 * not change the sorting order of the vector contents.
1837 */
1838 for (int i = 0; i < (int) pContents->size(); i++) {
1839 const AssetDir::FileInfo& info = pContents->itemAt(i);
1840 pContents->editItemAt(i).setFileName(partialPath.appendPathCopy(info.getFileName()));
1841 }
1842
1843 mergeInfoLocked(pMergedInfo, pContents);
sean_lu7c57d232014-06-16 15:11:29 +08001844 delete pContents;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001845 return true;
1846}
1847
1848/*
1849 * Trash the cache.
1850 */
1851void AssetManager::purgeFileNameCacheLocked(void)
1852{
1853 mCacheValid = false;
1854 mCache.clear();
1855}
1856
1857/*
1858 * ===========================================================================
1859 * AssetManager::SharedZip
1860 * ===========================================================================
1861 */
1862
1863
1864Mutex AssetManager::SharedZip::gLock;
1865DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1866
1867AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1868 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1869 mResourceTableAsset(NULL), mResourceTable(NULL)
1870{
1871 //ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001872 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamath560566d2013-12-03 13:16:03 +00001873 mZipFile = ZipFileRO::open(mPath.string());
1874 if (mZipFile == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001875 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001876 }
1877}
1878
Mårten Kongstad48d22322014-01-31 14:43:27 +01001879sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1880 bool createIfNotPresent)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001881{
1882 AutoMutex _l(gLock);
1883 time_t modWhen = getFileModDate(path);
1884 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1885 if (zip != NULL && zip->mModWhen == modWhen) {
1886 return zip;
1887 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001888 if (zip == NULL && !createIfNotPresent) {
1889 return NULL;
1890 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001891 zip = new SharedZip(path, modWhen);
1892 gOpen.add(path, zip);
1893 return zip;
1894
1895}
1896
1897ZipFileRO* AssetManager::SharedZip::getZip()
1898{
1899 return mZipFile;
1900}
1901
1902Asset* AssetManager::SharedZip::getResourceTableAsset()
1903{
1904 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1905 return mResourceTableAsset;
1906}
1907
1908Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1909{
1910 {
1911 AutoMutex _l(gLock);
1912 if (mResourceTableAsset == NULL) {
1913 mResourceTableAsset = asset;
1914 // This is not thread safe the first time it is called, so
1915 // do it here with the global lock held.
1916 asset->getBuffer(true);
1917 return asset;
1918 }
1919 }
1920 delete asset;
1921 return mResourceTableAsset;
1922}
1923
1924ResTable* AssetManager::SharedZip::getResourceTable()
1925{
1926 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1927 return mResourceTable;
1928}
1929
1930ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1931{
1932 {
1933 AutoMutex _l(gLock);
1934 if (mResourceTable == NULL) {
1935 mResourceTable = res;
1936 return res;
1937 }
1938 }
1939 delete res;
1940 return mResourceTable;
1941}
1942
1943bool AssetManager::SharedZip::isUpToDate()
1944{
1945 time_t modWhen = getFileModDate(mPath.string());
1946 return mModWhen == modWhen;
1947}
1948
Mårten Kongstad48d22322014-01-31 14:43:27 +01001949void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1950{
1951 mOverlays.add(ap);
1952}
1953
1954bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1955{
1956 if (idx >= mOverlays.size()) {
1957 return false;
1958 }
1959 *out = mOverlays[idx];
1960 return true;
1961}
1962
Adam Lesinski16c4d152014-01-24 13:27:13 -08001963AssetManager::SharedZip::~SharedZip()
1964{
1965 //ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1966 if (mResourceTable != NULL) {
1967 delete mResourceTable;
1968 }
1969 if (mResourceTableAsset != NULL) {
1970 delete mResourceTableAsset;
1971 }
1972 if (mZipFile != NULL) {
1973 delete mZipFile;
1974 ALOGV("Closed '%s'\n", mPath.string());
1975 }
1976}
1977
1978/*
1979 * ===========================================================================
1980 * AssetManager::ZipSet
1981 * ===========================================================================
1982 */
1983
1984/*
1985 * Constructor.
1986 */
1987AssetManager::ZipSet::ZipSet(void)
1988{
1989}
1990
1991/*
1992 * Destructor. Close any open archives.
1993 */
1994AssetManager::ZipSet::~ZipSet(void)
1995{
1996 size_t N = mZipFile.size();
1997 for (size_t i = 0; i < N; i++)
1998 closeZip(i);
1999}
2000
2001/*
2002 * Close a Zip file and reset the entry.
2003 */
2004void AssetManager::ZipSet::closeZip(int idx)
2005{
2006 mZipFile.editItemAt(idx) = NULL;
2007}
2008
2009
2010/*
2011 * Retrieve the appropriate Zip file from the set.
2012 */
2013ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
2014{
2015 int idx = getIndex(path);
2016 sp<SharedZip> zip = mZipFile[idx];
2017 if (zip == NULL) {
2018 zip = SharedZip::get(path);
2019 mZipFile.editItemAt(idx) = zip;
2020 }
2021 return zip->getZip();
2022}
2023
2024Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
2025{
2026 int idx = getIndex(path);
2027 sp<SharedZip> zip = mZipFile[idx];
2028 if (zip == NULL) {
2029 zip = SharedZip::get(path);
2030 mZipFile.editItemAt(idx) = zip;
2031 }
2032 return zip->getResourceTableAsset();
2033}
2034
2035Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
2036 Asset* asset)
2037{
2038 int idx = getIndex(path);
2039 sp<SharedZip> zip = mZipFile[idx];
2040 // doesn't make sense to call before previously accessing.
2041 return zip->setResourceTableAsset(asset);
2042}
2043
2044ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
2045{
2046 int idx = getIndex(path);
2047 sp<SharedZip> zip = mZipFile[idx];
2048 if (zip == NULL) {
2049 zip = SharedZip::get(path);
2050 mZipFile.editItemAt(idx) = zip;
2051 }
2052 return zip->getResourceTable();
2053}
2054
2055ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
2056 ResTable* res)
2057{
2058 int idx = getIndex(path);
2059 sp<SharedZip> zip = mZipFile[idx];
2060 // doesn't make sense to call before previously accessing.
2061 return zip->setResourceTable(res);
2062}
2063
2064/*
2065 * Generate the partial pathname for the specified archive. The caller
2066 * gets to prepend the asset root directory.
2067 *
2068 * Returns something like "common/en-US-noogle.jar".
2069 */
2070/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
2071{
2072 return String8(zipPath);
2073}
2074
2075bool AssetManager::ZipSet::isUpToDate()
2076{
2077 const size_t N = mZipFile.size();
2078 for (size_t i=0; i<N; i++) {
2079 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
2080 return false;
2081 }
2082 }
2083 return true;
2084}
2085
Mårten Kongstad48d22322014-01-31 14:43:27 +01002086void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
2087{
2088 int idx = getIndex(path);
2089 sp<SharedZip> zip = mZipFile[idx];
2090 zip->addOverlay(overlay);
2091}
2092
2093bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
2094{
2095 sp<SharedZip> zip = SharedZip::get(path, false);
2096 if (zip == NULL) {
2097 return false;
2098 }
2099 return zip->getOverlay(idx, out);
2100}
2101
Adam Lesinski16c4d152014-01-24 13:27:13 -08002102/*
2103 * Compute the zip file's index.
2104 *
2105 * "appName", "locale", and "vendor" should be set to NULL to indicate the
2106 * default directory.
2107 */
2108int AssetManager::ZipSet::getIndex(const String8& zip) const
2109{
2110 const size_t N = mZipPath.size();
2111 for (size_t i=0; i<N; i++) {
2112 if (mZipPath[i] == zip) {
2113 return i;
2114 }
2115 }
2116
2117 mZipPath.add(zip);
2118 mZipFile.add(NULL);
2119
2120 return mZipPath.size()-1;
2121}