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