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