blob: ae789d649e721aec9d5541fbdc4b7138683d9dd7 [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);
neo.chae6a742a32016-11-01 00:02:38 +0900687 delete oidmap;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100688 }
689 }
Martin Wallgren0fbb6082015-08-11 15:10:31 +0200690
691#ifndef _WIN32
692 TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_UN));
693#endif
Mårten Kongstad48d22322014-01-31 14:43:27 +0100694 fclose(fin);
695}
696
Adam Lesinski16c4d152014-01-24 13:27:13 -0800697const ResTable& AssetManager::getResources(bool required) const
698{
699 const ResTable* rt = getResTable(required);
700 return *rt;
701}
702
703bool AssetManager::isUpToDate()
704{
705 AutoMutex _l(mLock);
706 return mZipSet.isUpToDate();
707}
708
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800709void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800710{
711 ResTable* res = mResources;
712 if (res != NULL) {
Roozbeh Pournader7e5f96f2016-06-13 18:10:49 -0700713 res->getLocales(locales, includeSystemLocales, true /* mergeEquivalentLangs */);
Narayan Kamathe4345db2014-06-26 16:01:28 +0100714 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800715}
716
717/*
718 * Open a non-asset file as if it were an asset, searching for it in the
719 * specified app.
720 *
721 * Pass in a NULL values for "appName" if the common app directory should
722 * be used.
723 */
724Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
725 const asset_path& ap)
726{
727 Asset* pAsset = NULL;
728
729 /* look at the filesystem on disk */
730 if (ap.type == kFileTypeDirectory) {
731 String8 path(ap.path);
732 path.appendPath(fileName);
733
734 pAsset = openAssetFromFileLocked(path, mode);
735
736 if (pAsset == NULL) {
737 /* try again, this time with ".gz" */
738 path.append(".gz");
739 pAsset = openAssetFromFileLocked(path, mode);
740 }
741
742 if (pAsset != NULL) {
743 //printf("FOUND NA '%s' on disk\n", fileName);
744 pAsset->setAssetSource(path);
745 }
746
747 /* look inside the zip file */
748 } else {
749 String8 path(fileName);
750
751 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +0000752 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800753 if (pZip != NULL) {
754 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000755 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800756 if (entry != NULL) {
757 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
758 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000759 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800760 }
761 }
762
763 if (pAsset != NULL) {
764 /* create a "source" name, for debug/display */
765 pAsset->setAssetSource(
766 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
767 String8(fileName)));
768 }
769 }
770
771 return pAsset;
772}
773
774/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800775 * Create a "source name" for a file from a Zip archive.
776 */
777String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
778 const String8& dirName, const String8& fileName)
779{
780 String8 sourceName("zip:");
781 sourceName.append(zipFileName);
782 sourceName.append(":");
783 if (dirName.length() > 0) {
784 sourceName.appendPath(dirName);
785 }
786 sourceName.appendPath(fileName);
787 return sourceName;
788}
789
790/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800791 * Create a path to a loose asset (asset-base/app/rootDir).
792 */
793String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
794{
795 String8 path(ap.path);
796 if (rootDir != NULL) path.appendPath(rootDir);
797 return path;
798}
799
800/*
801 * Return a pointer to one of our open Zip archives. Returns NULL if no
802 * matching Zip file exists.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800803 */
804ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
805{
806 ALOGV("getZipFileLocked() in %p\n", this);
807
808 return mZipSet.getZip(ap.path);
809}
810
811/*
812 * Try to open an asset from a file on disk.
813 *
814 * If the file is compressed with gzip, we seek to the start of the
815 * deflated data and pass that in (just like we would for a Zip archive).
816 *
817 * For uncompressed data, we may already have an mmap()ed version sitting
818 * around. If so, we want to hand that to the Asset instead.
819 *
820 * This returns NULL if the file doesn't exist, couldn't be opened, or
821 * claims to be a ".gz" but isn't.
822 */
823Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
824 AccessMode mode)
825{
826 Asset* pAsset = NULL;
827
828 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
829 //printf("TRYING '%s'\n", (const char*) pathName);
830 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
831 } else {
832 //printf("TRYING '%s'\n", (const char*) pathName);
833 pAsset = Asset::createFromFile(pathName.string(), mode);
834 }
835
836 return pAsset;
837}
838
839/*
840 * Given an entry in a Zip archive, create a new Asset object.
841 *
842 * If the entry is uncompressed, we may want to create or share a
843 * slice of shared memory.
844 */
845Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
846 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
847{
848 Asset* pAsset = NULL;
849
850 // TODO: look for previously-created shared memory slice?
Narayan Kamath407753c2015-06-16 12:02:57 +0100851 uint16_t method;
852 uint32_t uncompressedLen;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800853
854 //printf("USING Zip '%s'\n", pEntry->getFileName());
855
Adam Lesinski16c4d152014-01-24 13:27:13 -0800856 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
857 NULL, NULL))
858 {
859 ALOGW("getEntryInfo failed\n");
860 return NULL;
861 }
862
863 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
864 if (dataMap == NULL) {
865 ALOGW("create map from entry failed\n");
866 return NULL;
867 }
868
869 if (method == ZipFileRO::kCompressStored) {
870 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
871 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
872 dataMap->getFileName(), mode, pAsset);
873 } else {
Narayan Kamath407753c2015-06-16 12:02:57 +0100874 pAsset = Asset::createFromCompressedMap(dataMap,
875 static_cast<size_t>(uncompressedLen), mode);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800876 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
877 dataMap->getFileName(), mode, pAsset);
878 }
879 if (pAsset == NULL) {
880 /* unexpected */
881 ALOGW("create from segment failed\n");
882 }
883
884 return pAsset;
885}
886
Adam Lesinski16c4d152014-01-24 13:27:13 -0800887/*
888 * Open a directory in the asset namespace.
889 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700890 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800891 *
892 * Pass in "" for the root dir.
893 */
894AssetDir* AssetManager::openDir(const char* dirName)
895{
896 AutoMutex _l(mLock);
897
898 AssetDir* pDir = NULL;
899 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
900
901 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
902 assert(dirName != NULL);
903
904 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
905
Adam Lesinski16c4d152014-01-24 13:27:13 -0800906 pDir = new AssetDir;
907
908 /*
909 * Scan the various directories, merging what we find into a single
910 * vector. We want to scan them in reverse priority order so that
911 * the ".EXCLUDE" processing works correctly. Also, if we decide we
912 * want to remember where the file is coming from, we'll get the right
913 * version.
914 *
915 * We start with Zip archives, then do loose files.
916 */
917 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
918
919 size_t i = mAssetPaths.size();
920 while (i > 0) {
921 i--;
922 const asset_path& ap = mAssetPaths.itemAt(i);
923 if (ap.type == kFileTypeRegular) {
924 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
925 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
926 } else {
927 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
928 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
929 }
930 }
931
932#if 0
933 printf("FILE LIST:\n");
934 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
935 printf(" %d: (%d) '%s'\n", i,
936 pMergedInfo->itemAt(i).getFileType(),
937 (const char*) pMergedInfo->itemAt(i).getFileName());
938 }
939#endif
940
941 pDir->setFileList(pMergedInfo);
942 return pDir;
943}
944
945/*
946 * Open a directory in the non-asset namespace.
947 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700948 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800949 *
950 * Pass in "" for the root dir.
951 */
Narayan Kamatha0c62602014-01-24 13:51:51 +0000952AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800953{
954 AutoMutex _l(mLock);
955
956 AssetDir* pDir = NULL;
957 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
958
959 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
960 assert(dirName != NULL);
961
962 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
963
Adam Lesinski16c4d152014-01-24 13:27:13 -0800964 pDir = new AssetDir;
965
966 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
967
Narayan Kamatha0c62602014-01-24 13:51:51 +0000968 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800969
970 if (which < mAssetPaths.size()) {
971 const asset_path& ap = mAssetPaths.itemAt(which);
972 if (ap.type == kFileTypeRegular) {
973 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
974 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
975 } else {
976 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
977 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
978 }
979 }
980
981#if 0
982 printf("FILE LIST:\n");
983 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
984 printf(" %d: (%d) '%s'\n", i,
985 pMergedInfo->itemAt(i).getFileType(),
986 (const char*) pMergedInfo->itemAt(i).getFileName());
987 }
988#endif
989
990 pDir->setFileList(pMergedInfo);
991 return pDir;
992}
993
994/*
995 * Scan the contents of the specified directory and merge them into the
996 * "pMergedInfo" vector, removing previous entries if we find "exclude"
997 * directives.
998 *
999 * Returns "false" if we found nothing to contribute.
1000 */
1001bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1002 const asset_path& ap, const char* rootDir, const char* dirName)
1003{
Adam Lesinski16c4d152014-01-24 13:27:13 -08001004 assert(pMergedInfo != NULL);
1005
Adam Lesinskia77685f2016-10-03 16:26:28 -07001006 //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001007
Adam Lesinskia77685f2016-10-03 16:26:28 -07001008 String8 path = createPathNameLocked(ap, rootDir);
1009 if (dirName[0] != '\0')
1010 path.appendPath(dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001011
Adam Lesinskia77685f2016-10-03 16:26:28 -07001012 SortedVector<AssetDir::FileInfo>* pContents = scanDirLocked(path);
1013 if (pContents == NULL)
1014 return false;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001015
1016 // if we wanted to do an incremental cache fill, we would do it here
1017
1018 /*
1019 * Process "exclude" directives. If we find a filename that ends with
1020 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1021 * remove it if we find it. We also delete the "exclude" entry.
1022 */
1023 int i, count, exclExtLen;
1024
1025 count = pContents->size();
1026 exclExtLen = strlen(kExcludeExtension);
1027 for (i = 0; i < count; i++) {
1028 const char* name;
1029 int nameLen;
1030
1031 name = pContents->itemAt(i).getFileName().string();
1032 nameLen = strlen(name);
1033 if (nameLen > exclExtLen &&
1034 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1035 {
1036 String8 match(name, nameLen - exclExtLen);
1037 int matchIdx;
1038
1039 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1040 if (matchIdx > 0) {
1041 ALOGV("Excluding '%s' [%s]\n",
1042 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1043 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1044 pMergedInfo->removeAt(matchIdx);
1045 } else {
1046 //printf("+++ no match on '%s'\n", (const char*) match);
1047 }
1048
1049 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1050 pContents->removeAt(i);
1051 i--; // adjust "for" loop
1052 count--; // and loop limit
1053 }
1054 }
1055
1056 mergeInfoLocked(pMergedInfo, pContents);
1057
1058 delete pContents;
1059
1060 return true;
1061}
1062
1063/*
1064 * Scan the contents of the specified directory, and stuff what we find
1065 * into a newly-allocated vector.
1066 *
1067 * Files ending in ".gz" will have their extensions removed.
1068 *
1069 * We should probably think about skipping files with "illegal" names,
1070 * e.g. illegal characters (/\:) or excessive length.
1071 *
1072 * Returns NULL if the specified directory doesn't exist.
1073 */
1074SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1075{
1076 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1077 DIR* dir;
1078 struct dirent* entry;
1079 FileType fileType;
1080
1081 ALOGV("Scanning dir '%s'\n", path.string());
1082
1083 dir = opendir(path.string());
1084 if (dir == NULL)
1085 return NULL;
1086
1087 pContents = new SortedVector<AssetDir::FileInfo>;
1088
1089 while (1) {
1090 entry = readdir(dir);
1091 if (entry == NULL)
1092 break;
1093
1094 if (strcmp(entry->d_name, ".") == 0 ||
1095 strcmp(entry->d_name, "..") == 0)
1096 continue;
1097
1098#ifdef _DIRENT_HAVE_D_TYPE
1099 if (entry->d_type == DT_REG)
1100 fileType = kFileTypeRegular;
1101 else if (entry->d_type == DT_DIR)
1102 fileType = kFileTypeDirectory;
1103 else
1104 fileType = kFileTypeUnknown;
1105#else
1106 // stat the file
1107 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1108#endif
1109
1110 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1111 continue;
1112
1113 AssetDir::FileInfo info;
1114 info.set(String8(entry->d_name), fileType);
1115 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1116 info.setFileName(info.getFileName().getBasePath());
1117 info.setSourceName(path.appendPathCopy(info.getFileName()));
1118 pContents->add(info);
1119 }
1120
1121 closedir(dir);
1122 return pContents;
1123}
1124
1125/*
1126 * Scan the contents out of the specified Zip archive, and merge what we
1127 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1128 * we return immediately.
1129 *
1130 * Returns "false" if we found nothing to contribute.
1131 */
1132bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1133 const asset_path& ap, const char* rootDir, const char* baseDirName)
1134{
1135 ZipFileRO* pZip;
1136 Vector<String8> dirs;
1137 AssetDir::FileInfo info;
1138 SortedVector<AssetDir::FileInfo> contents;
1139 String8 sourceName, zipName, dirName;
1140
1141 pZip = mZipSet.getZip(ap.path);
1142 if (pZip == NULL) {
1143 ALOGW("Failure opening zip %s\n", ap.path.string());
1144 return false;
1145 }
1146
1147 zipName = ZipSet::getPathName(ap.path.string());
1148
1149 /* convert "sounds" to "rootDir/sounds" */
1150 if (rootDir != NULL) dirName = rootDir;
1151 dirName.appendPath(baseDirName);
1152
1153 /*
1154 * Scan through the list of files, looking for a match. The files in
1155 * the Zip table of contents are not in sorted order, so we have to
1156 * process the entire list. We're looking for a string that begins
1157 * with the characters in "dirName", is followed by a '/', and has no
1158 * subsequent '/' in the stuff that follows.
1159 *
1160 * What makes this especially fun is that directories are not stored
1161 * explicitly in Zip archives, so we have to infer them from context.
1162 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1163 * to insert a directory called "sounds" into the list. We store
1164 * these in temporary vector so that we only return each one once.
1165 *
1166 * Name comparisons are case-sensitive to match UNIX filesystem
1167 * semantics.
1168 */
1169 int dirNameLen = dirName.length();
Narayan Kamath560566d2013-12-03 13:16:03 +00001170 void *iterationCookie;
Yusuke Sato05f648e2015-08-03 16:21:10 -07001171 if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
Narayan Kamath560566d2013-12-03 13:16:03 +00001172 ALOGW("ZipFileRO::startIteration returned false");
1173 return false;
1174 }
1175
1176 ZipEntryRO entry;
1177 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001178 char nameBuf[256];
1179
Adam Lesinski16c4d152014-01-24 13:27:13 -08001180 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1181 // TODO: fix this if we expect to have long names
1182 ALOGE("ARGH: name too long?\n");
1183 continue;
1184 }
1185 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
Yusuke Sato05f648e2015-08-03 16:21:10 -07001186 if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
Adam Lesinski16c4d152014-01-24 13:27:13 -08001187 {
1188 const char* cp;
1189 const char* nextSlash;
1190
1191 cp = nameBuf + dirNameLen;
1192 if (dirNameLen != 0)
1193 cp++; // advance past the '/'
1194
1195 nextSlash = strchr(cp, '/');
1196//xxx this may break if there are bare directory entries
1197 if (nextSlash == NULL) {
1198 /* this is a file in the requested directory */
1199
1200 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1201
1202 info.setSourceName(
1203 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1204
1205 contents.add(info);
1206 //printf("FOUND: file '%s'\n", info.getFileName().string());
1207 } else {
1208 /* this is a subdir; add it if we don't already have it*/
1209 String8 subdirName(cp, nextSlash - cp);
1210 size_t j;
1211 size_t N = dirs.size();
1212
1213 for (j = 0; j < N; j++) {
1214 if (subdirName == dirs[j]) {
1215 break;
1216 }
1217 }
1218 if (j == N) {
1219 dirs.add(subdirName);
1220 }
1221
1222 //printf("FOUND: dir '%s'\n", subdirName.string());
1223 }
1224 }
1225 }
1226
Narayan Kamath560566d2013-12-03 13:16:03 +00001227 pZip->endIteration(iterationCookie);
1228
Adam Lesinski16c4d152014-01-24 13:27:13 -08001229 /*
1230 * Add the set of unique directories.
1231 */
1232 for (int i = 0; i < (int) dirs.size(); i++) {
1233 info.set(dirs[i], kFileTypeDirectory);
1234 info.setSourceName(
1235 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1236 contents.add(info);
1237 }
1238
1239 mergeInfoLocked(pMergedInfo, &contents);
1240
1241 return true;
1242}
1243
1244
1245/*
1246 * Merge two vectors of FileInfo.
1247 *
1248 * The merged contents will be stuffed into *pMergedInfo.
1249 *
1250 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1251 * we use the newer "pContents" entry.
1252 */
1253void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1254 const SortedVector<AssetDir::FileInfo>* pContents)
1255{
1256 /*
1257 * Merge what we found in this directory with what we found in
1258 * other places.
1259 *
1260 * Two basic approaches:
1261 * (1) Create a new array that holds the unique values of the two
1262 * arrays.
1263 * (2) Take the elements from pContents and shove them into pMergedInfo.
1264 *
1265 * Because these are vectors of complex objects, moving elements around
1266 * inside the vector requires constructing new objects and allocating
1267 * storage for members. With approach #1, we're always adding to the
1268 * end, whereas with #2 we could be inserting multiple elements at the
1269 * front of the vector. Approach #1 requires a full copy of the
1270 * contents of pMergedInfo, but approach #2 requires the same copy for
1271 * every insertion at the front of pMergedInfo.
1272 *
1273 * (We should probably use a SortedVector interface that allows us to
1274 * just stuff items in, trusting us to maintain the sort order.)
1275 */
1276 SortedVector<AssetDir::FileInfo>* pNewSorted;
1277 int mergeMax, contMax;
1278 int mergeIdx, contIdx;
1279
1280 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1281 mergeMax = pMergedInfo->size();
1282 contMax = pContents->size();
1283 mergeIdx = contIdx = 0;
1284
1285 while (mergeIdx < mergeMax || contIdx < contMax) {
1286 if (mergeIdx == mergeMax) {
1287 /* hit end of "merge" list, copy rest of "contents" */
1288 pNewSorted->add(pContents->itemAt(contIdx));
1289 contIdx++;
1290 } else if (contIdx == contMax) {
1291 /* hit end of "cont" list, copy rest of "merge" */
1292 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1293 mergeIdx++;
1294 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1295 {
1296 /* items are identical, add newer and advance both indices */
1297 pNewSorted->add(pContents->itemAt(contIdx));
1298 mergeIdx++;
1299 contIdx++;
1300 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1301 {
1302 /* "merge" is lower, add that one */
1303 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1304 mergeIdx++;
1305 } else {
1306 /* "cont" is lower, add that one */
1307 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1308 pNewSorted->add(pContents->itemAt(contIdx));
1309 contIdx++;
1310 }
1311 }
1312
1313 /*
1314 * Overwrite the "merged" list with the new stuff.
1315 */
1316 *pMergedInfo = *pNewSorted;
1317 delete pNewSorted;
1318
1319#if 0 // for Vector, rather than SortedVector
1320 int i, j;
1321 for (i = pContents->size() -1; i >= 0; i--) {
1322 bool add = true;
1323
1324 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1325 /* case-sensitive comparisons, to behave like UNIX fs */
1326 if (strcmp(pContents->itemAt(i).mFileName,
1327 pMergedInfo->itemAt(j).mFileName) == 0)
1328 {
1329 /* match, don't add this entry */
1330 add = false;
1331 break;
1332 }
1333 }
1334
1335 if (add)
1336 pMergedInfo->add(pContents->itemAt(i));
1337 }
1338#endif
1339}
1340
Adam Lesinski16c4d152014-01-24 13:27:13 -08001341/*
1342 * ===========================================================================
1343 * AssetManager::SharedZip
1344 * ===========================================================================
1345 */
1346
1347
1348Mutex AssetManager::SharedZip::gLock;
1349DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1350
1351AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1352 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1353 mResourceTableAsset(NULL), mResourceTable(NULL)
1354{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001355 if (kIsDebug) {
1356 ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1357 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001358 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamath560566d2013-12-03 13:16:03 +00001359 mZipFile = ZipFileRO::open(mPath.string());
1360 if (mZipFile == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001361 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001362 }
1363}
1364
Mårten Kongstad48d22322014-01-31 14:43:27 +01001365sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1366 bool createIfNotPresent)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001367{
1368 AutoMutex _l(gLock);
1369 time_t modWhen = getFileModDate(path);
1370 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1371 if (zip != NULL && zip->mModWhen == modWhen) {
1372 return zip;
1373 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001374 if (zip == NULL && !createIfNotPresent) {
1375 return NULL;
1376 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001377 zip = new SharedZip(path, modWhen);
1378 gOpen.add(path, zip);
1379 return zip;
1380
1381}
1382
1383ZipFileRO* AssetManager::SharedZip::getZip()
1384{
1385 return mZipFile;
1386}
1387
1388Asset* AssetManager::SharedZip::getResourceTableAsset()
1389{
songjinshi49921f22016-09-08 15:24:30 +08001390 AutoMutex _l(gLock);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001391 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1392 return mResourceTableAsset;
1393}
1394
1395Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1396{
1397 {
1398 AutoMutex _l(gLock);
1399 if (mResourceTableAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001400 // This is not thread safe the first time it is called, so
1401 // do it here with the global lock held.
1402 asset->getBuffer(true);
songjinshi49921f22016-09-08 15:24:30 +08001403 mResourceTableAsset = asset;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001404 return asset;
1405 }
1406 }
1407 delete asset;
1408 return mResourceTableAsset;
1409}
1410
1411ResTable* AssetManager::SharedZip::getResourceTable()
1412{
1413 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1414 return mResourceTable;
1415}
1416
1417ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1418{
1419 {
1420 AutoMutex _l(gLock);
1421 if (mResourceTable == NULL) {
1422 mResourceTable = res;
1423 return res;
1424 }
1425 }
1426 delete res;
1427 return mResourceTable;
1428}
1429
1430bool AssetManager::SharedZip::isUpToDate()
1431{
1432 time_t modWhen = getFileModDate(mPath.string());
1433 return mModWhen == modWhen;
1434}
1435
Mårten Kongstad48d22322014-01-31 14:43:27 +01001436void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1437{
1438 mOverlays.add(ap);
1439}
1440
1441bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1442{
1443 if (idx >= mOverlays.size()) {
1444 return false;
1445 }
1446 *out = mOverlays[idx];
1447 return true;
1448}
1449
Adam Lesinski16c4d152014-01-24 13:27:13 -08001450AssetManager::SharedZip::~SharedZip()
1451{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001452 if (kIsDebug) {
1453 ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1454 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001455 if (mResourceTable != NULL) {
1456 delete mResourceTable;
1457 }
1458 if (mResourceTableAsset != NULL) {
1459 delete mResourceTableAsset;
1460 }
1461 if (mZipFile != NULL) {
1462 delete mZipFile;
1463 ALOGV("Closed '%s'\n", mPath.string());
1464 }
1465}
1466
1467/*
1468 * ===========================================================================
1469 * AssetManager::ZipSet
1470 * ===========================================================================
1471 */
1472
1473/*
Adam Lesinski16c4d152014-01-24 13:27:13 -08001474 * Destructor. Close any open archives.
1475 */
1476AssetManager::ZipSet::~ZipSet(void)
1477{
1478 size_t N = mZipFile.size();
1479 for (size_t i = 0; i < N; i++)
1480 closeZip(i);
1481}
1482
1483/*
1484 * Close a Zip file and reset the entry.
1485 */
1486void AssetManager::ZipSet::closeZip(int idx)
1487{
1488 mZipFile.editItemAt(idx) = NULL;
1489}
1490
1491
1492/*
1493 * Retrieve the appropriate Zip file from the set.
1494 */
1495ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1496{
1497 int idx = getIndex(path);
1498 sp<SharedZip> zip = mZipFile[idx];
1499 if (zip == NULL) {
1500 zip = SharedZip::get(path);
1501 mZipFile.editItemAt(idx) = zip;
1502 }
1503 return zip->getZip();
1504}
1505
1506Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
1507{
1508 int idx = getIndex(path);
1509 sp<SharedZip> zip = mZipFile[idx];
1510 if (zip == NULL) {
1511 zip = SharedZip::get(path);
1512 mZipFile.editItemAt(idx) = zip;
1513 }
1514 return zip->getResourceTableAsset();
1515}
1516
1517Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
1518 Asset* asset)
1519{
1520 int idx = getIndex(path);
1521 sp<SharedZip> zip = mZipFile[idx];
1522 // doesn't make sense to call before previously accessing.
1523 return zip->setResourceTableAsset(asset);
1524}
1525
1526ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
1527{
1528 int idx = getIndex(path);
1529 sp<SharedZip> zip = mZipFile[idx];
1530 if (zip == NULL) {
1531 zip = SharedZip::get(path);
1532 mZipFile.editItemAt(idx) = zip;
1533 }
1534 return zip->getResourceTable();
1535}
1536
1537ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
1538 ResTable* res)
1539{
1540 int idx = getIndex(path);
1541 sp<SharedZip> zip = mZipFile[idx];
1542 // doesn't make sense to call before previously accessing.
1543 return zip->setResourceTable(res);
1544}
1545
1546/*
1547 * Generate the partial pathname for the specified archive. The caller
1548 * gets to prepend the asset root directory.
1549 *
1550 * Returns something like "common/en-US-noogle.jar".
1551 */
1552/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
1553{
1554 return String8(zipPath);
1555}
1556
1557bool AssetManager::ZipSet::isUpToDate()
1558{
1559 const size_t N = mZipFile.size();
1560 for (size_t i=0; i<N; i++) {
1561 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
1562 return false;
1563 }
1564 }
1565 return true;
1566}
1567
Mårten Kongstad48d22322014-01-31 14:43:27 +01001568void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
1569{
1570 int idx = getIndex(path);
1571 sp<SharedZip> zip = mZipFile[idx];
1572 zip->addOverlay(overlay);
1573}
1574
1575bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
1576{
1577 sp<SharedZip> zip = SharedZip::get(path, false);
1578 if (zip == NULL) {
1579 return false;
1580 }
1581 return zip->getOverlay(idx, out);
1582}
1583
Adam Lesinski16c4d152014-01-24 13:27:13 -08001584/*
1585 * Compute the zip file's index.
1586 *
1587 * "appName", "locale", and "vendor" should be set to NULL to indicate the
1588 * default directory.
1589 */
1590int AssetManager::ZipSet::getIndex(const String8& zip) const
1591{
1592 const size_t N = mZipPath.size();
1593 for (size_t i=0; i<N; i++) {
1594 if (mZipPath[i] == zip) {
1595 return i;
1596 }
1597 }
1598
1599 mZipPath.add(zip);
1600 mZipFile.add(NULL);
1601
1602 return mZipPath.size()-1;
1603}