blob: 46fc9d43b3f617a50da477bc6a27d9f09120f206 [file] [log] [blame]
Adam Lesinski16c4d152014-01-24 13:27:13 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Provide access to read-only assets.
19//
20
21#define LOG_TAG "asset"
22#define ATRACE_TAG ATRACE_TAG_RESOURCES
23//#define LOG_NDEBUG 0
24
25#include <androidfw/Asset.h>
26#include <androidfw/AssetDir.h>
27#include <androidfw/AssetManager.h>
28#include <androidfw/misc.h>
29#include <androidfw/ResourceTypes.h>
30#include <androidfw/ZipFileRO.h>
31#include <utils/Atomic.h>
32#include <utils/Log.h>
33#include <utils/String8.h>
34#include <utils/String8.h>
35#include <utils/threads.h>
36#include <utils/Timers.h>
Adam Lesinskib7e1ce02016-04-11 20:03:01 -070037#include <utils/Trace.h>
Martin Wallgren0fbb6082015-08-11 15:10:31 +020038#ifndef _WIN32
39#include <sys/file.h>
40#endif
Adam Lesinski16c4d152014-01-24 13:27:13 -080041
42#include <assert.h>
43#include <dirent.h>
44#include <errno.h>
Mårten Kongstad48d22322014-01-31 14:43:27 +010045#include <string.h> // strerror
Adam Lesinski16c4d152014-01-24 13:27:13 -080046#include <strings.h>
Adam Lesinski16c4d152014-01-24 13:27:13 -080047
48#ifndef TEMP_FAILURE_RETRY
49/* Used to retry syscalls that can return EINTR. */
50#define TEMP_FAILURE_RETRY(exp) ({ \
51 typeof (exp) _rc; \
52 do { \
53 _rc = (exp); \
54 } while (_rc == -1 && errno == EINTR); \
55 _rc; })
56#endif
57
Adam Lesinski16c4d152014-01-24 13:27:13 -080058using namespace android;
59
Andreas Gampe2204f0b2014-10-21 23:04:54 -070060static const bool kIsDebug = false;
61
Adam Lesinski16c4d152014-01-24 13:27:13 -080062static const char* kAssetsRoot = "assets";
63static const char* kAppZipName = NULL; //"classes.jar";
64static const char* kSystemAssets = "framework/framework-res.apk";
Mårten Kongstad48d22322014-01-31 14:43:27 +010065static const char* kResourceCache = "resource-cache";
Adam Lesinski16c4d152014-01-24 13:27:13 -080066
67static const char* kExcludeExtension = ".EXCLUDE";
68
69static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
70
71static volatile int32_t gCount = 0;
72
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010073const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
Mårten Kongstad48d22322014-01-31 14:43:27 +010074const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
75const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
Jakub Adamek54dcaab2016-10-19 11:46:13 +010076const char* AssetManager::OVERLAY_THEME_DIR_PROPERTY = "ro.boot.vendor.overlay.theme";
Mårten Kongstad48d22322014-01-31 14:43:27 +010077const char* AssetManager::TARGET_PACKAGE_NAME = "android";
78const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
79const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010080
Adam Lesinski16c4d152014-01-24 13:27:13 -080081namespace {
Adam Lesinski16c4d152014-01-24 13:27:13 -080082
Adam Lesinskia77685f2016-10-03 16:26:28 -070083String8 idmapPathForPackagePath(const String8& pkgPath) {
84 const char* root = getenv("ANDROID_DATA");
85 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
86 String8 path(root);
87 path.appendPath(kResourceCache);
Adam Lesinski16c4d152014-01-24 13:27:13 -080088
Adam Lesinskia77685f2016-10-03 16:26:28 -070089 char buf[256]; // 256 chars should be enough for anyone...
90 strncpy(buf, pkgPath.string(), 255);
91 buf[255] = '\0';
92 char* filename = buf;
93 while (*filename && *filename == '/') {
94 ++filename;
Adam Lesinski16c4d152014-01-24 13:27:13 -080095 }
Adam Lesinskia77685f2016-10-03 16:26:28 -070096 char* p = filename;
97 while (*p) {
98 if (*p == '/') {
99 *p = '@';
100 }
101 ++p;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800102 }
Adam Lesinskia77685f2016-10-03 16:26:28 -0700103 path.appendPath(filename);
104 path.append("@idmap");
105
106 return path;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800107}
108
109/*
Adam Lesinskia77685f2016-10-03 16:26:28 -0700110 * Like strdup(), but uses C++ "new" operator instead of malloc.
111 */
112static char* strdupNew(const char* str) {
113 char* newStr;
114 int len;
115
116 if (str == NULL)
117 return NULL;
118
119 len = strlen(str);
120 newStr = new char[len+1];
121 memcpy(newStr, str, len+1);
122
123 return newStr;
124}
125
126} // namespace
127
128/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800129 * ===========================================================================
130 * AssetManager
131 * ===========================================================================
132 */
133
Adam Lesinskia77685f2016-10-03 16:26:28 -0700134int32_t AssetManager::getGlobalCount() {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800135 return gCount;
136}
137
Adam Lesinskia77685f2016-10-03 16:26:28 -0700138AssetManager::AssetManager() :
139 mLocale(NULL), mResources(NULL), mConfig(new ResTable_config) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700140 int count = android_atomic_inc(&gCount) + 1;
141 if (kIsDebug) {
142 ALOGI("Creating AssetManager %p #%d\n", this, count);
143 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800144 memset(mConfig, 0, sizeof(ResTable_config));
145}
146
Adam Lesinskia77685f2016-10-03 16:26:28 -0700147AssetManager::~AssetManager() {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800148 int count = android_atomic_dec(&gCount);
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700149 if (kIsDebug) {
150 ALOGI("Destroying AssetManager in %p #%d\n", this, count);
151 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800152
153 delete mConfig;
154 delete mResources;
155
156 // don't have a String class yet, so make sure we clean up
157 delete[] mLocale;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800158}
159
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800160bool AssetManager::addAssetPath(
Adam Lesinskia77685f2016-10-03 16:26:28 -0700161 const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800162 AutoMutex _l(mLock);
163
164 asset_path ap;
165
166 String8 realPath(path);
167 if (kAppZipName) {
168 realPath.appendPath(kAppZipName);
169 }
170 ap.type = ::getFileType(realPath.string());
171 if (ap.type == kFileTypeRegular) {
172 ap.path = realPath;
173 } else {
174 ap.path = path;
175 ap.type = ::getFileType(path.string());
176 if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
177 ALOGW("Asset path %s is neither a directory nor file (type=%d).",
178 path.string(), (int)ap.type);
179 return false;
180 }
181 }
182
183 // Skip if we have it already.
184 for (size_t i=0; i<mAssetPaths.size(); i++) {
185 if (mAssetPaths[i].path == ap.path) {
186 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000187 *cookie = static_cast<int32_t>(i+1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800188 }
189 return true;
190 }
191 }
192
193 ALOGV("In %p Asset %s path: %s", this,
194 ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
195
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800196 ap.isSystemAsset = isSystemAsset;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800197 mAssetPaths.add(ap);
198
199 // new paths are always added at the end
200 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000201 *cookie = static_cast<int32_t>(mAssetPaths.size());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800202 }
203
Elliott Hughesba3fe562015-08-12 14:49:53 -0700204#ifdef __ANDROID__
Mårten Kongstad48d22322014-01-31 14:43:27 +0100205 // Load overlays, if any
206 asset_path oap;
207 for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800208 oap.isSystemAsset = isSystemAsset;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100209 mAssetPaths.add(oap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800210 }
Mårten Kongstad48d22322014-01-31 14:43:27 +0100211#endif
Adam Lesinski16c4d152014-01-24 13:27:13 -0800212
Martin Kosiba7df36252014-01-16 16:25:56 +0000213 if (mResources != NULL) {
Tao Baia6d7e3f2015-09-01 18:49:54 -0700214 appendPathToResTable(ap, appAsLib);
Martin Kosiba7df36252014-01-16 16:25:56 +0000215 }
216
Adam Lesinski16c4d152014-01-24 13:27:13 -0800217 return true;
218}
219
Mårten Kongstad48d22322014-01-31 14:43:27 +0100220bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
221{
222 const String8 idmapPath = idmapPathForPackagePath(packagePath);
223
224 AutoMutex _l(mLock);
225
226 for (size_t i = 0; i < mAssetPaths.size(); ++i) {
227 if (mAssetPaths[i].idmap == idmapPath) {
228 *cookie = static_cast<int32_t>(i + 1);
229 return true;
230 }
231 }
232
233 Asset* idmap = NULL;
234 if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
235 ALOGW("failed to open idmap file %s\n", idmapPath.string());
236 return false;
237 }
238
239 String8 targetPath;
240 String8 overlayPath;
241 if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700242 NULL, NULL, NULL, &targetPath, &overlayPath)) {
Mårten Kongstad48d22322014-01-31 14:43:27 +0100243 ALOGW("failed to read idmap file %s\n", idmapPath.string());
244 delete idmap;
245 return false;
246 }
247 delete idmap;
248
249 if (overlayPath != packagePath) {
250 ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
251 idmapPath.string(), packagePath.string(), overlayPath.string());
252 return false;
253 }
254 if (access(targetPath.string(), R_OK) != 0) {
255 ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
256 return false;
257 }
258 if (access(idmapPath.string(), R_OK) != 0) {
259 ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
260 return false;
261 }
262 if (access(overlayPath.string(), R_OK) != 0) {
263 ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
264 return false;
265 }
266
267 asset_path oap;
268 oap.path = overlayPath;
269 oap.type = ::getFileType(overlayPath.string());
270 oap.idmap = idmapPath;
271#if 0
272 ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
273 targetPath.string(), overlayPath.string(), idmapPath.string());
274#endif
275 mAssetPaths.add(oap);
276 *cookie = static_cast<int32_t>(mAssetPaths.size());
277
Mårten Kongstad30113132014-11-07 10:52:17 +0100278 if (mResources != NULL) {
279 appendPathToResTable(oap);
280 }
281
Mårten Kongstad48d22322014-01-31 14:43:27 +0100282 return true;
283 }
284
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100285bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
Dianne Hackborn32bb5fa2014-02-11 13:56:21 -0800286 uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100287{
288 AutoMutex _l(mLock);
289 const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
290 ResTable tables[2];
291
292 for (int i = 0; i < 2; ++i) {
293 asset_path ap;
294 ap.type = kFileTypeRegular;
295 ap.path = paths[i];
296 Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
297 if (ass == NULL) {
298 ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
299 return false;
300 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700301 tables[i].add(ass);
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100302 }
303
304 return tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
305 targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
306}
307
Adam Lesinski16c4d152014-01-24 13:27:13 -0800308bool AssetManager::addDefaultAssets()
309{
310 const char* root = getenv("ANDROID_ROOT");
311 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
312
313 String8 path(root);
314 path.appendPath(kSystemAssets);
315
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800316 return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800317}
318
Narayan Kamatha0c62602014-01-24 13:51:51 +0000319int32_t AssetManager::nextAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800320{
321 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000322 const size_t next = static_cast<size_t>(cookie) + 1;
323 return next > mAssetPaths.size() ? -1 : next;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800324}
325
Narayan Kamatha0c62602014-01-24 13:51:51 +0000326String8 AssetManager::getAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800327{
328 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000329 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800330 if (which < mAssetPaths.size()) {
331 return mAssetPaths[which].path;
332 }
333 return String8();
334}
335
Adam Lesinski16c4d152014-01-24 13:27:13 -0800336void AssetManager::setLocaleLocked(const char* locale)
337{
338 if (mLocale != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800339 delete[] mLocale;
340 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700341
Adam Lesinski16c4d152014-01-24 13:27:13 -0800342 mLocale = strdupNew(locale);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800343 updateResourceParamsLocked();
344}
345
Adam Lesinski16c4d152014-01-24 13:27:13 -0800346void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
347{
348 AutoMutex _l(mLock);
349 *mConfig = config;
350 if (locale) {
351 setLocaleLocked(locale);
352 } else if (config.language[0] != 0) {
Narayan Kamath91447d82014-01-21 15:32:36 +0000353 char spec[RESTABLE_MAX_LOCALE_LEN];
354 config.getBcp47Locale(spec);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800355 setLocaleLocked(spec);
356 } else {
357 updateResourceParamsLocked();
358 }
359}
360
361void AssetManager::getConfiguration(ResTable_config* outConfig) const
362{
363 AutoMutex _l(mLock);
364 *outConfig = *mConfig;
365}
366
367/*
368 * Open an asset.
369 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700370 * The data could be in any asset path. Each asset path could be:
371 * - A directory on disk.
372 * - A Zip archive, uncompressed or compressed.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800373 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700374 * If the file is in a directory, it could have a .gz suffix, meaning it is compressed.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800375 *
376 * We should probably reject requests for "illegal" filenames, e.g. those
377 * with illegal characters or "../" backward relative paths.
378 */
379Asset* AssetManager::open(const char* fileName, AccessMode mode)
380{
381 AutoMutex _l(mLock);
382
383 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
384
Adam Lesinski16c4d152014-01-24 13:27:13 -0800385 String8 assetName(kAssetsRoot);
386 assetName.appendPath(fileName);
387
388 /*
389 * For each top-level asset path, search for the asset.
390 */
391
392 size_t i = mAssetPaths.size();
393 while (i > 0) {
394 i--;
395 ALOGV("Looking for asset '%s' in '%s'\n",
396 assetName.string(), mAssetPaths.itemAt(i).path.string());
397 Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
398 if (pAsset != NULL) {
399 return pAsset != kExcludedAsset ? pAsset : NULL;
400 }
401 }
402
403 return NULL;
404}
405
406/*
407 * Open a non-asset file as if it were an asset.
408 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700409 * The "fileName" is the partial path starting from the application name.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800410 */
Adam Lesinskide898ff2014-01-29 18:20:45 -0800411Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800412{
413 AutoMutex _l(mLock);
414
415 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
416
Adam Lesinski16c4d152014-01-24 13:27:13 -0800417 /*
418 * For each top-level asset path, search for the asset.
419 */
420
421 size_t i = mAssetPaths.size();
422 while (i > 0) {
423 i--;
424 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
425 Asset* pAsset = openNonAssetInPathLocked(
426 fileName, mode, mAssetPaths.itemAt(i));
427 if (pAsset != NULL) {
Adam Lesinskide898ff2014-01-29 18:20:45 -0800428 if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800429 return pAsset != kExcludedAsset ? pAsset : NULL;
430 }
431 }
432
433 return NULL;
434}
435
Narayan Kamatha0c62602014-01-24 13:51:51 +0000436Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800437{
Narayan Kamatha0c62602014-01-24 13:51:51 +0000438 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800439
440 AutoMutex _l(mLock);
441
442 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
443
Adam Lesinski16c4d152014-01-24 13:27:13 -0800444 if (which < mAssetPaths.size()) {
445 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
446 mAssetPaths.itemAt(which).path.string());
447 Asset* pAsset = openNonAssetInPathLocked(
448 fileName, mode, mAssetPaths.itemAt(which));
449 if (pAsset != NULL) {
450 return pAsset != kExcludedAsset ? pAsset : NULL;
451 }
452 }
453
454 return NULL;
455}
456
457/*
458 * Get the type of a file in the asset namespace.
459 *
460 * This currently only works for regular files. All others (including
461 * directories) will return kFileTypeNonexistent.
462 */
463FileType AssetManager::getFileType(const char* fileName)
464{
465 Asset* pAsset = NULL;
466
467 /*
468 * Open the asset. This is less efficient than simply finding the
469 * file, but it's not too bad (we don't uncompress or mmap data until
470 * the first read() call).
471 */
472 pAsset = open(fileName, Asset::ACCESS_STREAMING);
473 delete pAsset;
474
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700475 if (pAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800476 return kFileTypeNonexistent;
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700477 } else {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800478 return kFileTypeRegular;
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700479 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800480}
481
Tao Baia6d7e3f2015-09-01 18:49:54 -0700482bool AssetManager::appendPathToResTable(const asset_path& ap, bool appAsLib) const {
Mårten Kongstadcb7b63d2014-11-07 10:57:15 +0100483 // skip those ap's that correspond to system overlays
484 if (ap.isSystemOverlay) {
485 return true;
486 }
487
Martin Kosiba7df36252014-01-16 16:25:56 +0000488 Asset* ass = NULL;
489 ResTable* sharedRes = NULL;
490 bool shared = true;
491 bool onlyEmptyResources = true;
Adam Lesinskib7e1ce02016-04-11 20:03:01 -0700492 ATRACE_NAME(ap.path.string());
Martin Kosiba7df36252014-01-16 16:25:56 +0000493 Asset* idmap = openIdmapLocked(ap);
494 size_t nextEntryIdx = mResources->getTableCount();
495 ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
496 if (ap.type != kFileTypeDirectory) {
497 if (nextEntryIdx == 0) {
498 // The first item is typically the framework resources,
499 // which we want to avoid parsing every time.
500 sharedRes = const_cast<AssetManager*>(this)->
501 mZipSet.getZipResourceTable(ap.path);
502 if (sharedRes != NULL) {
503 // skip ahead the number of system overlay packages preloaded
504 nextEntryIdx = sharedRes->getTableCount();
505 }
506 }
507 if (sharedRes == NULL) {
508 ass = const_cast<AssetManager*>(this)->
509 mZipSet.getZipResourceTableAsset(ap.path);
510 if (ass == NULL) {
511 ALOGV("loading resource table %s\n", ap.path.string());
512 ass = const_cast<AssetManager*>(this)->
513 openNonAssetInPathLocked("resources.arsc",
514 Asset::ACCESS_BUFFER,
515 ap);
516 if (ass != NULL && ass != kExcludedAsset) {
517 ass = const_cast<AssetManager*>(this)->
518 mZipSet.setZipResourceTableAsset(ap.path, ass);
519 }
520 }
521
522 if (nextEntryIdx == 0 && ass != NULL) {
523 // If this is the first resource table in the asset
524 // manager, then we are going to cache it so that we
525 // can quickly copy it out for others.
526 ALOGV("Creating shared resources for %s", ap.path.string());
527 sharedRes = new ResTable();
528 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
Elliott Hughesba3fe562015-08-12 14:49:53 -0700529#ifdef __ANDROID__
Martin Kosiba7df36252014-01-16 16:25:56 +0000530 const char* data = getenv("ANDROID_DATA");
531 LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
532 String8 overlaysListPath(data);
533 overlaysListPath.appendPath(kResourceCache);
534 overlaysListPath.appendPath("overlays.list");
535 addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
536#endif
537 sharedRes = const_cast<AssetManager*>(this)->
538 mZipSet.setZipResourceTable(ap.path, sharedRes);
539 }
540 }
541 } else {
542 ALOGV("loading resource table %s\n", ap.path.string());
543 ass = const_cast<AssetManager*>(this)->
544 openNonAssetInPathLocked("resources.arsc",
545 Asset::ACCESS_BUFFER,
546 ap);
547 shared = false;
548 }
549
550 if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
551 ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
552 if (sharedRes != NULL) {
553 ALOGV("Copying existing resources for %s", ap.path.string());
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800554 mResources->add(sharedRes, ap.isSystemAsset);
Martin Kosiba7df36252014-01-16 16:25:56 +0000555 } else {
556 ALOGV("Parsing resources for %s", ap.path.string());
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800557 mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
Martin Kosiba7df36252014-01-16 16:25:56 +0000558 }
559 onlyEmptyResources = false;
560
561 if (!shared) {
562 delete ass;
563 }
564 } else {
565 ALOGV("Installing empty resources in to table %p\n", mResources);
566 mResources->addEmpty(nextEntryIdx + 1);
567 }
568
569 if (idmap != NULL) {
570 delete idmap;
571 }
Martin Kosiba7df36252014-01-16 16:25:56 +0000572 return onlyEmptyResources;
573}
574
Adam Lesinski16c4d152014-01-24 13:27:13 -0800575const ResTable* AssetManager::getResTable(bool required) const
576{
577 ResTable* rt = mResources;
578 if (rt) {
579 return rt;
580 }
581
582 // Iterate through all asset packages, collecting resources from each.
583
584 AutoMutex _l(mLock);
585
586 if (mResources != NULL) {
587 return mResources;
588 }
589
590 if (required) {
591 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
592 }
593
Adam Lesinskide898ff2014-01-29 18:20:45 -0800594 mResources = new ResTable();
595 updateResourceParamsLocked();
596
597 bool onlyEmptyResources = true;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800598 const size_t N = mAssetPaths.size();
599 for (size_t i=0; i<N; i++) {
Martin Kosiba7df36252014-01-16 16:25:56 +0000600 bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
601 onlyEmptyResources = onlyEmptyResources && empty;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800602 }
603
Adam Lesinskide898ff2014-01-29 18:20:45 -0800604 if (required && onlyEmptyResources) {
605 ALOGW("Unable to find resources file resources.arsc");
606 delete mResources;
607 mResources = NULL;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800608 }
Adam Lesinskide898ff2014-01-29 18:20:45 -0800609
610 return mResources;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800611}
612
613void AssetManager::updateResourceParamsLocked() const
614{
Adam Lesinskib7e1ce02016-04-11 20:03:01 -0700615 ATRACE_CALL();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800616 ResTable* res = mResources;
617 if (!res) {
618 return;
619 }
620
Narayan Kamath91447d82014-01-21 15:32:36 +0000621 if (mLocale) {
622 mConfig->setBcp47Locale(mLocale);
623 } else {
624 mConfig->clearLocale();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800625 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800626
627 res->setParameters(mConfig);
628}
629
630Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
631{
632 Asset* ass = NULL;
633 if (ap.idmap.size() != 0) {
634 ass = const_cast<AssetManager*>(this)->
635 openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
636 if (ass) {
637 ALOGV("loading idmap %s\n", ap.idmap.string());
638 } else {
639 ALOGW("failed to load idmap %s\n", ap.idmap.string());
640 }
641 }
642 return ass;
643}
644
Mårten Kongstad48d22322014-01-31 14:43:27 +0100645void AssetManager::addSystemOverlays(const char* pathOverlaysList,
646 const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
647{
648 FILE* fin = fopen(pathOverlaysList, "r");
649 if (fin == NULL) {
650 return;
651 }
652
Martin Wallgren0fbb6082015-08-11 15:10:31 +0200653#ifndef _WIN32
654 if (TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_SH)) != 0) {
655 fclose(fin);
656 return;
657 }
658#endif
Mårten Kongstad48d22322014-01-31 14:43:27 +0100659 char buf[1024];
660 while (fgets(buf, sizeof(buf), fin)) {
661 // format of each line:
662 // <path to apk><space><path to idmap><newline>
663 char* space = strchr(buf, ' ');
664 char* newline = strchr(buf, '\n');
665 asset_path oap;
666
667 if (space == NULL || newline == NULL || newline < space) {
668 continue;
669 }
670
671 oap.path = String8(buf, space - buf);
672 oap.type = kFileTypeRegular;
673 oap.idmap = String8(space + 1, newline - space - 1);
Mårten Kongstadcb7b63d2014-11-07 10:57:15 +0100674 oap.isSystemOverlay = true;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100675
676 Asset* oass = const_cast<AssetManager*>(this)->
677 openNonAssetInPathLocked("resources.arsc",
678 Asset::ACCESS_BUFFER,
679 oap);
680
681 if (oass != NULL) {
682 Asset* oidmap = openIdmapLocked(oap);
683 offset++;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700684 sharedRes->add(oass, oidmap, offset + 1, false);
Mårten Kongstad48d22322014-01-31 14:43:27 +0100685 const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
686 const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
687 }
688 }
Martin Wallgren0fbb6082015-08-11 15:10:31 +0200689
690#ifndef _WIN32
691 TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_UN));
692#endif
Mårten Kongstad48d22322014-01-31 14:43:27 +0100693 fclose(fin);
694}
695
Adam Lesinski16c4d152014-01-24 13:27:13 -0800696const ResTable& AssetManager::getResources(bool required) const
697{
698 const ResTable* rt = getResTable(required);
699 return *rt;
700}
701
702bool AssetManager::isUpToDate()
703{
704 AutoMutex _l(mLock);
705 return mZipSet.isUpToDate();
706}
707
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800708void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800709{
710 ResTable* res = mResources;
711 if (res != NULL) {
Roozbeh Pournader7e5f96f2016-06-13 18:10:49 -0700712 res->getLocales(locales, includeSystemLocales, true /* mergeEquivalentLangs */);
Narayan Kamathe4345db2014-06-26 16:01:28 +0100713 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800714}
715
716/*
717 * Open a non-asset file as if it were an asset, searching for it in the
718 * specified app.
719 *
720 * Pass in a NULL values for "appName" if the common app directory should
721 * be used.
722 */
723Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
724 const asset_path& ap)
725{
726 Asset* pAsset = NULL;
727
728 /* look at the filesystem on disk */
729 if (ap.type == kFileTypeDirectory) {
730 String8 path(ap.path);
731 path.appendPath(fileName);
732
733 pAsset = openAssetFromFileLocked(path, mode);
734
735 if (pAsset == NULL) {
736 /* try again, this time with ".gz" */
737 path.append(".gz");
738 pAsset = openAssetFromFileLocked(path, mode);
739 }
740
741 if (pAsset != NULL) {
742 //printf("FOUND NA '%s' on disk\n", fileName);
743 pAsset->setAssetSource(path);
744 }
745
746 /* look inside the zip file */
747 } else {
748 String8 path(fileName);
749
750 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +0000751 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800752 if (pZip != NULL) {
753 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000754 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800755 if (entry != NULL) {
756 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
757 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000758 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800759 }
760 }
761
762 if (pAsset != NULL) {
763 /* create a "source" name, for debug/display */
764 pAsset->setAssetSource(
765 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
766 String8(fileName)));
767 }
768 }
769
770 return pAsset;
771}
772
773/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800774 * Create a "source name" for a file from a Zip archive.
775 */
776String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
777 const String8& dirName, const String8& fileName)
778{
779 String8 sourceName("zip:");
780 sourceName.append(zipFileName);
781 sourceName.append(":");
782 if (dirName.length() > 0) {
783 sourceName.appendPath(dirName);
784 }
785 sourceName.appendPath(fileName);
786 return sourceName;
787}
788
789/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800790 * Create a path to a loose asset (asset-base/app/rootDir).
791 */
792String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
793{
794 String8 path(ap.path);
795 if (rootDir != NULL) path.appendPath(rootDir);
796 return path;
797}
798
799/*
800 * Return a pointer to one of our open Zip archives. Returns NULL if no
801 * matching Zip file exists.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800802 */
803ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
804{
805 ALOGV("getZipFileLocked() in %p\n", this);
806
807 return mZipSet.getZip(ap.path);
808}
809
810/*
811 * Try to open an asset from a file on disk.
812 *
813 * If the file is compressed with gzip, we seek to the start of the
814 * deflated data and pass that in (just like we would for a Zip archive).
815 *
816 * For uncompressed data, we may already have an mmap()ed version sitting
817 * around. If so, we want to hand that to the Asset instead.
818 *
819 * This returns NULL if the file doesn't exist, couldn't be opened, or
820 * claims to be a ".gz" but isn't.
821 */
822Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
823 AccessMode mode)
824{
825 Asset* pAsset = NULL;
826
827 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
828 //printf("TRYING '%s'\n", (const char*) pathName);
829 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
830 } else {
831 //printf("TRYING '%s'\n", (const char*) pathName);
832 pAsset = Asset::createFromFile(pathName.string(), mode);
833 }
834
835 return pAsset;
836}
837
838/*
839 * Given an entry in a Zip archive, create a new Asset object.
840 *
841 * If the entry is uncompressed, we may want to create or share a
842 * slice of shared memory.
843 */
844Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
845 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
846{
847 Asset* pAsset = NULL;
848
849 // TODO: look for previously-created shared memory slice?
Narayan Kamath407753c2015-06-16 12:02:57 +0100850 uint16_t method;
851 uint32_t uncompressedLen;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800852
853 //printf("USING Zip '%s'\n", pEntry->getFileName());
854
Adam Lesinski16c4d152014-01-24 13:27:13 -0800855 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
856 NULL, NULL))
857 {
858 ALOGW("getEntryInfo failed\n");
859 return NULL;
860 }
861
862 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
863 if (dataMap == NULL) {
864 ALOGW("create map from entry failed\n");
865 return NULL;
866 }
867
868 if (method == ZipFileRO::kCompressStored) {
869 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
870 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
871 dataMap->getFileName(), mode, pAsset);
872 } else {
Narayan Kamath407753c2015-06-16 12:02:57 +0100873 pAsset = Asset::createFromCompressedMap(dataMap,
874 static_cast<size_t>(uncompressedLen), mode);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800875 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
876 dataMap->getFileName(), mode, pAsset);
877 }
878 if (pAsset == NULL) {
879 /* unexpected */
880 ALOGW("create from segment failed\n");
881 }
882
883 return pAsset;
884}
885
Adam Lesinski16c4d152014-01-24 13:27:13 -0800886/*
887 * Open a directory in the asset namespace.
888 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700889 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800890 *
891 * Pass in "" for the root dir.
892 */
893AssetDir* AssetManager::openDir(const char* dirName)
894{
895 AutoMutex _l(mLock);
896
897 AssetDir* pDir = NULL;
898 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
899
900 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
901 assert(dirName != NULL);
902
903 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
904
Adam Lesinski16c4d152014-01-24 13:27:13 -0800905 pDir = new AssetDir;
906
907 /*
908 * Scan the various directories, merging what we find into a single
909 * vector. We want to scan them in reverse priority order so that
910 * the ".EXCLUDE" processing works correctly. Also, if we decide we
911 * want to remember where the file is coming from, we'll get the right
912 * version.
913 *
914 * We start with Zip archives, then do loose files.
915 */
916 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
917
918 size_t i = mAssetPaths.size();
919 while (i > 0) {
920 i--;
921 const asset_path& ap = mAssetPaths.itemAt(i);
922 if (ap.type == kFileTypeRegular) {
923 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
924 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
925 } else {
926 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
927 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
928 }
929 }
930
931#if 0
932 printf("FILE LIST:\n");
933 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
934 printf(" %d: (%d) '%s'\n", i,
935 pMergedInfo->itemAt(i).getFileType(),
936 (const char*) pMergedInfo->itemAt(i).getFileName());
937 }
938#endif
939
940 pDir->setFileList(pMergedInfo);
941 return pDir;
942}
943
944/*
945 * Open a directory in the non-asset namespace.
946 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700947 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800948 *
949 * Pass in "" for the root dir.
950 */
Narayan Kamatha0c62602014-01-24 13:51:51 +0000951AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800952{
953 AutoMutex _l(mLock);
954
955 AssetDir* pDir = NULL;
956 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
957
958 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
959 assert(dirName != NULL);
960
961 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
962
Adam Lesinski16c4d152014-01-24 13:27:13 -0800963 pDir = new AssetDir;
964
965 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
966
Narayan Kamatha0c62602014-01-24 13:51:51 +0000967 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800968
969 if (which < mAssetPaths.size()) {
970 const asset_path& ap = mAssetPaths.itemAt(which);
971 if (ap.type == kFileTypeRegular) {
972 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
973 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
974 } else {
975 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
976 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
977 }
978 }
979
980#if 0
981 printf("FILE LIST:\n");
982 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
983 printf(" %d: (%d) '%s'\n", i,
984 pMergedInfo->itemAt(i).getFileType(),
985 (const char*) pMergedInfo->itemAt(i).getFileName());
986 }
987#endif
988
989 pDir->setFileList(pMergedInfo);
990 return pDir;
991}
992
993/*
994 * Scan the contents of the specified directory and merge them into the
995 * "pMergedInfo" vector, removing previous entries if we find "exclude"
996 * directives.
997 *
998 * Returns "false" if we found nothing to contribute.
999 */
1000bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1001 const asset_path& ap, const char* rootDir, const char* dirName)
1002{
Adam Lesinski16c4d152014-01-24 13:27:13 -08001003 assert(pMergedInfo != NULL);
1004
Adam Lesinskia77685f2016-10-03 16:26:28 -07001005 //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001006
Adam Lesinskia77685f2016-10-03 16:26:28 -07001007 String8 path = createPathNameLocked(ap, rootDir);
1008 if (dirName[0] != '\0')
1009 path.appendPath(dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001010
Adam Lesinskia77685f2016-10-03 16:26:28 -07001011 SortedVector<AssetDir::FileInfo>* pContents = scanDirLocked(path);
1012 if (pContents == NULL)
1013 return false;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001014
1015 // if we wanted to do an incremental cache fill, we would do it here
1016
1017 /*
1018 * Process "exclude" directives. If we find a filename that ends with
1019 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1020 * remove it if we find it. We also delete the "exclude" entry.
1021 */
1022 int i, count, exclExtLen;
1023
1024 count = pContents->size();
1025 exclExtLen = strlen(kExcludeExtension);
1026 for (i = 0; i < count; i++) {
1027 const char* name;
1028 int nameLen;
1029
1030 name = pContents->itemAt(i).getFileName().string();
1031 nameLen = strlen(name);
1032 if (nameLen > exclExtLen &&
1033 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1034 {
1035 String8 match(name, nameLen - exclExtLen);
1036 int matchIdx;
1037
1038 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1039 if (matchIdx > 0) {
1040 ALOGV("Excluding '%s' [%s]\n",
1041 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1042 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1043 pMergedInfo->removeAt(matchIdx);
1044 } else {
1045 //printf("+++ no match on '%s'\n", (const char*) match);
1046 }
1047
1048 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1049 pContents->removeAt(i);
1050 i--; // adjust "for" loop
1051 count--; // and loop limit
1052 }
1053 }
1054
1055 mergeInfoLocked(pMergedInfo, pContents);
1056
1057 delete pContents;
1058
1059 return true;
1060}
1061
1062/*
1063 * Scan the contents of the specified directory, and stuff what we find
1064 * into a newly-allocated vector.
1065 *
1066 * Files ending in ".gz" will have their extensions removed.
1067 *
1068 * We should probably think about skipping files with "illegal" names,
1069 * e.g. illegal characters (/\:) or excessive length.
1070 *
1071 * Returns NULL if the specified directory doesn't exist.
1072 */
1073SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1074{
1075 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1076 DIR* dir;
1077 struct dirent* entry;
1078 FileType fileType;
1079
1080 ALOGV("Scanning dir '%s'\n", path.string());
1081
1082 dir = opendir(path.string());
1083 if (dir == NULL)
1084 return NULL;
1085
1086 pContents = new SortedVector<AssetDir::FileInfo>;
1087
1088 while (1) {
1089 entry = readdir(dir);
1090 if (entry == NULL)
1091 break;
1092
1093 if (strcmp(entry->d_name, ".") == 0 ||
1094 strcmp(entry->d_name, "..") == 0)
1095 continue;
1096
1097#ifdef _DIRENT_HAVE_D_TYPE
1098 if (entry->d_type == DT_REG)
1099 fileType = kFileTypeRegular;
1100 else if (entry->d_type == DT_DIR)
1101 fileType = kFileTypeDirectory;
1102 else
1103 fileType = kFileTypeUnknown;
1104#else
1105 // stat the file
1106 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1107#endif
1108
1109 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1110 continue;
1111
1112 AssetDir::FileInfo info;
1113 info.set(String8(entry->d_name), fileType);
1114 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1115 info.setFileName(info.getFileName().getBasePath());
1116 info.setSourceName(path.appendPathCopy(info.getFileName()));
1117 pContents->add(info);
1118 }
1119
1120 closedir(dir);
1121 return pContents;
1122}
1123
1124/*
1125 * Scan the contents out of the specified Zip archive, and merge what we
1126 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1127 * we return immediately.
1128 *
1129 * Returns "false" if we found nothing to contribute.
1130 */
1131bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1132 const asset_path& ap, const char* rootDir, const char* baseDirName)
1133{
1134 ZipFileRO* pZip;
1135 Vector<String8> dirs;
1136 AssetDir::FileInfo info;
1137 SortedVector<AssetDir::FileInfo> contents;
1138 String8 sourceName, zipName, dirName;
1139
1140 pZip = mZipSet.getZip(ap.path);
1141 if (pZip == NULL) {
1142 ALOGW("Failure opening zip %s\n", ap.path.string());
1143 return false;
1144 }
1145
1146 zipName = ZipSet::getPathName(ap.path.string());
1147
1148 /* convert "sounds" to "rootDir/sounds" */
1149 if (rootDir != NULL) dirName = rootDir;
1150 dirName.appendPath(baseDirName);
1151
1152 /*
1153 * Scan through the list of files, looking for a match. The files in
1154 * the Zip table of contents are not in sorted order, so we have to
1155 * process the entire list. We're looking for a string that begins
1156 * with the characters in "dirName", is followed by a '/', and has no
1157 * subsequent '/' in the stuff that follows.
1158 *
1159 * What makes this especially fun is that directories are not stored
1160 * explicitly in Zip archives, so we have to infer them from context.
1161 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1162 * to insert a directory called "sounds" into the list. We store
1163 * these in temporary vector so that we only return each one once.
1164 *
1165 * Name comparisons are case-sensitive to match UNIX filesystem
1166 * semantics.
1167 */
1168 int dirNameLen = dirName.length();
Narayan Kamath560566d2013-12-03 13:16:03 +00001169 void *iterationCookie;
Yusuke Sato05f648e2015-08-03 16:21:10 -07001170 if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
Narayan Kamath560566d2013-12-03 13:16:03 +00001171 ALOGW("ZipFileRO::startIteration returned false");
1172 return false;
1173 }
1174
1175 ZipEntryRO entry;
1176 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001177 char nameBuf[256];
1178
Adam Lesinski16c4d152014-01-24 13:27:13 -08001179 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1180 // TODO: fix this if we expect to have long names
1181 ALOGE("ARGH: name too long?\n");
1182 continue;
1183 }
1184 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
Yusuke Sato05f648e2015-08-03 16:21:10 -07001185 if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
Adam Lesinski16c4d152014-01-24 13:27:13 -08001186 {
1187 const char* cp;
1188 const char* nextSlash;
1189
1190 cp = nameBuf + dirNameLen;
1191 if (dirNameLen != 0)
1192 cp++; // advance past the '/'
1193
1194 nextSlash = strchr(cp, '/');
1195//xxx this may break if there are bare directory entries
1196 if (nextSlash == NULL) {
1197 /* this is a file in the requested directory */
1198
1199 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1200
1201 info.setSourceName(
1202 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1203
1204 contents.add(info);
1205 //printf("FOUND: file '%s'\n", info.getFileName().string());
1206 } else {
1207 /* this is a subdir; add it if we don't already have it*/
1208 String8 subdirName(cp, nextSlash - cp);
1209 size_t j;
1210 size_t N = dirs.size();
1211
1212 for (j = 0; j < N; j++) {
1213 if (subdirName == dirs[j]) {
1214 break;
1215 }
1216 }
1217 if (j == N) {
1218 dirs.add(subdirName);
1219 }
1220
1221 //printf("FOUND: dir '%s'\n", subdirName.string());
1222 }
1223 }
1224 }
1225
Narayan Kamath560566d2013-12-03 13:16:03 +00001226 pZip->endIteration(iterationCookie);
1227
Adam Lesinski16c4d152014-01-24 13:27:13 -08001228 /*
1229 * Add the set of unique directories.
1230 */
1231 for (int i = 0; i < (int) dirs.size(); i++) {
1232 info.set(dirs[i], kFileTypeDirectory);
1233 info.setSourceName(
1234 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1235 contents.add(info);
1236 }
1237
1238 mergeInfoLocked(pMergedInfo, &contents);
1239
1240 return true;
1241}
1242
1243
1244/*
1245 * Merge two vectors of FileInfo.
1246 *
1247 * The merged contents will be stuffed into *pMergedInfo.
1248 *
1249 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1250 * we use the newer "pContents" entry.
1251 */
1252void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1253 const SortedVector<AssetDir::FileInfo>* pContents)
1254{
1255 /*
1256 * Merge what we found in this directory with what we found in
1257 * other places.
1258 *
1259 * Two basic approaches:
1260 * (1) Create a new array that holds the unique values of the two
1261 * arrays.
1262 * (2) Take the elements from pContents and shove them into pMergedInfo.
1263 *
1264 * Because these are vectors of complex objects, moving elements around
1265 * inside the vector requires constructing new objects and allocating
1266 * storage for members. With approach #1, we're always adding to the
1267 * end, whereas with #2 we could be inserting multiple elements at the
1268 * front of the vector. Approach #1 requires a full copy of the
1269 * contents of pMergedInfo, but approach #2 requires the same copy for
1270 * every insertion at the front of pMergedInfo.
1271 *
1272 * (We should probably use a SortedVector interface that allows us to
1273 * just stuff items in, trusting us to maintain the sort order.)
1274 */
1275 SortedVector<AssetDir::FileInfo>* pNewSorted;
1276 int mergeMax, contMax;
1277 int mergeIdx, contIdx;
1278
1279 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1280 mergeMax = pMergedInfo->size();
1281 contMax = pContents->size();
1282 mergeIdx = contIdx = 0;
1283
1284 while (mergeIdx < mergeMax || contIdx < contMax) {
1285 if (mergeIdx == mergeMax) {
1286 /* hit end of "merge" list, copy rest of "contents" */
1287 pNewSorted->add(pContents->itemAt(contIdx));
1288 contIdx++;
1289 } else if (contIdx == contMax) {
1290 /* hit end of "cont" list, copy rest of "merge" */
1291 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1292 mergeIdx++;
1293 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1294 {
1295 /* items are identical, add newer and advance both indices */
1296 pNewSorted->add(pContents->itemAt(contIdx));
1297 mergeIdx++;
1298 contIdx++;
1299 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1300 {
1301 /* "merge" is lower, add that one */
1302 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1303 mergeIdx++;
1304 } else {
1305 /* "cont" is lower, add that one */
1306 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1307 pNewSorted->add(pContents->itemAt(contIdx));
1308 contIdx++;
1309 }
1310 }
1311
1312 /*
1313 * Overwrite the "merged" list with the new stuff.
1314 */
1315 *pMergedInfo = *pNewSorted;
1316 delete pNewSorted;
1317
1318#if 0 // for Vector, rather than SortedVector
1319 int i, j;
1320 for (i = pContents->size() -1; i >= 0; i--) {
1321 bool add = true;
1322
1323 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1324 /* case-sensitive comparisons, to behave like UNIX fs */
1325 if (strcmp(pContents->itemAt(i).mFileName,
1326 pMergedInfo->itemAt(j).mFileName) == 0)
1327 {
1328 /* match, don't add this entry */
1329 add = false;
1330 break;
1331 }
1332 }
1333
1334 if (add)
1335 pMergedInfo->add(pContents->itemAt(i));
1336 }
1337#endif
1338}
1339
Adam Lesinski16c4d152014-01-24 13:27:13 -08001340/*
1341 * ===========================================================================
1342 * AssetManager::SharedZip
1343 * ===========================================================================
1344 */
1345
1346
1347Mutex AssetManager::SharedZip::gLock;
1348DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1349
1350AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1351 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1352 mResourceTableAsset(NULL), mResourceTable(NULL)
1353{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001354 if (kIsDebug) {
1355 ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1356 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001357 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamath560566d2013-12-03 13:16:03 +00001358 mZipFile = ZipFileRO::open(mPath.string());
1359 if (mZipFile == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001360 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001361 }
1362}
1363
Mårten Kongstad48d22322014-01-31 14:43:27 +01001364sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1365 bool createIfNotPresent)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001366{
1367 AutoMutex _l(gLock);
1368 time_t modWhen = getFileModDate(path);
1369 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1370 if (zip != NULL && zip->mModWhen == modWhen) {
1371 return zip;
1372 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001373 if (zip == NULL && !createIfNotPresent) {
1374 return NULL;
1375 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001376 zip = new SharedZip(path, modWhen);
1377 gOpen.add(path, zip);
1378 return zip;
1379
1380}
1381
1382ZipFileRO* AssetManager::SharedZip::getZip()
1383{
1384 return mZipFile;
1385}
1386
1387Asset* AssetManager::SharedZip::getResourceTableAsset()
1388{
songjinshi49921f22016-09-08 15:24:30 +08001389 AutoMutex _l(gLock);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001390 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1391 return mResourceTableAsset;
1392}
1393
1394Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1395{
1396 {
1397 AutoMutex _l(gLock);
1398 if (mResourceTableAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001399 // This is not thread safe the first time it is called, so
1400 // do it here with the global lock held.
1401 asset->getBuffer(true);
songjinshi49921f22016-09-08 15:24:30 +08001402 mResourceTableAsset = asset;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001403 return asset;
1404 }
1405 }
1406 delete asset;
1407 return mResourceTableAsset;
1408}
1409
1410ResTable* AssetManager::SharedZip::getResourceTable()
1411{
1412 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1413 return mResourceTable;
1414}
1415
1416ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1417{
1418 {
1419 AutoMutex _l(gLock);
1420 if (mResourceTable == NULL) {
1421 mResourceTable = res;
1422 return res;
1423 }
1424 }
1425 delete res;
1426 return mResourceTable;
1427}
1428
1429bool AssetManager::SharedZip::isUpToDate()
1430{
1431 time_t modWhen = getFileModDate(mPath.string());
1432 return mModWhen == modWhen;
1433}
1434
Mårten Kongstad48d22322014-01-31 14:43:27 +01001435void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1436{
1437 mOverlays.add(ap);
1438}
1439
1440bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1441{
1442 if (idx >= mOverlays.size()) {
1443 return false;
1444 }
1445 *out = mOverlays[idx];
1446 return true;
1447}
1448
Adam Lesinski16c4d152014-01-24 13:27:13 -08001449AssetManager::SharedZip::~SharedZip()
1450{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001451 if (kIsDebug) {
1452 ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1453 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001454 if (mResourceTable != NULL) {
1455 delete mResourceTable;
1456 }
1457 if (mResourceTableAsset != NULL) {
1458 delete mResourceTableAsset;
1459 }
1460 if (mZipFile != NULL) {
1461 delete mZipFile;
1462 ALOGV("Closed '%s'\n", mPath.string());
1463 }
1464}
1465
1466/*
1467 * ===========================================================================
1468 * AssetManager::ZipSet
1469 * ===========================================================================
1470 */
1471
1472/*
Adam Lesinski16c4d152014-01-24 13:27:13 -08001473 * Destructor. Close any open archives.
1474 */
1475AssetManager::ZipSet::~ZipSet(void)
1476{
1477 size_t N = mZipFile.size();
1478 for (size_t i = 0; i < N; i++)
1479 closeZip(i);
1480}
1481
1482/*
1483 * Close a Zip file and reset the entry.
1484 */
1485void AssetManager::ZipSet::closeZip(int idx)
1486{
1487 mZipFile.editItemAt(idx) = NULL;
1488}
1489
1490
1491/*
1492 * Retrieve the appropriate Zip file from the set.
1493 */
1494ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1495{
1496 int idx = getIndex(path);
1497 sp<SharedZip> zip = mZipFile[idx];
1498 if (zip == NULL) {
1499 zip = SharedZip::get(path);
1500 mZipFile.editItemAt(idx) = zip;
1501 }
1502 return zip->getZip();
1503}
1504
1505Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
1506{
1507 int idx = getIndex(path);
1508 sp<SharedZip> zip = mZipFile[idx];
1509 if (zip == NULL) {
1510 zip = SharedZip::get(path);
1511 mZipFile.editItemAt(idx) = zip;
1512 }
1513 return zip->getResourceTableAsset();
1514}
1515
1516Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
1517 Asset* asset)
1518{
1519 int idx = getIndex(path);
1520 sp<SharedZip> zip = mZipFile[idx];
1521 // doesn't make sense to call before previously accessing.
1522 return zip->setResourceTableAsset(asset);
1523}
1524
1525ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
1526{
1527 int idx = getIndex(path);
1528 sp<SharedZip> zip = mZipFile[idx];
1529 if (zip == NULL) {
1530 zip = SharedZip::get(path);
1531 mZipFile.editItemAt(idx) = zip;
1532 }
1533 return zip->getResourceTable();
1534}
1535
1536ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
1537 ResTable* res)
1538{
1539 int idx = getIndex(path);
1540 sp<SharedZip> zip = mZipFile[idx];
1541 // doesn't make sense to call before previously accessing.
1542 return zip->setResourceTable(res);
1543}
1544
1545/*
1546 * Generate the partial pathname for the specified archive. The caller
1547 * gets to prepend the asset root directory.
1548 *
1549 * Returns something like "common/en-US-noogle.jar".
1550 */
1551/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
1552{
1553 return String8(zipPath);
1554}
1555
1556bool AssetManager::ZipSet::isUpToDate()
1557{
1558 const size_t N = mZipFile.size();
1559 for (size_t i=0; i<N; i++) {
1560 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
1561 return false;
1562 }
1563 }
1564 return true;
1565}
1566
Mårten Kongstad48d22322014-01-31 14:43:27 +01001567void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
1568{
1569 int idx = getIndex(path);
1570 sp<SharedZip> zip = mZipFile[idx];
1571 zip->addOverlay(overlay);
1572}
1573
1574bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
1575{
1576 sp<SharedZip> zip = SharedZip::get(path, false);
1577 if (zip == NULL) {
1578 return false;
1579 }
1580 return zip->getOverlay(idx, out);
1581}
1582
Adam Lesinski16c4d152014-01-24 13:27:13 -08001583/*
1584 * Compute the zip file's index.
1585 *
1586 * "appName", "locale", and "vendor" should be set to NULL to indicate the
1587 * default directory.
1588 */
1589int AssetManager::ZipSet::getIndex(const String8& zip) const
1590{
1591 const size_t N = mZipPath.size();
1592 for (size_t i=0; i<N; i++) {
1593 if (mZipPath[i] == zip) {
1594 return i;
1595 }
1596 }
1597
1598 mZipPath.add(zip);
1599 mZipFile.add(NULL);
1600
1601 return mZipPath.size()-1;
1602}