blob: 7a103430feb5f0e773c89cf4fb85520a35379d06 [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 Wallgrenf12af5e2015-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 Wallgrenf12af5e2015-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);
neo.chae6a742a32016-11-01 00:02:38 +0900807 delete oidmap;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100808 }
809 }
Martin Wallgrenf12af5e2015-08-11 15:10:31 +0200810
811#ifndef _WIN32
812 TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_UN));
813#endif
Mårten Kongstad48d22322014-01-31 14:43:27 +0100814 fclose(fin);
815}
816
Adam Lesinski16c4d152014-01-24 13:27:13 -0800817const ResTable& AssetManager::getResources(bool required) const
818{
819 const ResTable* rt = getResTable(required);
820 return *rt;
821}
822
823bool AssetManager::isUpToDate()
824{
825 AutoMutex _l(mLock);
826 return mZipSet.isUpToDate();
827}
828
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800829void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800830{
831 ResTable* res = mResources;
832 if (res != NULL) {
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800833 res->getLocales(locales, includeSystemLocales);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800834 }
Narayan Kamathe4345db2014-06-26 16:01:28 +0100835
836 const size_t numLocales = locales->size();
837 for (size_t i = 0; i < numLocales; ++i) {
838 const String8& localeStr = locales->itemAt(i);
839 if (localeStr.find(kTlPrefix) == 0) {
840 String8 replaced("fil");
841 replaced += (localeStr.string() + kTlPrefixLen);
842 locales->editItemAt(i) = replaced;
843 }
844 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800845}
846
847/*
848 * Open a non-asset file as if it were an asset, searching for it in the
849 * specified app.
850 *
851 * Pass in a NULL values for "appName" if the common app directory should
852 * be used.
853 */
854Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
855 const asset_path& ap)
856{
857 Asset* pAsset = NULL;
858
859 /* look at the filesystem on disk */
860 if (ap.type == kFileTypeDirectory) {
861 String8 path(ap.path);
862 path.appendPath(fileName);
863
864 pAsset = openAssetFromFileLocked(path, mode);
865
866 if (pAsset == NULL) {
867 /* try again, this time with ".gz" */
868 path.append(".gz");
869 pAsset = openAssetFromFileLocked(path, mode);
870 }
871
872 if (pAsset != NULL) {
873 //printf("FOUND NA '%s' on disk\n", fileName);
874 pAsset->setAssetSource(path);
875 }
876
877 /* look inside the zip file */
878 } else {
879 String8 path(fileName);
880
881 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +0000882 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800883 if (pZip != NULL) {
884 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000885 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800886 if (entry != NULL) {
887 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
888 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000889 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800890 }
891 }
892
893 if (pAsset != NULL) {
894 /* create a "source" name, for debug/display */
895 pAsset->setAssetSource(
896 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
897 String8(fileName)));
898 }
899 }
900
901 return pAsset;
902}
903
904/*
905 * Open an asset, searching for it in the directory hierarchy for the
906 * specified app.
907 *
908 * Pass in a NULL values for "appName" if the common app directory should
909 * be used.
910 */
911Asset* AssetManager::openInPathLocked(const char* fileName, AccessMode mode,
912 const asset_path& ap)
913{
914 Asset* pAsset = NULL;
915
916 /*
917 * Try various combinations of locale and vendor.
918 */
919 if (mLocale != NULL && mVendor != NULL)
920 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, mVendor);
921 if (pAsset == NULL && mVendor != NULL)
922 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, mVendor);
923 if (pAsset == NULL && mLocale != NULL)
924 pAsset = openInLocaleVendorLocked(fileName, mode, ap, mLocale, NULL);
925 if (pAsset == NULL)
926 pAsset = openInLocaleVendorLocked(fileName, mode, ap, NULL, NULL);
927
928 return pAsset;
929}
930
931/*
932 * Open an asset, searching for it in the directory hierarchy for the
933 * specified locale and vendor.
934 *
935 * We also search in "app.jar".
936 *
937 * Pass in NULL values for "appName", "locale", and "vendor" if the
938 * defaults should be used.
939 */
940Asset* AssetManager::openInLocaleVendorLocked(const char* fileName, AccessMode mode,
941 const asset_path& ap, const char* locale, const char* vendor)
942{
943 Asset* pAsset = NULL;
944
945 if (ap.type == kFileTypeDirectory) {
946 if (mCacheMode == CACHE_OFF) {
947 /* look at the filesystem on disk */
948 String8 path(createPathNameLocked(ap, locale, vendor));
949 path.appendPath(fileName);
950
951 String8 excludeName(path);
952 excludeName.append(kExcludeExtension);
953 if (::getFileType(excludeName.string()) != kFileTypeNonexistent) {
954 /* say no more */
955 //printf("+++ excluding '%s'\n", (const char*) excludeName);
956 return kExcludedAsset;
957 }
958
959 pAsset = openAssetFromFileLocked(path, mode);
960
961 if (pAsset == NULL) {
962 /* try again, this time with ".gz" */
963 path.append(".gz");
964 pAsset = openAssetFromFileLocked(path, mode);
965 }
966
967 if (pAsset != NULL)
968 pAsset->setAssetSource(path);
969 } else {
970 /* find in cache */
971 String8 path(createPathNameLocked(ap, locale, vendor));
972 path.appendPath(fileName);
973
974 AssetDir::FileInfo tmpInfo;
975 bool found = false;
976
977 String8 excludeName(path);
978 excludeName.append(kExcludeExtension);
979
980 if (mCache.indexOf(excludeName) != NAME_NOT_FOUND) {
981 /* go no farther */
982 //printf("+++ Excluding '%s'\n", (const char*) excludeName);
983 return kExcludedAsset;
984 }
985
986 /*
987 * File compression extensions (".gz") don't get stored in the
988 * name cache, so we have to try both here.
989 */
990 if (mCache.indexOf(path) != NAME_NOT_FOUND) {
991 found = true;
992 pAsset = openAssetFromFileLocked(path, mode);
993 if (pAsset == NULL) {
994 /* try again, this time with ".gz" */
995 path.append(".gz");
996 pAsset = openAssetFromFileLocked(path, mode);
997 }
998 }
999
1000 if (pAsset != NULL)
1001 pAsset->setAssetSource(path);
1002
1003 /*
1004 * Don't continue the search into the Zip files. Our cached info
1005 * said it was a file on disk; to be consistent with openDir()
1006 * we want to return the loose asset. If the cached file gets
1007 * removed, we fail.
1008 *
1009 * The alternative is to update our cache when files get deleted,
1010 * or make some sort of "best effort" promise, but for now I'm
1011 * taking the hard line.
1012 */
1013 if (found) {
1014 if (pAsset == NULL)
1015 ALOGD("Expected file not found: '%s'\n", path.string());
1016 return pAsset;
1017 }
1018 }
1019 }
1020
1021 /*
1022 * Either it wasn't found on disk or on the cached view of the disk.
1023 * Dig through the currently-opened set of Zip files. If caching
1024 * is disabled, the Zip file may get reopened.
1025 */
1026 if (pAsset == NULL && ap.type == kFileTypeRegular) {
1027 String8 path;
1028
1029 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1030 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1031 path.appendPath(fileName);
1032
1033 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +00001034 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001035 if (pZip != NULL) {
1036 //printf("GOT zip, checking '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +00001037 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001038 if (entry != NULL) {
1039 //printf("FOUND in Zip file for %s/%s-%s\n",
1040 // appName, locale, vendor);
1041 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +00001042 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001043 }
1044 }
1045
1046 if (pAsset != NULL) {
1047 /* create a "source" name, for debug/display */
1048 pAsset->setAssetSource(createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()),
1049 String8(""), String8(fileName)));
1050 }
1051 }
1052
1053 return pAsset;
1054}
1055
1056/*
1057 * Create a "source name" for a file from a Zip archive.
1058 */
1059String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
1060 const String8& dirName, const String8& fileName)
1061{
1062 String8 sourceName("zip:");
1063 sourceName.append(zipFileName);
1064 sourceName.append(":");
1065 if (dirName.length() > 0) {
1066 sourceName.appendPath(dirName);
1067 }
1068 sourceName.appendPath(fileName);
1069 return sourceName;
1070}
1071
1072/*
1073 * Create a path to a loose asset (asset-base/app/locale/vendor).
1074 */
1075String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
1076 const char* vendor)
1077{
1078 String8 path(ap.path);
1079 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
1080 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
1081 return path;
1082}
1083
1084/*
1085 * Create a path to a loose asset (asset-base/app/rootDir).
1086 */
1087String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
1088{
1089 String8 path(ap.path);
1090 if (rootDir != NULL) path.appendPath(rootDir);
1091 return path;
1092}
1093
1094/*
1095 * Return a pointer to one of our open Zip archives. Returns NULL if no
1096 * matching Zip file exists.
1097 *
1098 * Right now we have 2 possible Zip files (1 each in app/"common").
1099 *
1100 * If caching is set to CACHE_OFF, to get the expected behavior we
1101 * need to reopen the Zip file on every request. That would be silly
1102 * and expensive, so instead we just check the file modification date.
1103 *
1104 * Pass in NULL values for "appName", "locale", and "vendor" if the
1105 * generics should be used.
1106 */
1107ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
1108{
1109 ALOGV("getZipFileLocked() in %p\n", this);
1110
1111 return mZipSet.getZip(ap.path);
1112}
1113
1114/*
1115 * Try to open an asset from a file on disk.
1116 *
1117 * If the file is compressed with gzip, we seek to the start of the
1118 * deflated data and pass that in (just like we would for a Zip archive).
1119 *
1120 * For uncompressed data, we may already have an mmap()ed version sitting
1121 * around. If so, we want to hand that to the Asset instead.
1122 *
1123 * This returns NULL if the file doesn't exist, couldn't be opened, or
1124 * claims to be a ".gz" but isn't.
1125 */
1126Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
1127 AccessMode mode)
1128{
1129 Asset* pAsset = NULL;
1130
1131 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
1132 //printf("TRYING '%s'\n", (const char*) pathName);
1133 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
1134 } else {
1135 //printf("TRYING '%s'\n", (const char*) pathName);
1136 pAsset = Asset::createFromFile(pathName.string(), mode);
1137 }
1138
1139 return pAsset;
1140}
1141
1142/*
1143 * Given an entry in a Zip archive, create a new Asset object.
1144 *
1145 * If the entry is uncompressed, we may want to create or share a
1146 * slice of shared memory.
1147 */
1148Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
1149 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
1150{
1151 Asset* pAsset = NULL;
1152
1153 // TODO: look for previously-created shared memory slice?
Narayan Kamath407753c2015-06-16 12:02:57 +01001154 uint16_t method;
1155 uint32_t uncompressedLen;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001156
1157 //printf("USING Zip '%s'\n", pEntry->getFileName());
1158
Adam Lesinski16c4d152014-01-24 13:27:13 -08001159 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
1160 NULL, NULL))
1161 {
1162 ALOGW("getEntryInfo failed\n");
1163 return NULL;
1164 }
1165
1166 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
1167 if (dataMap == NULL) {
1168 ALOGW("create map from entry failed\n");
1169 return NULL;
1170 }
1171
1172 if (method == ZipFileRO::kCompressStored) {
1173 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
1174 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
1175 dataMap->getFileName(), mode, pAsset);
1176 } else {
Narayan Kamath407753c2015-06-16 12:02:57 +01001177 pAsset = Asset::createFromCompressedMap(dataMap,
1178 static_cast<size_t>(uncompressedLen), mode);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001179 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
1180 dataMap->getFileName(), mode, pAsset);
1181 }
1182 if (pAsset == NULL) {
1183 /* unexpected */
1184 ALOGW("create from segment failed\n");
1185 }
1186
1187 return pAsset;
1188}
1189
1190
1191
1192/*
1193 * Open a directory in the asset namespace.
1194 *
1195 * An "asset directory" is simply the combination of all files in all
1196 * locations, with ".gz" stripped for loose files. With app, locale, and
1197 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1198 *
1199 * Pass in "" for the root dir.
1200 */
1201AssetDir* AssetManager::openDir(const char* dirName)
1202{
1203 AutoMutex _l(mLock);
1204
1205 AssetDir* pDir = NULL;
1206 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1207
1208 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1209 assert(dirName != NULL);
1210
1211 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1212
1213 if (mCacheMode != CACHE_OFF && !mCacheValid)
1214 loadFileNameCacheLocked();
1215
1216 pDir = new AssetDir;
1217
1218 /*
1219 * Scan the various directories, merging what we find into a single
1220 * vector. We want to scan them in reverse priority order so that
1221 * the ".EXCLUDE" processing works correctly. Also, if we decide we
1222 * want to remember where the file is coming from, we'll get the right
1223 * version.
1224 *
1225 * We start with Zip archives, then do loose files.
1226 */
1227 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1228
1229 size_t i = mAssetPaths.size();
1230 while (i > 0) {
1231 i--;
1232 const asset_path& ap = mAssetPaths.itemAt(i);
1233 if (ap.type == kFileTypeRegular) {
1234 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1235 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1236 } else {
1237 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1238 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
1239 }
1240 }
1241
1242#if 0
1243 printf("FILE LIST:\n");
1244 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1245 printf(" %d: (%d) '%s'\n", i,
1246 pMergedInfo->itemAt(i).getFileType(),
1247 (const char*) pMergedInfo->itemAt(i).getFileName());
1248 }
1249#endif
1250
1251 pDir->setFileList(pMergedInfo);
1252 return pDir;
1253}
1254
1255/*
1256 * Open a directory in the non-asset namespace.
1257 *
1258 * An "asset directory" is simply the combination of all files in all
1259 * locations, with ".gz" stripped for loose files. With app, locale, and
1260 * vendor defined, we have 8 directories and 2 Zip archives to scan.
1261 *
1262 * Pass in "" for the root dir.
1263 */
Narayan Kamatha0c62602014-01-24 13:51:51 +00001264AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001265{
1266 AutoMutex _l(mLock);
1267
1268 AssetDir* pDir = NULL;
1269 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
1270
1271 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
1272 assert(dirName != NULL);
1273
1274 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
1275
1276 if (mCacheMode != CACHE_OFF && !mCacheValid)
1277 loadFileNameCacheLocked();
1278
1279 pDir = new AssetDir;
1280
1281 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
1282
Narayan Kamatha0c62602014-01-24 13:51:51 +00001283 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001284
1285 if (which < mAssetPaths.size()) {
1286 const asset_path& ap = mAssetPaths.itemAt(which);
1287 if (ap.type == kFileTypeRegular) {
1288 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1289 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
1290 } else {
1291 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1292 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
1293 }
1294 }
1295
1296#if 0
1297 printf("FILE LIST:\n");
1298 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1299 printf(" %d: (%d) '%s'\n", i,
1300 pMergedInfo->itemAt(i).getFileType(),
1301 (const char*) pMergedInfo->itemAt(i).getFileName());
1302 }
1303#endif
1304
1305 pDir->setFileList(pMergedInfo);
1306 return pDir;
1307}
1308
1309/*
1310 * Scan the contents of the specified directory and merge them into the
1311 * "pMergedInfo" vector, removing previous entries if we find "exclude"
1312 * directives.
1313 *
1314 * Returns "false" if we found nothing to contribute.
1315 */
1316bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1317 const asset_path& ap, const char* rootDir, const char* dirName)
1318{
1319 SortedVector<AssetDir::FileInfo>* pContents;
1320 String8 path;
1321
1322 assert(pMergedInfo != NULL);
1323
1324 //printf("scanAndMergeDir: %s %s %s %s\n", appName, locale, vendor,dirName);
1325
1326 if (mCacheValid) {
1327 int i, start, count;
1328
1329 pContents = new SortedVector<AssetDir::FileInfo>;
1330
1331 /*
1332 * Get the basic partial path and find it in the cache. That's
1333 * the start point for the search.
1334 */
1335 path = createPathNameLocked(ap, rootDir);
1336 if (dirName[0] != '\0')
1337 path.appendPath(dirName);
1338
1339 start = mCache.indexOf(path);
1340 if (start == NAME_NOT_FOUND) {
1341 //printf("+++ not found in cache: dir '%s'\n", (const char*) path);
1342 delete pContents;
1343 return false;
1344 }
1345
1346 /*
1347 * The match string looks like "common/default/default/foo/bar/".
1348 * The '/' on the end ensures that we don't match on the directory
1349 * itself or on ".../foo/barfy/".
1350 */
1351 path.append("/");
1352
1353 count = mCache.size();
1354
1355 /*
1356 * Pick out the stuff in the current dir by examining the pathname.
1357 * It needs to match the partial pathname prefix, and not have a '/'
1358 * (fssep) anywhere after the prefix.
1359 */
1360 for (i = start+1; i < count; i++) {
1361 if (mCache[i].getFileName().length() > path.length() &&
1362 strncmp(mCache[i].getFileName().string(), path.string(), path.length()) == 0)
1363 {
1364 const char* name = mCache[i].getFileName().string();
1365 // XXX THIS IS BROKEN! Looks like we need to store the full
1366 // path prefix separately from the file path.
1367 if (strchr(name + path.length(), '/') == NULL) {
1368 /* grab it, reducing path to just the filename component */
1369 AssetDir::FileInfo tmp = mCache[i];
1370 tmp.setFileName(tmp.getFileName().getPathLeaf());
1371 pContents->add(tmp);
1372 }
1373 } else {
1374 /* no longer in the dir or its subdirs */
1375 break;
1376 }
1377
1378 }
1379 } else {
1380 path = createPathNameLocked(ap, rootDir);
1381 if (dirName[0] != '\0')
1382 path.appendPath(dirName);
1383 pContents = scanDirLocked(path);
1384 if (pContents == NULL)
1385 return false;
1386 }
1387
1388 // if we wanted to do an incremental cache fill, we would do it here
1389
1390 /*
1391 * Process "exclude" directives. If we find a filename that ends with
1392 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1393 * remove it if we find it. We also delete the "exclude" entry.
1394 */
1395 int i, count, exclExtLen;
1396
1397 count = pContents->size();
1398 exclExtLen = strlen(kExcludeExtension);
1399 for (i = 0; i < count; i++) {
1400 const char* name;
1401 int nameLen;
1402
1403 name = pContents->itemAt(i).getFileName().string();
1404 nameLen = strlen(name);
1405 if (nameLen > exclExtLen &&
1406 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1407 {
1408 String8 match(name, nameLen - exclExtLen);
1409 int matchIdx;
1410
1411 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1412 if (matchIdx > 0) {
1413 ALOGV("Excluding '%s' [%s]\n",
1414 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1415 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1416 pMergedInfo->removeAt(matchIdx);
1417 } else {
1418 //printf("+++ no match on '%s'\n", (const char*) match);
1419 }
1420
1421 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1422 pContents->removeAt(i);
1423 i--; // adjust "for" loop
1424 count--; // and loop limit
1425 }
1426 }
1427
1428 mergeInfoLocked(pMergedInfo, pContents);
1429
1430 delete pContents;
1431
1432 return true;
1433}
1434
1435/*
1436 * Scan the contents of the specified directory, and stuff what we find
1437 * into a newly-allocated vector.
1438 *
1439 * Files ending in ".gz" will have their extensions removed.
1440 *
1441 * We should probably think about skipping files with "illegal" names,
1442 * e.g. illegal characters (/\:) or excessive length.
1443 *
1444 * Returns NULL if the specified directory doesn't exist.
1445 */
1446SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1447{
1448 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1449 DIR* dir;
1450 struct dirent* entry;
1451 FileType fileType;
1452
1453 ALOGV("Scanning dir '%s'\n", path.string());
1454
1455 dir = opendir(path.string());
1456 if (dir == NULL)
1457 return NULL;
1458
1459 pContents = new SortedVector<AssetDir::FileInfo>;
1460
1461 while (1) {
1462 entry = readdir(dir);
1463 if (entry == NULL)
1464 break;
1465
1466 if (strcmp(entry->d_name, ".") == 0 ||
1467 strcmp(entry->d_name, "..") == 0)
1468 continue;
1469
1470#ifdef _DIRENT_HAVE_D_TYPE
1471 if (entry->d_type == DT_REG)
1472 fileType = kFileTypeRegular;
1473 else if (entry->d_type == DT_DIR)
1474 fileType = kFileTypeDirectory;
1475 else
1476 fileType = kFileTypeUnknown;
1477#else
1478 // stat the file
1479 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1480#endif
1481
1482 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1483 continue;
1484
1485 AssetDir::FileInfo info;
1486 info.set(String8(entry->d_name), fileType);
1487 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1488 info.setFileName(info.getFileName().getBasePath());
1489 info.setSourceName(path.appendPathCopy(info.getFileName()));
1490 pContents->add(info);
1491 }
1492
1493 closedir(dir);
1494 return pContents;
1495}
1496
1497/*
1498 * Scan the contents out of the specified Zip archive, and merge what we
1499 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1500 * we return immediately.
1501 *
1502 * Returns "false" if we found nothing to contribute.
1503 */
1504bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1505 const asset_path& ap, const char* rootDir, const char* baseDirName)
1506{
1507 ZipFileRO* pZip;
1508 Vector<String8> dirs;
1509 AssetDir::FileInfo info;
1510 SortedVector<AssetDir::FileInfo> contents;
1511 String8 sourceName, zipName, dirName;
1512
1513 pZip = mZipSet.getZip(ap.path);
1514 if (pZip == NULL) {
1515 ALOGW("Failure opening zip %s\n", ap.path.string());
1516 return false;
1517 }
1518
1519 zipName = ZipSet::getPathName(ap.path.string());
1520
1521 /* convert "sounds" to "rootDir/sounds" */
1522 if (rootDir != NULL) dirName = rootDir;
1523 dirName.appendPath(baseDirName);
1524
1525 /*
1526 * Scan through the list of files, looking for a match. The files in
1527 * the Zip table of contents are not in sorted order, so we have to
1528 * process the entire list. We're looking for a string that begins
1529 * with the characters in "dirName", is followed by a '/', and has no
1530 * subsequent '/' in the stuff that follows.
1531 *
1532 * What makes this especially fun is that directories are not stored
1533 * explicitly in Zip archives, so we have to infer them from context.
1534 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1535 * to insert a directory called "sounds" into the list. We store
1536 * these in temporary vector so that we only return each one once.
1537 *
1538 * Name comparisons are case-sensitive to match UNIX filesystem
1539 * semantics.
1540 */
1541 int dirNameLen = dirName.length();
Narayan Kamath560566d2013-12-03 13:16:03 +00001542 void *iterationCookie;
Yusuke Sato05f648e2015-08-03 16:21:10 -07001543 if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
Narayan Kamath560566d2013-12-03 13:16:03 +00001544 ALOGW("ZipFileRO::startIteration returned false");
1545 return false;
1546 }
1547
1548 ZipEntryRO entry;
1549 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001550 char nameBuf[256];
1551
Adam Lesinski16c4d152014-01-24 13:27:13 -08001552 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1553 // TODO: fix this if we expect to have long names
1554 ALOGE("ARGH: name too long?\n");
1555 continue;
1556 }
1557 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
Yusuke Sato05f648e2015-08-03 16:21:10 -07001558 if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
Adam Lesinski16c4d152014-01-24 13:27:13 -08001559 {
1560 const char* cp;
1561 const char* nextSlash;
1562
1563 cp = nameBuf + dirNameLen;
1564 if (dirNameLen != 0)
1565 cp++; // advance past the '/'
1566
1567 nextSlash = strchr(cp, '/');
1568//xxx this may break if there are bare directory entries
1569 if (nextSlash == NULL) {
1570 /* this is a file in the requested directory */
1571
1572 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1573
1574 info.setSourceName(
1575 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1576
1577 contents.add(info);
1578 //printf("FOUND: file '%s'\n", info.getFileName().string());
1579 } else {
1580 /* this is a subdir; add it if we don't already have it*/
1581 String8 subdirName(cp, nextSlash - cp);
1582 size_t j;
1583 size_t N = dirs.size();
1584
1585 for (j = 0; j < N; j++) {
1586 if (subdirName == dirs[j]) {
1587 break;
1588 }
1589 }
1590 if (j == N) {
1591 dirs.add(subdirName);
1592 }
1593
1594 //printf("FOUND: dir '%s'\n", subdirName.string());
1595 }
1596 }
1597 }
1598
Narayan Kamath560566d2013-12-03 13:16:03 +00001599 pZip->endIteration(iterationCookie);
1600
Adam Lesinski16c4d152014-01-24 13:27:13 -08001601 /*
1602 * Add the set of unique directories.
1603 */
1604 for (int i = 0; i < (int) dirs.size(); i++) {
1605 info.set(dirs[i], kFileTypeDirectory);
1606 info.setSourceName(
1607 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1608 contents.add(info);
1609 }
1610
1611 mergeInfoLocked(pMergedInfo, &contents);
1612
1613 return true;
1614}
1615
1616
1617/*
1618 * Merge two vectors of FileInfo.
1619 *
1620 * The merged contents will be stuffed into *pMergedInfo.
1621 *
1622 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1623 * we use the newer "pContents" entry.
1624 */
1625void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1626 const SortedVector<AssetDir::FileInfo>* pContents)
1627{
1628 /*
1629 * Merge what we found in this directory with what we found in
1630 * other places.
1631 *
1632 * Two basic approaches:
1633 * (1) Create a new array that holds the unique values of the two
1634 * arrays.
1635 * (2) Take the elements from pContents and shove them into pMergedInfo.
1636 *
1637 * Because these are vectors of complex objects, moving elements around
1638 * inside the vector requires constructing new objects and allocating
1639 * storage for members. With approach #1, we're always adding to the
1640 * end, whereas with #2 we could be inserting multiple elements at the
1641 * front of the vector. Approach #1 requires a full copy of the
1642 * contents of pMergedInfo, but approach #2 requires the same copy for
1643 * every insertion at the front of pMergedInfo.
1644 *
1645 * (We should probably use a SortedVector interface that allows us to
1646 * just stuff items in, trusting us to maintain the sort order.)
1647 */
1648 SortedVector<AssetDir::FileInfo>* pNewSorted;
1649 int mergeMax, contMax;
1650 int mergeIdx, contIdx;
1651
1652 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1653 mergeMax = pMergedInfo->size();
1654 contMax = pContents->size();
1655 mergeIdx = contIdx = 0;
1656
1657 while (mergeIdx < mergeMax || contIdx < contMax) {
1658 if (mergeIdx == mergeMax) {
1659 /* hit end of "merge" list, copy rest of "contents" */
1660 pNewSorted->add(pContents->itemAt(contIdx));
1661 contIdx++;
1662 } else if (contIdx == contMax) {
1663 /* hit end of "cont" list, copy rest of "merge" */
1664 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1665 mergeIdx++;
1666 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1667 {
1668 /* items are identical, add newer and advance both indices */
1669 pNewSorted->add(pContents->itemAt(contIdx));
1670 mergeIdx++;
1671 contIdx++;
1672 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1673 {
1674 /* "merge" is lower, add that one */
1675 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1676 mergeIdx++;
1677 } else {
1678 /* "cont" is lower, add that one */
1679 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1680 pNewSorted->add(pContents->itemAt(contIdx));
1681 contIdx++;
1682 }
1683 }
1684
1685 /*
1686 * Overwrite the "merged" list with the new stuff.
1687 */
1688 *pMergedInfo = *pNewSorted;
1689 delete pNewSorted;
1690
1691#if 0 // for Vector, rather than SortedVector
1692 int i, j;
1693 for (i = pContents->size() -1; i >= 0; i--) {
1694 bool add = true;
1695
1696 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1697 /* case-sensitive comparisons, to behave like UNIX fs */
1698 if (strcmp(pContents->itemAt(i).mFileName,
1699 pMergedInfo->itemAt(j).mFileName) == 0)
1700 {
1701 /* match, don't add this entry */
1702 add = false;
1703 break;
1704 }
1705 }
1706
1707 if (add)
1708 pMergedInfo->add(pContents->itemAt(i));
1709 }
1710#endif
1711}
1712
1713
1714/*
1715 * Load all files into the file name cache. We want to do this across
1716 * all combinations of { appname, locale, vendor }, performing a recursive
1717 * directory traversal.
1718 *
1719 * This is not the most efficient data structure. Also, gathering the
1720 * information as we needed it (file-by-file or directory-by-directory)
1721 * would be faster. However, on the actual device, 99% of the files will
1722 * live in Zip archives, so this list will be very small. The trouble
1723 * is that we have to check the "loose" files first, so it's important
1724 * that we don't beat the filesystem silly looking for files that aren't
1725 * there.
1726 *
1727 * Note on thread safety: this is the only function that causes updates
1728 * to mCache, and anybody who tries to use it will call here if !mCacheValid,
1729 * so we need to employ a mutex here.
1730 */
1731void AssetManager::loadFileNameCacheLocked(void)
1732{
1733 assert(!mCacheValid);
1734 assert(mCache.size() == 0);
1735
1736#ifdef DO_TIMINGS // need to link against -lrt for this now
1737 DurationTimer timer;
1738 timer.start();
1739#endif
1740
1741 fncScanLocked(&mCache, "");
1742
1743#ifdef DO_TIMINGS
1744 timer.stop();
1745 ALOGD("Cache scan took %.3fms\n",
1746 timer.durationUsecs() / 1000.0);
1747#endif
1748
1749#if 0
1750 int i;
1751 printf("CACHED FILE LIST (%d entries):\n", mCache.size());
1752 for (i = 0; i < (int) mCache.size(); i++) {
1753 printf(" %d: (%d) '%s'\n", i,
1754 mCache.itemAt(i).getFileType(),
1755 (const char*) mCache.itemAt(i).getFileName());
1756 }
1757#endif
1758
1759 mCacheValid = true;
1760}
1761
1762/*
1763 * Scan up to 8 versions of the specified directory.
1764 */
1765void AssetManager::fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1766 const char* dirName)
1767{
1768 size_t i = mAssetPaths.size();
1769 while (i > 0) {
1770 i--;
1771 const asset_path& ap = mAssetPaths.itemAt(i);
1772 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, NULL, dirName);
1773 if (mLocale != NULL)
1774 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, NULL, dirName);
1775 if (mVendor != NULL)
1776 fncScanAndMergeDirLocked(pMergedInfo, ap, NULL, mVendor, dirName);
1777 if (mLocale != NULL && mVendor != NULL)
1778 fncScanAndMergeDirLocked(pMergedInfo, ap, mLocale, mVendor, dirName);
1779 }
1780}
1781
1782/*
1783 * Recursively scan this directory and all subdirs.
1784 *
1785 * This is similar to scanAndMergeDir, but we don't remove the .EXCLUDE
1786 * files, and we prepend the extended partial path to the filenames.
1787 */
1788bool AssetManager::fncScanAndMergeDirLocked(
1789 SortedVector<AssetDir::FileInfo>* pMergedInfo,
1790 const asset_path& ap, const char* locale, const char* vendor,
1791 const char* dirName)
1792{
1793 SortedVector<AssetDir::FileInfo>* pContents;
1794 String8 partialPath;
1795 String8 fullPath;
1796
1797 // XXX This is broken -- the filename cache needs to hold the base
1798 // asset path separately from its filename.
1799
1800 partialPath = createPathNameLocked(ap, locale, vendor);
1801 if (dirName[0] != '\0') {
1802 partialPath.appendPath(dirName);
1803 }
1804
1805 fullPath = partialPath;
1806 pContents = scanDirLocked(fullPath);
1807 if (pContents == NULL) {
1808 return false; // directory did not exist
1809 }
1810
1811 /*
1812 * Scan all subdirectories of the current dir, merging what we find
1813 * into "pMergedInfo".
1814 */
1815 for (int i = 0; i < (int) pContents->size(); i++) {
1816 if (pContents->itemAt(i).getFileType() == kFileTypeDirectory) {
1817 String8 subdir(dirName);
1818 subdir.appendPath(pContents->itemAt(i).getFileName());
1819
1820 fncScanAndMergeDirLocked(pMergedInfo, ap, locale, vendor, subdir.string());
1821 }
1822 }
1823
1824 /*
1825 * To be consistent, we want entries for the root directory. If
1826 * we're the root, add one now.
1827 */
1828 if (dirName[0] == '\0') {
1829 AssetDir::FileInfo tmpInfo;
1830
1831 tmpInfo.set(String8(""), kFileTypeDirectory);
1832 tmpInfo.setSourceName(createPathNameLocked(ap, locale, vendor));
1833 pContents->add(tmpInfo);
1834 }
1835
1836 /*
1837 * We want to prepend the extended partial path to every entry in
1838 * "pContents". It's the same value for each entry, so this will
1839 * not change the sorting order of the vector contents.
1840 */
1841 for (int i = 0; i < (int) pContents->size(); i++) {
1842 const AssetDir::FileInfo& info = pContents->itemAt(i);
1843 pContents->editItemAt(i).setFileName(partialPath.appendPathCopy(info.getFileName()));
1844 }
1845
1846 mergeInfoLocked(pMergedInfo, pContents);
sean_lu7c57d232014-06-16 15:11:29 +08001847 delete pContents;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001848 return true;
1849}
1850
1851/*
1852 * Trash the cache.
1853 */
1854void AssetManager::purgeFileNameCacheLocked(void)
1855{
1856 mCacheValid = false;
1857 mCache.clear();
1858}
1859
1860/*
1861 * ===========================================================================
1862 * AssetManager::SharedZip
1863 * ===========================================================================
1864 */
1865
1866
1867Mutex AssetManager::SharedZip::gLock;
1868DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1869
1870AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1871 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1872 mResourceTableAsset(NULL), mResourceTable(NULL)
1873{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001874 if (kIsDebug) {
1875 ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1876 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001877 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamath560566d2013-12-03 13:16:03 +00001878 mZipFile = ZipFileRO::open(mPath.string());
1879 if (mZipFile == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001880 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001881 }
1882}
1883
Mårten Kongstad48d22322014-01-31 14:43:27 +01001884sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1885 bool createIfNotPresent)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001886{
1887 AutoMutex _l(gLock);
1888 time_t modWhen = getFileModDate(path);
1889 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1890 if (zip != NULL && zip->mModWhen == modWhen) {
1891 return zip;
1892 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001893 if (zip == NULL && !createIfNotPresent) {
1894 return NULL;
1895 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001896 zip = new SharedZip(path, modWhen);
1897 gOpen.add(path, zip);
1898 return zip;
1899
1900}
1901
1902ZipFileRO* AssetManager::SharedZip::getZip()
1903{
1904 return mZipFile;
1905}
1906
1907Asset* AssetManager::SharedZip::getResourceTableAsset()
1908{
songjinshi49921f22016-09-08 15:24:30 +08001909 AutoMutex _l(gLock);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001910 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1911 return mResourceTableAsset;
1912}
1913
1914Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1915{
1916 {
1917 AutoMutex _l(gLock);
1918 if (mResourceTableAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001919 // This is not thread safe the first time it is called, so
1920 // do it here with the global lock held.
1921 asset->getBuffer(true);
songjinshi49921f22016-09-08 15:24:30 +08001922 mResourceTableAsset = asset;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001923 return asset;
1924 }
1925 }
1926 delete asset;
1927 return mResourceTableAsset;
1928}
1929
1930ResTable* AssetManager::SharedZip::getResourceTable()
1931{
1932 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1933 return mResourceTable;
1934}
1935
1936ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1937{
1938 {
1939 AutoMutex _l(gLock);
1940 if (mResourceTable == NULL) {
1941 mResourceTable = res;
1942 return res;
1943 }
1944 }
1945 delete res;
1946 return mResourceTable;
1947}
1948
1949bool AssetManager::SharedZip::isUpToDate()
1950{
1951 time_t modWhen = getFileModDate(mPath.string());
1952 return mModWhen == modWhen;
1953}
1954
Mårten Kongstad48d22322014-01-31 14:43:27 +01001955void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1956{
1957 mOverlays.add(ap);
1958}
1959
1960bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1961{
1962 if (idx >= mOverlays.size()) {
1963 return false;
1964 }
1965 *out = mOverlays[idx];
1966 return true;
1967}
1968
Adam Lesinski16c4d152014-01-24 13:27:13 -08001969AssetManager::SharedZip::~SharedZip()
1970{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001971 if (kIsDebug) {
1972 ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1973 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001974 if (mResourceTable != NULL) {
1975 delete mResourceTable;
1976 }
1977 if (mResourceTableAsset != NULL) {
1978 delete mResourceTableAsset;
1979 }
1980 if (mZipFile != NULL) {
1981 delete mZipFile;
1982 ALOGV("Closed '%s'\n", mPath.string());
1983 }
1984}
1985
1986/*
1987 * ===========================================================================
1988 * AssetManager::ZipSet
1989 * ===========================================================================
1990 */
1991
1992/*
1993 * Constructor.
1994 */
1995AssetManager::ZipSet::ZipSet(void)
1996{
1997}
1998
1999/*
2000 * Destructor. Close any open archives.
2001 */
2002AssetManager::ZipSet::~ZipSet(void)
2003{
2004 size_t N = mZipFile.size();
2005 for (size_t i = 0; i < N; i++)
2006 closeZip(i);
2007}
2008
2009/*
2010 * Close a Zip file and reset the entry.
2011 */
2012void AssetManager::ZipSet::closeZip(int idx)
2013{
2014 mZipFile.editItemAt(idx) = NULL;
2015}
2016
2017
2018/*
2019 * Retrieve the appropriate Zip file from the set.
2020 */
2021ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
2022{
2023 int idx = getIndex(path);
2024 sp<SharedZip> zip = mZipFile[idx];
2025 if (zip == NULL) {
2026 zip = SharedZip::get(path);
2027 mZipFile.editItemAt(idx) = zip;
2028 }
2029 return zip->getZip();
2030}
2031
2032Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
2033{
2034 int idx = getIndex(path);
2035 sp<SharedZip> zip = mZipFile[idx];
2036 if (zip == NULL) {
2037 zip = SharedZip::get(path);
2038 mZipFile.editItemAt(idx) = zip;
2039 }
2040 return zip->getResourceTableAsset();
2041}
2042
2043Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
2044 Asset* asset)
2045{
2046 int idx = getIndex(path);
2047 sp<SharedZip> zip = mZipFile[idx];
2048 // doesn't make sense to call before previously accessing.
2049 return zip->setResourceTableAsset(asset);
2050}
2051
2052ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
2053{
2054 int idx = getIndex(path);
2055 sp<SharedZip> zip = mZipFile[idx];
2056 if (zip == NULL) {
2057 zip = SharedZip::get(path);
2058 mZipFile.editItemAt(idx) = zip;
2059 }
2060 return zip->getResourceTable();
2061}
2062
2063ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
2064 ResTable* res)
2065{
2066 int idx = getIndex(path);
2067 sp<SharedZip> zip = mZipFile[idx];
2068 // doesn't make sense to call before previously accessing.
2069 return zip->setResourceTable(res);
2070}
2071
2072/*
2073 * Generate the partial pathname for the specified archive. The caller
2074 * gets to prepend the asset root directory.
2075 *
2076 * Returns something like "common/en-US-noogle.jar".
2077 */
2078/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
2079{
2080 return String8(zipPath);
2081}
2082
2083bool AssetManager::ZipSet::isUpToDate()
2084{
2085 const size_t N = mZipFile.size();
2086 for (size_t i=0; i<N; i++) {
2087 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
2088 return false;
2089 }
2090 }
2091 return true;
2092}
2093
Mårten Kongstad48d22322014-01-31 14:43:27 +01002094void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
2095{
2096 int idx = getIndex(path);
2097 sp<SharedZip> zip = mZipFile[idx];
2098 zip->addOverlay(overlay);
2099}
2100
2101bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
2102{
2103 sp<SharedZip> zip = SharedZip::get(path, false);
2104 if (zip == NULL) {
2105 return false;
2106 }
2107 return zip->getOverlay(idx, out);
2108}
2109
Adam Lesinski16c4d152014-01-24 13:27:13 -08002110/*
2111 * Compute the zip file's index.
2112 *
2113 * "appName", "locale", and "vendor" should be set to NULL to indicate the
2114 * default directory.
2115 */
2116int AssetManager::ZipSet::getIndex(const String8& zip) const
2117{
2118 const size_t N = mZipPath.size();
2119 for (size_t i=0; i<N; i++) {
2120 if (mZipPath[i] == zip) {
2121 return i;
2122 }
2123 }
2124
2125 mZipPath.add(zip);
2126 mZipFile.add(NULL);
2127
2128 return mZipPath.size()-1;
2129}