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