blob: 394a9ab308968e8f9f4060cde0b0a6c307ef04a6 [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>
Adam Lesinski16c4d152014-01-24 13:27:13 -080038
39#include <assert.h>
40#include <dirent.h>
41#include <errno.h>
Mårten Kongstad48d22322014-01-31 14:43:27 +010042#include <string.h> // strerror
Adam Lesinski16c4d152014-01-24 13:27:13 -080043#include <strings.h>
Adam Lesinski16c4d152014-01-24 13:27:13 -080044
45#ifndef TEMP_FAILURE_RETRY
46/* Used to retry syscalls that can return EINTR. */
47#define TEMP_FAILURE_RETRY(exp) ({ \
48 typeof (exp) _rc; \
49 do { \
50 _rc = (exp); \
51 } while (_rc == -1 && errno == EINTR); \
52 _rc; })
53#endif
54
Adam Lesinski16c4d152014-01-24 13:27:13 -080055using namespace android;
56
Andreas Gampe2204f0b2014-10-21 23:04:54 -070057static const bool kIsDebug = false;
58
Adam Lesinski16c4d152014-01-24 13:27:13 -080059/*
60 * Names for default app, locale, and vendor. We might want to change
61 * these to be an actual locale, e.g. always use en-US as the default.
62 */
63static const char* kDefaultLocale = "default";
64static const char* kDefaultVendor = "default";
65static const char* kAssetsRoot = "assets";
66static const char* kAppZipName = NULL; //"classes.jar";
67static const char* kSystemAssets = "framework/framework-res.apk";
Mårten Kongstad48d22322014-01-31 14:43:27 +010068static const char* kResourceCache = "resource-cache";
Adam Lesinski16c4d152014-01-24 13:27:13 -080069
70static const char* kExcludeExtension = ".EXCLUDE";
71
72static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
73
74static volatile int32_t gCount = 0;
75
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010076const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
Mårten Kongstad48d22322014-01-31 14:43:27 +010077const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
78const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
Jakub Adamekc03d9482016-09-30 09:19:09 +010079const char* AssetManager::OVERLAY_SKU_DIR_PROPERTY = "ro.boot.vendor.overlay.sku";
Mårten Kongstad48d22322014-01-31 14:43:27 +010080const char* AssetManager::TARGET_PACKAGE_NAME = "android";
81const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
82const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010083
Adam Lesinski16c4d152014-01-24 13:27:13 -080084namespace {
Adam Lesinski16c4d152014-01-24 13:27:13 -080085
Adam Lesinskia77685f2016-10-03 16:26:28 -070086String8 idmapPathForPackagePath(const String8& pkgPath) {
87 const char* root = getenv("ANDROID_DATA");
88 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
89 String8 path(root);
90 path.appendPath(kResourceCache);
Adam Lesinski16c4d152014-01-24 13:27:13 -080091
Adam Lesinskia77685f2016-10-03 16:26:28 -070092 char buf[256]; // 256 chars should be enough for anyone...
93 strncpy(buf, pkgPath.string(), 255);
94 buf[255] = '\0';
95 char* filename = buf;
96 while (*filename && *filename == '/') {
97 ++filename;
Adam Lesinski16c4d152014-01-24 13:27:13 -080098 }
Adam Lesinskia77685f2016-10-03 16:26:28 -070099 char* p = filename;
100 while (*p) {
101 if (*p == '/') {
102 *p = '@';
103 }
104 ++p;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800105 }
Adam Lesinskia77685f2016-10-03 16:26:28 -0700106 path.appendPath(filename);
107 path.append("@idmap");
108
109 return path;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800110}
111
112/*
Adam Lesinskia77685f2016-10-03 16:26:28 -0700113 * Like strdup(), but uses C++ "new" operator instead of malloc.
114 */
115static char* strdupNew(const char* str) {
116 char* newStr;
117 int len;
118
119 if (str == NULL)
120 return NULL;
121
122 len = strlen(str);
123 newStr = new char[len+1];
124 memcpy(newStr, str, len+1);
125
126 return newStr;
127}
128
129} // namespace
130
131/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800132 * ===========================================================================
133 * AssetManager
134 * ===========================================================================
135 */
136
Adam Lesinskia77685f2016-10-03 16:26:28 -0700137int32_t AssetManager::getGlobalCount() {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800138 return gCount;
139}
140
Adam Lesinskia77685f2016-10-03 16:26:28 -0700141AssetManager::AssetManager() :
142 mLocale(NULL), mResources(NULL), mConfig(new ResTable_config) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700143 int count = android_atomic_inc(&gCount) + 1;
144 if (kIsDebug) {
145 ALOGI("Creating AssetManager %p #%d\n", this, count);
146 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800147 memset(mConfig, 0, sizeof(ResTable_config));
148}
149
Adam Lesinskia77685f2016-10-03 16:26:28 -0700150AssetManager::~AssetManager() {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800151 int count = android_atomic_dec(&gCount);
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700152 if (kIsDebug) {
153 ALOGI("Destroying AssetManager in %p #%d\n", this, count);
154 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800155
156 delete mConfig;
157 delete mResources;
158
159 // don't have a String class yet, so make sure we clean up
160 delete[] mLocale;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800161}
162
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800163bool AssetManager::addAssetPath(
Adam Lesinskia77685f2016-10-03 16:26:28 -0700164 const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800165 AutoMutex _l(mLock);
166
167 asset_path ap;
168
169 String8 realPath(path);
170 if (kAppZipName) {
171 realPath.appendPath(kAppZipName);
172 }
173 ap.type = ::getFileType(realPath.string());
174 if (ap.type == kFileTypeRegular) {
175 ap.path = realPath;
176 } else {
177 ap.path = path;
178 ap.type = ::getFileType(path.string());
179 if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
180 ALOGW("Asset path %s is neither a directory nor file (type=%d).",
181 path.string(), (int)ap.type);
182 return false;
183 }
184 }
185
186 // Skip if we have it already.
187 for (size_t i=0; i<mAssetPaths.size(); i++) {
188 if (mAssetPaths[i].path == ap.path) {
189 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000190 *cookie = static_cast<int32_t>(i+1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800191 }
192 return true;
193 }
194 }
195
196 ALOGV("In %p Asset %s path: %s", this,
197 ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
198
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800199 ap.isSystemAsset = isSystemAsset;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800200 mAssetPaths.add(ap);
201
202 // new paths are always added at the end
203 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000204 *cookie = static_cast<int32_t>(mAssetPaths.size());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800205 }
206
Elliott Hughesba3fe562015-08-12 14:49:53 -0700207#ifdef __ANDROID__
Mårten Kongstad48d22322014-01-31 14:43:27 +0100208 // Load overlays, if any
209 asset_path oap;
210 for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800211 oap.isSystemAsset = isSystemAsset;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100212 mAssetPaths.add(oap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800213 }
Mårten Kongstad48d22322014-01-31 14:43:27 +0100214#endif
Adam Lesinski16c4d152014-01-24 13:27:13 -0800215
Martin Kosiba7df36252014-01-16 16:25:56 +0000216 if (mResources != NULL) {
Tao Baia6d7e3f2015-09-01 18:49:54 -0700217 appendPathToResTable(ap, appAsLib);
Martin Kosiba7df36252014-01-16 16:25:56 +0000218 }
219
Adam Lesinski16c4d152014-01-24 13:27:13 -0800220 return true;
221}
222
Mårten Kongstad48d22322014-01-31 14:43:27 +0100223bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
224{
225 const String8 idmapPath = idmapPathForPackagePath(packagePath);
226
227 AutoMutex _l(mLock);
228
229 for (size_t i = 0; i < mAssetPaths.size(); ++i) {
230 if (mAssetPaths[i].idmap == idmapPath) {
231 *cookie = static_cast<int32_t>(i + 1);
232 return true;
233 }
234 }
235
236 Asset* idmap = NULL;
237 if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
238 ALOGW("failed to open idmap file %s\n", idmapPath.string());
239 return false;
240 }
241
242 String8 targetPath;
243 String8 overlayPath;
244 if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700245 NULL, NULL, NULL, &targetPath, &overlayPath)) {
Mårten Kongstad48d22322014-01-31 14:43:27 +0100246 ALOGW("failed to read idmap file %s\n", idmapPath.string());
247 delete idmap;
248 return false;
249 }
250 delete idmap;
251
252 if (overlayPath != packagePath) {
253 ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
254 idmapPath.string(), packagePath.string(), overlayPath.string());
255 return false;
256 }
257 if (access(targetPath.string(), R_OK) != 0) {
258 ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
259 return false;
260 }
261 if (access(idmapPath.string(), R_OK) != 0) {
262 ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
263 return false;
264 }
265 if (access(overlayPath.string(), R_OK) != 0) {
266 ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
267 return false;
268 }
269
270 asset_path oap;
271 oap.path = overlayPath;
272 oap.type = ::getFileType(overlayPath.string());
273 oap.idmap = idmapPath;
274#if 0
275 ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
276 targetPath.string(), overlayPath.string(), idmapPath.string());
277#endif
278 mAssetPaths.add(oap);
279 *cookie = static_cast<int32_t>(mAssetPaths.size());
280
Mårten Kongstad30113132014-11-07 10:52:17 +0100281 if (mResources != NULL) {
282 appendPathToResTable(oap);
283 }
284
Mårten Kongstad48d22322014-01-31 14:43:27 +0100285 return true;
286 }
287
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100288bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
Dianne Hackborn32bb5fa2014-02-11 13:56:21 -0800289 uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100290{
291 AutoMutex _l(mLock);
292 const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
293 ResTable tables[2];
294
295 for (int i = 0; i < 2; ++i) {
296 asset_path ap;
297 ap.type = kFileTypeRegular;
298 ap.path = paths[i];
299 Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
300 if (ass == NULL) {
301 ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
302 return false;
303 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700304 tables[i].add(ass);
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100305 }
306
307 return tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
308 targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
309}
310
Adam Lesinski16c4d152014-01-24 13:27:13 -0800311bool AssetManager::addDefaultAssets()
312{
313 const char* root = getenv("ANDROID_ROOT");
314 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
315
316 String8 path(root);
317 path.appendPath(kSystemAssets);
318
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800319 return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800320}
321
Narayan Kamatha0c62602014-01-24 13:51:51 +0000322int32_t AssetManager::nextAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800323{
324 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000325 const size_t next = static_cast<size_t>(cookie) + 1;
326 return next > mAssetPaths.size() ? -1 : next;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800327}
328
Narayan Kamatha0c62602014-01-24 13:51:51 +0000329String8 AssetManager::getAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800330{
331 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000332 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800333 if (which < mAssetPaths.size()) {
334 return mAssetPaths[which].path;
335 }
336 return String8();
337}
338
Adam Lesinski16c4d152014-01-24 13:27:13 -0800339void AssetManager::setLocaleLocked(const char* locale)
340{
341 if (mLocale != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800342 delete[] mLocale;
343 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700344
Adam Lesinski16c4d152014-01-24 13:27:13 -0800345 mLocale = strdupNew(locale);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800346 updateResourceParamsLocked();
347}
348
Adam Lesinski16c4d152014-01-24 13:27:13 -0800349void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
350{
351 AutoMutex _l(mLock);
352 *mConfig = config;
353 if (locale) {
354 setLocaleLocked(locale);
355 } else if (config.language[0] != 0) {
Narayan Kamath91447d82014-01-21 15:32:36 +0000356 char spec[RESTABLE_MAX_LOCALE_LEN];
357 config.getBcp47Locale(spec);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800358 setLocaleLocked(spec);
359 } else {
360 updateResourceParamsLocked();
361 }
362}
363
364void AssetManager::getConfiguration(ResTable_config* outConfig) const
365{
366 AutoMutex _l(mLock);
367 *outConfig = *mConfig;
368}
369
370/*
371 * Open an asset.
372 *
373 * The data could be;
374 * - In a file on disk (assetBase + fileName).
375 * - In a compressed file on disk (assetBase + fileName.gz).
376 * - In a Zip archive, uncompressed or compressed.
377 *
378 * It can be in a number of different directories and Zip archives.
379 * The search order is:
380 * - [appname]
381 * - locale + vendor
382 * - "default" + vendor
383 * - locale + "default"
384 * - "default + "default"
385 * - "common"
386 * - (same as above)
387 *
388 * To find a particular file, we have to try up to eight paths with
389 * all three forms of data.
390 *
391 * We should probably reject requests for "illegal" filenames, e.g. those
392 * with illegal characters or "../" backward relative paths.
393 */
394Asset* AssetManager::open(const char* fileName, AccessMode mode)
395{
396 AutoMutex _l(mLock);
397
398 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
399
Adam Lesinski16c4d152014-01-24 13:27:13 -0800400 String8 assetName(kAssetsRoot);
401 assetName.appendPath(fileName);
402
403 /*
404 * For each top-level asset path, search for the asset.
405 */
406
407 size_t i = mAssetPaths.size();
408 while (i > 0) {
409 i--;
410 ALOGV("Looking for asset '%s' in '%s'\n",
411 assetName.string(), mAssetPaths.itemAt(i).path.string());
412 Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
413 if (pAsset != NULL) {
414 return pAsset != kExcludedAsset ? pAsset : NULL;
415 }
416 }
417
418 return NULL;
419}
420
421/*
422 * Open a non-asset file as if it were an asset.
423 *
424 * The "fileName" is the partial path starting from the application
425 * name.
426 */
Adam Lesinskide898ff2014-01-29 18:20:45 -0800427Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800428{
429 AutoMutex _l(mLock);
430
431 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
432
Adam Lesinski16c4d152014-01-24 13:27:13 -0800433 /*
434 * For each top-level asset path, search for the asset.
435 */
436
437 size_t i = mAssetPaths.size();
438 while (i > 0) {
439 i--;
440 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
441 Asset* pAsset = openNonAssetInPathLocked(
442 fileName, mode, mAssetPaths.itemAt(i));
443 if (pAsset != NULL) {
Adam Lesinskide898ff2014-01-29 18:20:45 -0800444 if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800445 return pAsset != kExcludedAsset ? pAsset : NULL;
446 }
447 }
448
449 return NULL;
450}
451
Narayan Kamatha0c62602014-01-24 13:51:51 +0000452Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800453{
Narayan Kamatha0c62602014-01-24 13:51:51 +0000454 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800455
456 AutoMutex _l(mLock);
457
458 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
459
Adam Lesinski16c4d152014-01-24 13:27:13 -0800460 if (which < mAssetPaths.size()) {
461 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
462 mAssetPaths.itemAt(which).path.string());
463 Asset* pAsset = openNonAssetInPathLocked(
464 fileName, mode, mAssetPaths.itemAt(which));
465 if (pAsset != NULL) {
466 return pAsset != kExcludedAsset ? pAsset : NULL;
467 }
468 }
469
470 return NULL;
471}
472
473/*
474 * Get the type of a file in the asset namespace.
475 *
476 * This currently only works for regular files. All others (including
477 * directories) will return kFileTypeNonexistent.
478 */
479FileType AssetManager::getFileType(const char* fileName)
480{
481 Asset* pAsset = NULL;
482
483 /*
484 * Open the asset. This is less efficient than simply finding the
485 * file, but it's not too bad (we don't uncompress or mmap data until
486 * the first read() call).
487 */
488 pAsset = open(fileName, Asset::ACCESS_STREAMING);
489 delete pAsset;
490
491 if (pAsset == NULL)
492 return kFileTypeNonexistent;
493 else
494 return kFileTypeRegular;
495}
496
Tao Baia6d7e3f2015-09-01 18:49:54 -0700497bool AssetManager::appendPathToResTable(const asset_path& ap, bool appAsLib) const {
Mårten Kongstadcb7b63d2014-11-07 10:57:15 +0100498 // skip those ap's that correspond to system overlays
499 if (ap.isSystemOverlay) {
500 return true;
501 }
502
Martin Kosiba7df36252014-01-16 16:25:56 +0000503 Asset* ass = NULL;
504 ResTable* sharedRes = NULL;
505 bool shared = true;
506 bool onlyEmptyResources = true;
Adam Lesinskib7e1ce02016-04-11 20:03:01 -0700507 ATRACE_NAME(ap.path.string());
Martin Kosiba7df36252014-01-16 16:25:56 +0000508 Asset* idmap = openIdmapLocked(ap);
509 size_t nextEntryIdx = mResources->getTableCount();
510 ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
511 if (ap.type != kFileTypeDirectory) {
512 if (nextEntryIdx == 0) {
513 // The first item is typically the framework resources,
514 // which we want to avoid parsing every time.
515 sharedRes = const_cast<AssetManager*>(this)->
516 mZipSet.getZipResourceTable(ap.path);
517 if (sharedRes != NULL) {
518 // skip ahead the number of system overlay packages preloaded
519 nextEntryIdx = sharedRes->getTableCount();
520 }
521 }
522 if (sharedRes == NULL) {
523 ass = const_cast<AssetManager*>(this)->
524 mZipSet.getZipResourceTableAsset(ap.path);
525 if (ass == NULL) {
526 ALOGV("loading resource table %s\n", ap.path.string());
527 ass = const_cast<AssetManager*>(this)->
528 openNonAssetInPathLocked("resources.arsc",
529 Asset::ACCESS_BUFFER,
530 ap);
531 if (ass != NULL && ass != kExcludedAsset) {
532 ass = const_cast<AssetManager*>(this)->
533 mZipSet.setZipResourceTableAsset(ap.path, ass);
534 }
535 }
536
537 if (nextEntryIdx == 0 && ass != NULL) {
538 // If this is the first resource table in the asset
539 // manager, then we are going to cache it so that we
540 // can quickly copy it out for others.
541 ALOGV("Creating shared resources for %s", ap.path.string());
542 sharedRes = new ResTable();
543 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
Elliott Hughesba3fe562015-08-12 14:49:53 -0700544#ifdef __ANDROID__
Martin Kosiba7df36252014-01-16 16:25:56 +0000545 const char* data = getenv("ANDROID_DATA");
546 LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
547 String8 overlaysListPath(data);
548 overlaysListPath.appendPath(kResourceCache);
549 overlaysListPath.appendPath("overlays.list");
550 addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
551#endif
552 sharedRes = const_cast<AssetManager*>(this)->
553 mZipSet.setZipResourceTable(ap.path, sharedRes);
554 }
555 }
556 } else {
557 ALOGV("loading resource table %s\n", ap.path.string());
558 ass = const_cast<AssetManager*>(this)->
559 openNonAssetInPathLocked("resources.arsc",
560 Asset::ACCESS_BUFFER,
561 ap);
562 shared = false;
563 }
564
565 if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
566 ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
567 if (sharedRes != NULL) {
568 ALOGV("Copying existing resources for %s", ap.path.string());
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800569 mResources->add(sharedRes, ap.isSystemAsset);
Martin Kosiba7df36252014-01-16 16:25:56 +0000570 } else {
571 ALOGV("Parsing resources for %s", ap.path.string());
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800572 mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
Martin Kosiba7df36252014-01-16 16:25:56 +0000573 }
574 onlyEmptyResources = false;
575
576 if (!shared) {
577 delete ass;
578 }
579 } else {
580 ALOGV("Installing empty resources in to table %p\n", mResources);
581 mResources->addEmpty(nextEntryIdx + 1);
582 }
583
584 if (idmap != NULL) {
585 delete idmap;
586 }
Martin Kosiba7df36252014-01-16 16:25:56 +0000587 return onlyEmptyResources;
588}
589
Adam Lesinski16c4d152014-01-24 13:27:13 -0800590const ResTable* AssetManager::getResTable(bool required) const
591{
592 ResTable* rt = mResources;
593 if (rt) {
594 return rt;
595 }
596
597 // Iterate through all asset packages, collecting resources from each.
598
599 AutoMutex _l(mLock);
600
601 if (mResources != NULL) {
602 return mResources;
603 }
604
605 if (required) {
606 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
607 }
608
Adam Lesinskide898ff2014-01-29 18:20:45 -0800609 mResources = new ResTable();
610 updateResourceParamsLocked();
611
612 bool onlyEmptyResources = true;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800613 const size_t N = mAssetPaths.size();
614 for (size_t i=0; i<N; i++) {
Martin Kosiba7df36252014-01-16 16:25:56 +0000615 bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
616 onlyEmptyResources = onlyEmptyResources && empty;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800617 }
618
Adam Lesinskide898ff2014-01-29 18:20:45 -0800619 if (required && onlyEmptyResources) {
620 ALOGW("Unable to find resources file resources.arsc");
621 delete mResources;
622 mResources = NULL;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800623 }
Adam Lesinskide898ff2014-01-29 18:20:45 -0800624
625 return mResources;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800626}
627
628void AssetManager::updateResourceParamsLocked() const
629{
Adam Lesinskib7e1ce02016-04-11 20:03:01 -0700630 ATRACE_CALL();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800631 ResTable* res = mResources;
632 if (!res) {
633 return;
634 }
635
Narayan Kamath91447d82014-01-21 15:32:36 +0000636 if (mLocale) {
637 mConfig->setBcp47Locale(mLocale);
638 } else {
639 mConfig->clearLocale();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800640 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800641
642 res->setParameters(mConfig);
643}
644
645Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
646{
647 Asset* ass = NULL;
648 if (ap.idmap.size() != 0) {
649 ass = const_cast<AssetManager*>(this)->
650 openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
651 if (ass) {
652 ALOGV("loading idmap %s\n", ap.idmap.string());
653 } else {
654 ALOGW("failed to load idmap %s\n", ap.idmap.string());
655 }
656 }
657 return ass;
658}
659
Mårten Kongstad48d22322014-01-31 14:43:27 +0100660void AssetManager::addSystemOverlays(const char* pathOverlaysList,
661 const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
662{
663 FILE* fin = fopen(pathOverlaysList, "r");
664 if (fin == NULL) {
665 return;
666 }
667
668 char buf[1024];
669 while (fgets(buf, sizeof(buf), fin)) {
670 // format of each line:
671 // <path to apk><space><path to idmap><newline>
672 char* space = strchr(buf, ' ');
673 char* newline = strchr(buf, '\n');
674 asset_path oap;
675
676 if (space == NULL || newline == NULL || newline < space) {
677 continue;
678 }
679
680 oap.path = String8(buf, space - buf);
681 oap.type = kFileTypeRegular;
682 oap.idmap = String8(space + 1, newline - space - 1);
Mårten Kongstadcb7b63d2014-11-07 10:57:15 +0100683 oap.isSystemOverlay = true;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100684
685 Asset* oass = const_cast<AssetManager*>(this)->
686 openNonAssetInPathLocked("resources.arsc",
687 Asset::ACCESS_BUFFER,
688 oap);
689
690 if (oass != NULL) {
691 Asset* oidmap = openIdmapLocked(oap);
692 offset++;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700693 sharedRes->add(oass, oidmap, offset + 1, false);
Mårten Kongstad48d22322014-01-31 14:43:27 +0100694 const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
695 const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
696 }
697 }
698 fclose(fin);
699}
700
Adam Lesinski16c4d152014-01-24 13:27:13 -0800701const ResTable& AssetManager::getResources(bool required) const
702{
703 const ResTable* rt = getResTable(required);
704 return *rt;
705}
706
707bool AssetManager::isUpToDate()
708{
709 AutoMutex _l(mLock);
710 return mZipSet.isUpToDate();
711}
712
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800713void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800714{
715 ResTable* res = mResources;
716 if (res != NULL) {
Roozbeh Pournader7e5f96f2016-06-13 18:10:49 -0700717 res->getLocales(locales, includeSystemLocales, true /* mergeEquivalentLangs */);
Narayan Kamathe4345db2014-06-26 16:01:28 +0100718 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800719}
720
721/*
722 * Open a non-asset file as if it were an asset, searching for it in the
723 * specified app.
724 *
725 * Pass in a NULL values for "appName" if the common app directory should
726 * be used.
727 */
728Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
729 const asset_path& ap)
730{
731 Asset* pAsset = NULL;
732
733 /* look at the filesystem on disk */
734 if (ap.type == kFileTypeDirectory) {
735 String8 path(ap.path);
736 path.appendPath(fileName);
737
738 pAsset = openAssetFromFileLocked(path, mode);
739
740 if (pAsset == NULL) {
741 /* try again, this time with ".gz" */
742 path.append(".gz");
743 pAsset = openAssetFromFileLocked(path, mode);
744 }
745
746 if (pAsset != NULL) {
747 //printf("FOUND NA '%s' on disk\n", fileName);
748 pAsset->setAssetSource(path);
749 }
750
751 /* look inside the zip file */
752 } else {
753 String8 path(fileName);
754
755 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +0000756 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800757 if (pZip != NULL) {
758 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000759 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800760 if (entry != NULL) {
761 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
762 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000763 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800764 }
765 }
766
767 if (pAsset != NULL) {
768 /* create a "source" name, for debug/display */
769 pAsset->setAssetSource(
770 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
771 String8(fileName)));
772 }
773 }
774
775 return pAsset;
776}
777
778/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800779 * Create a "source name" for a file from a Zip archive.
780 */
781String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
782 const String8& dirName, const String8& fileName)
783{
784 String8 sourceName("zip:");
785 sourceName.append(zipFileName);
786 sourceName.append(":");
787 if (dirName.length() > 0) {
788 sourceName.appendPath(dirName);
789 }
790 sourceName.appendPath(fileName);
791 return sourceName;
792}
793
794/*
795 * Create a path to a loose asset (asset-base/app/locale/vendor).
796 */
797String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* locale,
798 const char* vendor)
799{
800 String8 path(ap.path);
801 path.appendPath((locale != NULL) ? locale : kDefaultLocale);
802 path.appendPath((vendor != NULL) ? vendor : kDefaultVendor);
803 return path;
804}
805
806/*
807 * Create a path to a loose asset (asset-base/app/rootDir).
808 */
809String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
810{
811 String8 path(ap.path);
812 if (rootDir != NULL) path.appendPath(rootDir);
813 return path;
814}
815
816/*
817 * Return a pointer to one of our open Zip archives. Returns NULL if no
818 * matching Zip file exists.
819 *
820 * Right now we have 2 possible Zip files (1 each in app/"common").
821 *
822 * If caching is set to CACHE_OFF, to get the expected behavior we
823 * need to reopen the Zip file on every request. That would be silly
824 * and expensive, so instead we just check the file modification date.
825 *
826 * Pass in NULL values for "appName", "locale", and "vendor" if the
827 * generics should be used.
828 */
829ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
830{
831 ALOGV("getZipFileLocked() in %p\n", this);
832
833 return mZipSet.getZip(ap.path);
834}
835
836/*
837 * Try to open an asset from a file on disk.
838 *
839 * If the file is compressed with gzip, we seek to the start of the
840 * deflated data and pass that in (just like we would for a Zip archive).
841 *
842 * For uncompressed data, we may already have an mmap()ed version sitting
843 * around. If so, we want to hand that to the Asset instead.
844 *
845 * This returns NULL if the file doesn't exist, couldn't be opened, or
846 * claims to be a ".gz" but isn't.
847 */
848Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
849 AccessMode mode)
850{
851 Asset* pAsset = NULL;
852
853 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
854 //printf("TRYING '%s'\n", (const char*) pathName);
855 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
856 } else {
857 //printf("TRYING '%s'\n", (const char*) pathName);
858 pAsset = Asset::createFromFile(pathName.string(), mode);
859 }
860
861 return pAsset;
862}
863
864/*
865 * Given an entry in a Zip archive, create a new Asset object.
866 *
867 * If the entry is uncompressed, we may want to create or share a
868 * slice of shared memory.
869 */
870Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
871 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
872{
873 Asset* pAsset = NULL;
874
875 // TODO: look for previously-created shared memory slice?
Narayan Kamath407753c2015-06-16 12:02:57 +0100876 uint16_t method;
877 uint32_t uncompressedLen;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800878
879 //printf("USING Zip '%s'\n", pEntry->getFileName());
880
Adam Lesinski16c4d152014-01-24 13:27:13 -0800881 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
882 NULL, NULL))
883 {
884 ALOGW("getEntryInfo failed\n");
885 return NULL;
886 }
887
888 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
889 if (dataMap == NULL) {
890 ALOGW("create map from entry failed\n");
891 return NULL;
892 }
893
894 if (method == ZipFileRO::kCompressStored) {
895 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
896 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
897 dataMap->getFileName(), mode, pAsset);
898 } else {
Narayan Kamath407753c2015-06-16 12:02:57 +0100899 pAsset = Asset::createFromCompressedMap(dataMap,
900 static_cast<size_t>(uncompressedLen), mode);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800901 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
902 dataMap->getFileName(), mode, pAsset);
903 }
904 if (pAsset == NULL) {
905 /* unexpected */
906 ALOGW("create from segment failed\n");
907 }
908
909 return pAsset;
910}
911
912
913
914/*
915 * Open a directory in the asset namespace.
916 *
917 * An "asset directory" is simply the combination of all files in all
918 * locations, with ".gz" stripped for loose files. With app, locale, and
919 * vendor defined, we have 8 directories and 2 Zip archives to scan.
920 *
921 * Pass in "" for the root dir.
922 */
923AssetDir* AssetManager::openDir(const char* dirName)
924{
925 AutoMutex _l(mLock);
926
927 AssetDir* pDir = NULL;
928 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
929
930 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
931 assert(dirName != NULL);
932
933 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
934
Adam Lesinski16c4d152014-01-24 13:27:13 -0800935 pDir = new AssetDir;
936
937 /*
938 * Scan the various directories, merging what we find into a single
939 * vector. We want to scan them in reverse priority order so that
940 * the ".EXCLUDE" processing works correctly. Also, if we decide we
941 * want to remember where the file is coming from, we'll get the right
942 * version.
943 *
944 * We start with Zip archives, then do loose files.
945 */
946 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
947
948 size_t i = mAssetPaths.size();
949 while (i > 0) {
950 i--;
951 const asset_path& ap = mAssetPaths.itemAt(i);
952 if (ap.type == kFileTypeRegular) {
953 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
954 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
955 } else {
956 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
957 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
958 }
959 }
960
961#if 0
962 printf("FILE LIST:\n");
963 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
964 printf(" %d: (%d) '%s'\n", i,
965 pMergedInfo->itemAt(i).getFileType(),
966 (const char*) pMergedInfo->itemAt(i).getFileName());
967 }
968#endif
969
970 pDir->setFileList(pMergedInfo);
971 return pDir;
972}
973
974/*
975 * Open a directory in the non-asset namespace.
976 *
977 * An "asset directory" is simply the combination of all files in all
978 * locations, with ".gz" stripped for loose files. With app, locale, and
979 * vendor defined, we have 8 directories and 2 Zip archives to scan.
980 *
981 * Pass in "" for the root dir.
982 */
Narayan Kamatha0c62602014-01-24 13:51:51 +0000983AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800984{
985 AutoMutex _l(mLock);
986
987 AssetDir* pDir = NULL;
988 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
989
990 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
991 assert(dirName != NULL);
992
993 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
994
Adam Lesinski16c4d152014-01-24 13:27:13 -0800995 pDir = new AssetDir;
996
997 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
998
Narayan Kamatha0c62602014-01-24 13:51:51 +0000999 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001000
1001 if (which < mAssetPaths.size()) {
1002 const asset_path& ap = mAssetPaths.itemAt(which);
1003 if (ap.type == kFileTypeRegular) {
1004 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
1005 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
1006 } else {
1007 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
1008 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
1009 }
1010 }
1011
1012#if 0
1013 printf("FILE LIST:\n");
1014 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
1015 printf(" %d: (%d) '%s'\n", i,
1016 pMergedInfo->itemAt(i).getFileType(),
1017 (const char*) pMergedInfo->itemAt(i).getFileName());
1018 }
1019#endif
1020
1021 pDir->setFileList(pMergedInfo);
1022 return pDir;
1023}
1024
1025/*
1026 * Scan the contents of the specified directory and merge them into the
1027 * "pMergedInfo" vector, removing previous entries if we find "exclude"
1028 * directives.
1029 *
1030 * Returns "false" if we found nothing to contribute.
1031 */
1032bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1033 const asset_path& ap, const char* rootDir, const char* dirName)
1034{
Adam Lesinski16c4d152014-01-24 13:27:13 -08001035 assert(pMergedInfo != NULL);
1036
Adam Lesinskia77685f2016-10-03 16:26:28 -07001037 //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001038
Adam Lesinskia77685f2016-10-03 16:26:28 -07001039 String8 path = createPathNameLocked(ap, rootDir);
1040 if (dirName[0] != '\0')
1041 path.appendPath(dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001042
Adam Lesinskia77685f2016-10-03 16:26:28 -07001043 SortedVector<AssetDir::FileInfo>* pContents = scanDirLocked(path);
1044 if (pContents == NULL)
1045 return false;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001046
1047 // if we wanted to do an incremental cache fill, we would do it here
1048
1049 /*
1050 * Process "exclude" directives. If we find a filename that ends with
1051 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1052 * remove it if we find it. We also delete the "exclude" entry.
1053 */
1054 int i, count, exclExtLen;
1055
1056 count = pContents->size();
1057 exclExtLen = strlen(kExcludeExtension);
1058 for (i = 0; i < count; i++) {
1059 const char* name;
1060 int nameLen;
1061
1062 name = pContents->itemAt(i).getFileName().string();
1063 nameLen = strlen(name);
1064 if (nameLen > exclExtLen &&
1065 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1066 {
1067 String8 match(name, nameLen - exclExtLen);
1068 int matchIdx;
1069
1070 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1071 if (matchIdx > 0) {
1072 ALOGV("Excluding '%s' [%s]\n",
1073 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1074 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1075 pMergedInfo->removeAt(matchIdx);
1076 } else {
1077 //printf("+++ no match on '%s'\n", (const char*) match);
1078 }
1079
1080 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1081 pContents->removeAt(i);
1082 i--; // adjust "for" loop
1083 count--; // and loop limit
1084 }
1085 }
1086
1087 mergeInfoLocked(pMergedInfo, pContents);
1088
1089 delete pContents;
1090
1091 return true;
1092}
1093
1094/*
1095 * Scan the contents of the specified directory, and stuff what we find
1096 * into a newly-allocated vector.
1097 *
1098 * Files ending in ".gz" will have their extensions removed.
1099 *
1100 * We should probably think about skipping files with "illegal" names,
1101 * e.g. illegal characters (/\:) or excessive length.
1102 *
1103 * Returns NULL if the specified directory doesn't exist.
1104 */
1105SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1106{
1107 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1108 DIR* dir;
1109 struct dirent* entry;
1110 FileType fileType;
1111
1112 ALOGV("Scanning dir '%s'\n", path.string());
1113
1114 dir = opendir(path.string());
1115 if (dir == NULL)
1116 return NULL;
1117
1118 pContents = new SortedVector<AssetDir::FileInfo>;
1119
1120 while (1) {
1121 entry = readdir(dir);
1122 if (entry == NULL)
1123 break;
1124
1125 if (strcmp(entry->d_name, ".") == 0 ||
1126 strcmp(entry->d_name, "..") == 0)
1127 continue;
1128
1129#ifdef _DIRENT_HAVE_D_TYPE
1130 if (entry->d_type == DT_REG)
1131 fileType = kFileTypeRegular;
1132 else if (entry->d_type == DT_DIR)
1133 fileType = kFileTypeDirectory;
1134 else
1135 fileType = kFileTypeUnknown;
1136#else
1137 // stat the file
1138 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1139#endif
1140
1141 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1142 continue;
1143
1144 AssetDir::FileInfo info;
1145 info.set(String8(entry->d_name), fileType);
1146 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1147 info.setFileName(info.getFileName().getBasePath());
1148 info.setSourceName(path.appendPathCopy(info.getFileName()));
1149 pContents->add(info);
1150 }
1151
1152 closedir(dir);
1153 return pContents;
1154}
1155
1156/*
1157 * Scan the contents out of the specified Zip archive, and merge what we
1158 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1159 * we return immediately.
1160 *
1161 * Returns "false" if we found nothing to contribute.
1162 */
1163bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1164 const asset_path& ap, const char* rootDir, const char* baseDirName)
1165{
1166 ZipFileRO* pZip;
1167 Vector<String8> dirs;
1168 AssetDir::FileInfo info;
1169 SortedVector<AssetDir::FileInfo> contents;
1170 String8 sourceName, zipName, dirName;
1171
1172 pZip = mZipSet.getZip(ap.path);
1173 if (pZip == NULL) {
1174 ALOGW("Failure opening zip %s\n", ap.path.string());
1175 return false;
1176 }
1177
1178 zipName = ZipSet::getPathName(ap.path.string());
1179
1180 /* convert "sounds" to "rootDir/sounds" */
1181 if (rootDir != NULL) dirName = rootDir;
1182 dirName.appendPath(baseDirName);
1183
1184 /*
1185 * Scan through the list of files, looking for a match. The files in
1186 * the Zip table of contents are not in sorted order, so we have to
1187 * process the entire list. We're looking for a string that begins
1188 * with the characters in "dirName", is followed by a '/', and has no
1189 * subsequent '/' in the stuff that follows.
1190 *
1191 * What makes this especially fun is that directories are not stored
1192 * explicitly in Zip archives, so we have to infer them from context.
1193 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1194 * to insert a directory called "sounds" into the list. We store
1195 * these in temporary vector so that we only return each one once.
1196 *
1197 * Name comparisons are case-sensitive to match UNIX filesystem
1198 * semantics.
1199 */
1200 int dirNameLen = dirName.length();
Narayan Kamath560566d2013-12-03 13:16:03 +00001201 void *iterationCookie;
Yusuke Sato05f648e2015-08-03 16:21:10 -07001202 if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
Narayan Kamath560566d2013-12-03 13:16:03 +00001203 ALOGW("ZipFileRO::startIteration returned false");
1204 return false;
1205 }
1206
1207 ZipEntryRO entry;
1208 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001209 char nameBuf[256];
1210
Adam Lesinski16c4d152014-01-24 13:27:13 -08001211 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1212 // TODO: fix this if we expect to have long names
1213 ALOGE("ARGH: name too long?\n");
1214 continue;
1215 }
1216 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
Yusuke Sato05f648e2015-08-03 16:21:10 -07001217 if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
Adam Lesinski16c4d152014-01-24 13:27:13 -08001218 {
1219 const char* cp;
1220 const char* nextSlash;
1221
1222 cp = nameBuf + dirNameLen;
1223 if (dirNameLen != 0)
1224 cp++; // advance past the '/'
1225
1226 nextSlash = strchr(cp, '/');
1227//xxx this may break if there are bare directory entries
1228 if (nextSlash == NULL) {
1229 /* this is a file in the requested directory */
1230
1231 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1232
1233 info.setSourceName(
1234 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1235
1236 contents.add(info);
1237 //printf("FOUND: file '%s'\n", info.getFileName().string());
1238 } else {
1239 /* this is a subdir; add it if we don't already have it*/
1240 String8 subdirName(cp, nextSlash - cp);
1241 size_t j;
1242 size_t N = dirs.size();
1243
1244 for (j = 0; j < N; j++) {
1245 if (subdirName == dirs[j]) {
1246 break;
1247 }
1248 }
1249 if (j == N) {
1250 dirs.add(subdirName);
1251 }
1252
1253 //printf("FOUND: dir '%s'\n", subdirName.string());
1254 }
1255 }
1256 }
1257
Narayan Kamath560566d2013-12-03 13:16:03 +00001258 pZip->endIteration(iterationCookie);
1259
Adam Lesinski16c4d152014-01-24 13:27:13 -08001260 /*
1261 * Add the set of unique directories.
1262 */
1263 for (int i = 0; i < (int) dirs.size(); i++) {
1264 info.set(dirs[i], kFileTypeDirectory);
1265 info.setSourceName(
1266 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1267 contents.add(info);
1268 }
1269
1270 mergeInfoLocked(pMergedInfo, &contents);
1271
1272 return true;
1273}
1274
1275
1276/*
1277 * Merge two vectors of FileInfo.
1278 *
1279 * The merged contents will be stuffed into *pMergedInfo.
1280 *
1281 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1282 * we use the newer "pContents" entry.
1283 */
1284void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1285 const SortedVector<AssetDir::FileInfo>* pContents)
1286{
1287 /*
1288 * Merge what we found in this directory with what we found in
1289 * other places.
1290 *
1291 * Two basic approaches:
1292 * (1) Create a new array that holds the unique values of the two
1293 * arrays.
1294 * (2) Take the elements from pContents and shove them into pMergedInfo.
1295 *
1296 * Because these are vectors of complex objects, moving elements around
1297 * inside the vector requires constructing new objects and allocating
1298 * storage for members. With approach #1, we're always adding to the
1299 * end, whereas with #2 we could be inserting multiple elements at the
1300 * front of the vector. Approach #1 requires a full copy of the
1301 * contents of pMergedInfo, but approach #2 requires the same copy for
1302 * every insertion at the front of pMergedInfo.
1303 *
1304 * (We should probably use a SortedVector interface that allows us to
1305 * just stuff items in, trusting us to maintain the sort order.)
1306 */
1307 SortedVector<AssetDir::FileInfo>* pNewSorted;
1308 int mergeMax, contMax;
1309 int mergeIdx, contIdx;
1310
1311 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1312 mergeMax = pMergedInfo->size();
1313 contMax = pContents->size();
1314 mergeIdx = contIdx = 0;
1315
1316 while (mergeIdx < mergeMax || contIdx < contMax) {
1317 if (mergeIdx == mergeMax) {
1318 /* hit end of "merge" list, copy rest of "contents" */
1319 pNewSorted->add(pContents->itemAt(contIdx));
1320 contIdx++;
1321 } else if (contIdx == contMax) {
1322 /* hit end of "cont" list, copy rest of "merge" */
1323 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1324 mergeIdx++;
1325 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1326 {
1327 /* items are identical, add newer and advance both indices */
1328 pNewSorted->add(pContents->itemAt(contIdx));
1329 mergeIdx++;
1330 contIdx++;
1331 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1332 {
1333 /* "merge" is lower, add that one */
1334 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1335 mergeIdx++;
1336 } else {
1337 /* "cont" is lower, add that one */
1338 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1339 pNewSorted->add(pContents->itemAt(contIdx));
1340 contIdx++;
1341 }
1342 }
1343
1344 /*
1345 * Overwrite the "merged" list with the new stuff.
1346 */
1347 *pMergedInfo = *pNewSorted;
1348 delete pNewSorted;
1349
1350#if 0 // for Vector, rather than SortedVector
1351 int i, j;
1352 for (i = pContents->size() -1; i >= 0; i--) {
1353 bool add = true;
1354
1355 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1356 /* case-sensitive comparisons, to behave like UNIX fs */
1357 if (strcmp(pContents->itemAt(i).mFileName,
1358 pMergedInfo->itemAt(j).mFileName) == 0)
1359 {
1360 /* match, don't add this entry */
1361 add = false;
1362 break;
1363 }
1364 }
1365
1366 if (add)
1367 pMergedInfo->add(pContents->itemAt(i));
1368 }
1369#endif
1370}
1371
Adam Lesinski16c4d152014-01-24 13:27:13 -08001372/*
1373 * ===========================================================================
1374 * AssetManager::SharedZip
1375 * ===========================================================================
1376 */
1377
1378
1379Mutex AssetManager::SharedZip::gLock;
1380DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1381
1382AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1383 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1384 mResourceTableAsset(NULL), mResourceTable(NULL)
1385{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001386 if (kIsDebug) {
1387 ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1388 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001389 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamath560566d2013-12-03 13:16:03 +00001390 mZipFile = ZipFileRO::open(mPath.string());
1391 if (mZipFile == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001392 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001393 }
1394}
1395
Mårten Kongstad48d22322014-01-31 14:43:27 +01001396sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1397 bool createIfNotPresent)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001398{
1399 AutoMutex _l(gLock);
1400 time_t modWhen = getFileModDate(path);
1401 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1402 if (zip != NULL && zip->mModWhen == modWhen) {
1403 return zip;
1404 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001405 if (zip == NULL && !createIfNotPresent) {
1406 return NULL;
1407 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001408 zip = new SharedZip(path, modWhen);
1409 gOpen.add(path, zip);
1410 return zip;
1411
1412}
1413
1414ZipFileRO* AssetManager::SharedZip::getZip()
1415{
1416 return mZipFile;
1417}
1418
1419Asset* AssetManager::SharedZip::getResourceTableAsset()
1420{
songjinshi49921f22016-09-08 15:24:30 +08001421 AutoMutex _l(gLock);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001422 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1423 return mResourceTableAsset;
1424}
1425
1426Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1427{
1428 {
1429 AutoMutex _l(gLock);
1430 if (mResourceTableAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001431 // This is not thread safe the first time it is called, so
1432 // do it here with the global lock held.
1433 asset->getBuffer(true);
songjinshi49921f22016-09-08 15:24:30 +08001434 mResourceTableAsset = asset;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001435 return asset;
1436 }
1437 }
1438 delete asset;
1439 return mResourceTableAsset;
1440}
1441
1442ResTable* AssetManager::SharedZip::getResourceTable()
1443{
1444 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1445 return mResourceTable;
1446}
1447
1448ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1449{
1450 {
1451 AutoMutex _l(gLock);
1452 if (mResourceTable == NULL) {
1453 mResourceTable = res;
1454 return res;
1455 }
1456 }
1457 delete res;
1458 return mResourceTable;
1459}
1460
1461bool AssetManager::SharedZip::isUpToDate()
1462{
1463 time_t modWhen = getFileModDate(mPath.string());
1464 return mModWhen == modWhen;
1465}
1466
Mårten Kongstad48d22322014-01-31 14:43:27 +01001467void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1468{
1469 mOverlays.add(ap);
1470}
1471
1472bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1473{
1474 if (idx >= mOverlays.size()) {
1475 return false;
1476 }
1477 *out = mOverlays[idx];
1478 return true;
1479}
1480
Adam Lesinski16c4d152014-01-24 13:27:13 -08001481AssetManager::SharedZip::~SharedZip()
1482{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001483 if (kIsDebug) {
1484 ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1485 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001486 if (mResourceTable != NULL) {
1487 delete mResourceTable;
1488 }
1489 if (mResourceTableAsset != NULL) {
1490 delete mResourceTableAsset;
1491 }
1492 if (mZipFile != NULL) {
1493 delete mZipFile;
1494 ALOGV("Closed '%s'\n", mPath.string());
1495 }
1496}
1497
1498/*
1499 * ===========================================================================
1500 * AssetManager::ZipSet
1501 * ===========================================================================
1502 */
1503
1504/*
1505 * Constructor.
1506 */
1507AssetManager::ZipSet::ZipSet(void)
1508{
1509}
1510
1511/*
1512 * Destructor. Close any open archives.
1513 */
1514AssetManager::ZipSet::~ZipSet(void)
1515{
1516 size_t N = mZipFile.size();
1517 for (size_t i = 0; i < N; i++)
1518 closeZip(i);
1519}
1520
1521/*
1522 * Close a Zip file and reset the entry.
1523 */
1524void AssetManager::ZipSet::closeZip(int idx)
1525{
1526 mZipFile.editItemAt(idx) = NULL;
1527}
1528
1529
1530/*
1531 * Retrieve the appropriate Zip file from the set.
1532 */
1533ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1534{
1535 int idx = getIndex(path);
1536 sp<SharedZip> zip = mZipFile[idx];
1537 if (zip == NULL) {
1538 zip = SharedZip::get(path);
1539 mZipFile.editItemAt(idx) = zip;
1540 }
1541 return zip->getZip();
1542}
1543
1544Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
1545{
1546 int idx = getIndex(path);
1547 sp<SharedZip> zip = mZipFile[idx];
1548 if (zip == NULL) {
1549 zip = SharedZip::get(path);
1550 mZipFile.editItemAt(idx) = zip;
1551 }
1552 return zip->getResourceTableAsset();
1553}
1554
1555Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
1556 Asset* asset)
1557{
1558 int idx = getIndex(path);
1559 sp<SharedZip> zip = mZipFile[idx];
1560 // doesn't make sense to call before previously accessing.
1561 return zip->setResourceTableAsset(asset);
1562}
1563
1564ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
1565{
1566 int idx = getIndex(path);
1567 sp<SharedZip> zip = mZipFile[idx];
1568 if (zip == NULL) {
1569 zip = SharedZip::get(path);
1570 mZipFile.editItemAt(idx) = zip;
1571 }
1572 return zip->getResourceTable();
1573}
1574
1575ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
1576 ResTable* res)
1577{
1578 int idx = getIndex(path);
1579 sp<SharedZip> zip = mZipFile[idx];
1580 // doesn't make sense to call before previously accessing.
1581 return zip->setResourceTable(res);
1582}
1583
1584/*
1585 * Generate the partial pathname for the specified archive. The caller
1586 * gets to prepend the asset root directory.
1587 *
1588 * Returns something like "common/en-US-noogle.jar".
1589 */
1590/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
1591{
1592 return String8(zipPath);
1593}
1594
1595bool AssetManager::ZipSet::isUpToDate()
1596{
1597 const size_t N = mZipFile.size();
1598 for (size_t i=0; i<N; i++) {
1599 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
1600 return false;
1601 }
1602 }
1603 return true;
1604}
1605
Mårten Kongstad48d22322014-01-31 14:43:27 +01001606void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
1607{
1608 int idx = getIndex(path);
1609 sp<SharedZip> zip = mZipFile[idx];
1610 zip->addOverlay(overlay);
1611}
1612
1613bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
1614{
1615 sp<SharedZip> zip = SharedZip::get(path, false);
1616 if (zip == NULL) {
1617 return false;
1618 }
1619 return zip->getOverlay(idx, out);
1620}
1621
Adam Lesinski16c4d152014-01-24 13:27:13 -08001622/*
1623 * Compute the zip file's index.
1624 *
1625 * "appName", "locale", and "vendor" should be set to NULL to indicate the
1626 * default directory.
1627 */
1628int AssetManager::ZipSet::getIndex(const String8& zip) const
1629{
1630 const size_t N = mZipPath.size();
1631 for (size_t i=0; i<N; i++) {
1632 if (mZipPath[i] == zip) {
1633 return i;
1634 }
1635 }
1636
1637 mZipPath.add(zip);
1638 mZipFile.add(NULL);
1639
1640 return mZipPath.size()-1;
1641}