blob: 796cb3633626b463b88e77c8d39e86704cbb10ca [file] [log] [blame]
Adam Lesinski16c4d152014-01-24 13:27:13 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Provide access to read-only assets.
19//
20
21#define LOG_TAG "asset"
22#define ATRACE_TAG ATRACE_TAG_RESOURCES
23//#define LOG_NDEBUG 0
24
25#include <androidfw/Asset.h>
26#include <androidfw/AssetDir.h>
27#include <androidfw/AssetManager.h>
28#include <androidfw/misc.h>
29#include <androidfw/ResourceTypes.h>
30#include <androidfw/ZipFileRO.h>
31#include <utils/Atomic.h>
32#include <utils/Log.h>
33#include <utils/String8.h>
34#include <utils/String8.h>
35#include <utils/threads.h>
36#include <utils/Timers.h>
Adam Lesinskib7e1ce02016-04-11 20:03:01 -070037#include <utils/Trace.h>
Adam Lesinski16c4d152014-01-24 13:27:13 -080038
39#include <assert.h>
40#include <dirent.h>
41#include <errno.h>
Mårten Kongstad48d22322014-01-31 14:43:27 +010042#include <string.h> // strerror
Adam Lesinski16c4d152014-01-24 13:27:13 -080043#include <strings.h>
Adam Lesinski16c4d152014-01-24 13:27:13 -080044
45#ifndef TEMP_FAILURE_RETRY
46/* Used to retry syscalls that can return EINTR. */
47#define TEMP_FAILURE_RETRY(exp) ({ \
48 typeof (exp) _rc; \
49 do { \
50 _rc = (exp); \
51 } while (_rc == -1 && errno == EINTR); \
52 _rc; })
53#endif
54
Adam Lesinski16c4d152014-01-24 13:27:13 -080055using namespace android;
56
Andreas Gampe2204f0b2014-10-21 23:04:54 -070057static const bool kIsDebug = false;
58
Adam Lesinski16c4d152014-01-24 13:27:13 -080059static const char* kAssetsRoot = "assets";
60static const char* kAppZipName = NULL; //"classes.jar";
61static const char* kSystemAssets = "framework/framework-res.apk";
Mårten Kongstad48d22322014-01-31 14:43:27 +010062static const char* kResourceCache = "resource-cache";
Adam Lesinski16c4d152014-01-24 13:27:13 -080063
64static const char* kExcludeExtension = ".EXCLUDE";
65
66static Asset* const kExcludedAsset = (Asset*) 0xd000000d;
67
68static volatile int32_t gCount = 0;
69
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010070const char* AssetManager::RESOURCES_FILENAME = "resources.arsc";
Mårten Kongstad48d22322014-01-31 14:43:27 +010071const char* AssetManager::IDMAP_BIN = "/system/bin/idmap";
72const char* AssetManager::OVERLAY_DIR = "/vendor/overlay";
Jakub Adamekc03d9482016-09-30 09:19:09 +010073const char* AssetManager::OVERLAY_SKU_DIR_PROPERTY = "ro.boot.vendor.overlay.sku";
Mårten Kongstad48d22322014-01-31 14:43:27 +010074const char* AssetManager::TARGET_PACKAGE_NAME = "android";
75const char* AssetManager::TARGET_APK_PATH = "/system/framework/framework-res.apk";
76const char* AssetManager::IDMAP_DIR = "/data/resource-cache";
Mårten Kongstad65a05fd2014-01-31 14:01:52 +010077
Adam Lesinski16c4d152014-01-24 13:27:13 -080078namespace {
Adam Lesinski16c4d152014-01-24 13:27:13 -080079
Adam Lesinskia77685f2016-10-03 16:26:28 -070080String8 idmapPathForPackagePath(const String8& pkgPath) {
81 const char* root = getenv("ANDROID_DATA");
82 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
83 String8 path(root);
84 path.appendPath(kResourceCache);
Adam Lesinski16c4d152014-01-24 13:27:13 -080085
Adam Lesinskia77685f2016-10-03 16:26:28 -070086 char buf[256]; // 256 chars should be enough for anyone...
87 strncpy(buf, pkgPath.string(), 255);
88 buf[255] = '\0';
89 char* filename = buf;
90 while (*filename && *filename == '/') {
91 ++filename;
Adam Lesinski16c4d152014-01-24 13:27:13 -080092 }
Adam Lesinskia77685f2016-10-03 16:26:28 -070093 char* p = filename;
94 while (*p) {
95 if (*p == '/') {
96 *p = '@';
97 }
98 ++p;
Adam Lesinski16c4d152014-01-24 13:27:13 -080099 }
Adam Lesinskia77685f2016-10-03 16:26:28 -0700100 path.appendPath(filename);
101 path.append("@idmap");
102
103 return path;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800104}
105
106/*
Adam Lesinskia77685f2016-10-03 16:26:28 -0700107 * Like strdup(), but uses C++ "new" operator instead of malloc.
108 */
109static char* strdupNew(const char* str) {
110 char* newStr;
111 int len;
112
113 if (str == NULL)
114 return NULL;
115
116 len = strlen(str);
117 newStr = new char[len+1];
118 memcpy(newStr, str, len+1);
119
120 return newStr;
121}
122
123} // namespace
124
125/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800126 * ===========================================================================
127 * AssetManager
128 * ===========================================================================
129 */
130
Adam Lesinskia77685f2016-10-03 16:26:28 -0700131int32_t AssetManager::getGlobalCount() {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800132 return gCount;
133}
134
Adam Lesinskia77685f2016-10-03 16:26:28 -0700135AssetManager::AssetManager() :
136 mLocale(NULL), mResources(NULL), mConfig(new ResTable_config) {
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700137 int count = android_atomic_inc(&gCount) + 1;
138 if (kIsDebug) {
139 ALOGI("Creating AssetManager %p #%d\n", this, count);
140 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800141 memset(mConfig, 0, sizeof(ResTable_config));
142}
143
Adam Lesinskia77685f2016-10-03 16:26:28 -0700144AssetManager::~AssetManager() {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800145 int count = android_atomic_dec(&gCount);
Andreas Gampe2204f0b2014-10-21 23:04:54 -0700146 if (kIsDebug) {
147 ALOGI("Destroying AssetManager in %p #%d\n", this, count);
148 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800149
150 delete mConfig;
151 delete mResources;
152
153 // don't have a String class yet, so make sure we clean up
154 delete[] mLocale;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800155}
156
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800157bool AssetManager::addAssetPath(
Adam Lesinskia77685f2016-10-03 16:26:28 -0700158 const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800159 AutoMutex _l(mLock);
160
161 asset_path ap;
162
163 String8 realPath(path);
164 if (kAppZipName) {
165 realPath.appendPath(kAppZipName);
166 }
167 ap.type = ::getFileType(realPath.string());
168 if (ap.type == kFileTypeRegular) {
169 ap.path = realPath;
170 } else {
171 ap.path = path;
172 ap.type = ::getFileType(path.string());
173 if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
174 ALOGW("Asset path %s is neither a directory nor file (type=%d).",
175 path.string(), (int)ap.type);
176 return false;
177 }
178 }
179
180 // Skip if we have it already.
181 for (size_t i=0; i<mAssetPaths.size(); i++) {
182 if (mAssetPaths[i].path == ap.path) {
183 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000184 *cookie = static_cast<int32_t>(i+1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800185 }
186 return true;
187 }
188 }
189
190 ALOGV("In %p Asset %s path: %s", this,
191 ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
192
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800193 ap.isSystemAsset = isSystemAsset;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800194 mAssetPaths.add(ap);
195
196 // new paths are always added at the end
197 if (cookie) {
Narayan Kamatha0c62602014-01-24 13:51:51 +0000198 *cookie = static_cast<int32_t>(mAssetPaths.size());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800199 }
200
Elliott Hughesba3fe562015-08-12 14:49:53 -0700201#ifdef __ANDROID__
Mårten Kongstad48d22322014-01-31 14:43:27 +0100202 // Load overlays, if any
203 asset_path oap;
204 for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800205 oap.isSystemAsset = isSystemAsset;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100206 mAssetPaths.add(oap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800207 }
Mårten Kongstad48d22322014-01-31 14:43:27 +0100208#endif
Adam Lesinski16c4d152014-01-24 13:27:13 -0800209
Martin Kosiba7df36252014-01-16 16:25:56 +0000210 if (mResources != NULL) {
Tao Baia6d7e3f2015-09-01 18:49:54 -0700211 appendPathToResTable(ap, appAsLib);
Martin Kosiba7df36252014-01-16 16:25:56 +0000212 }
213
Adam Lesinski16c4d152014-01-24 13:27:13 -0800214 return true;
215}
216
Mårten Kongstad48d22322014-01-31 14:43:27 +0100217bool AssetManager::addOverlayPath(const String8& packagePath, int32_t* cookie)
218{
219 const String8 idmapPath = idmapPathForPackagePath(packagePath);
220
221 AutoMutex _l(mLock);
222
223 for (size_t i = 0; i < mAssetPaths.size(); ++i) {
224 if (mAssetPaths[i].idmap == idmapPath) {
225 *cookie = static_cast<int32_t>(i + 1);
226 return true;
227 }
228 }
229
230 Asset* idmap = NULL;
231 if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
232 ALOGW("failed to open idmap file %s\n", idmapPath.string());
233 return false;
234 }
235
236 String8 targetPath;
237 String8 overlayPath;
238 if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700239 NULL, NULL, NULL, &targetPath, &overlayPath)) {
Mårten Kongstad48d22322014-01-31 14:43:27 +0100240 ALOGW("failed to read idmap file %s\n", idmapPath.string());
241 delete idmap;
242 return false;
243 }
244 delete idmap;
245
246 if (overlayPath != packagePath) {
247 ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
248 idmapPath.string(), packagePath.string(), overlayPath.string());
249 return false;
250 }
251 if (access(targetPath.string(), R_OK) != 0) {
252 ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
253 return false;
254 }
255 if (access(idmapPath.string(), R_OK) != 0) {
256 ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
257 return false;
258 }
259 if (access(overlayPath.string(), R_OK) != 0) {
260 ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
261 return false;
262 }
263
264 asset_path oap;
265 oap.path = overlayPath;
266 oap.type = ::getFileType(overlayPath.string());
267 oap.idmap = idmapPath;
268#if 0
269 ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
270 targetPath.string(), overlayPath.string(), idmapPath.string());
271#endif
272 mAssetPaths.add(oap);
273 *cookie = static_cast<int32_t>(mAssetPaths.size());
274
Mårten Kongstad30113132014-11-07 10:52:17 +0100275 if (mResources != NULL) {
276 appendPathToResTable(oap);
277 }
278
Mårten Kongstad48d22322014-01-31 14:43:27 +0100279 return true;
280 }
281
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100282bool AssetManager::createIdmap(const char* targetApkPath, const char* overlayApkPath,
Dianne Hackborn32bb5fa2014-02-11 13:56:21 -0800283 uint32_t targetCrc, uint32_t overlayCrc, uint32_t** outData, size_t* outSize)
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100284{
285 AutoMutex _l(mLock);
286 const String8 paths[2] = { String8(targetApkPath), String8(overlayApkPath) };
287 ResTable tables[2];
288
289 for (int i = 0; i < 2; ++i) {
290 asset_path ap;
291 ap.type = kFileTypeRegular;
292 ap.path = paths[i];
293 Asset* ass = openNonAssetInPathLocked("resources.arsc", Asset::ACCESS_BUFFER, ap);
294 if (ass == NULL) {
295 ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
296 return false;
297 }
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700298 tables[i].add(ass);
Mårten Kongstad65a05fd2014-01-31 14:01:52 +0100299 }
300
301 return tables[0].createIdmap(tables[1], targetCrc, overlayCrc,
302 targetApkPath, overlayApkPath, (void**)outData, outSize) == NO_ERROR;
303}
304
Adam Lesinski16c4d152014-01-24 13:27:13 -0800305bool AssetManager::addDefaultAssets()
306{
307 const char* root = getenv("ANDROID_ROOT");
308 LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
309
310 String8 path(root);
311 path.appendPath(kSystemAssets);
312
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800313 return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800314}
315
Narayan Kamatha0c62602014-01-24 13:51:51 +0000316int32_t AssetManager::nextAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800317{
318 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000319 const size_t next = static_cast<size_t>(cookie) + 1;
320 return next > mAssetPaths.size() ? -1 : next;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800321}
322
Narayan Kamatha0c62602014-01-24 13:51:51 +0000323String8 AssetManager::getAssetPath(const int32_t cookie) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800324{
325 AutoMutex _l(mLock);
Narayan Kamatha0c62602014-01-24 13:51:51 +0000326 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800327 if (which < mAssetPaths.size()) {
328 return mAssetPaths[which].path;
329 }
330 return String8();
331}
332
Adam Lesinski16c4d152014-01-24 13:27:13 -0800333void AssetManager::setLocaleLocked(const char* locale)
334{
335 if (mLocale != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800336 delete[] mLocale;
337 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700338
Adam Lesinski16c4d152014-01-24 13:27:13 -0800339 mLocale = strdupNew(locale);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800340 updateResourceParamsLocked();
341}
342
Adam Lesinski16c4d152014-01-24 13:27:13 -0800343void AssetManager::setConfiguration(const ResTable_config& config, const char* locale)
344{
345 AutoMutex _l(mLock);
346 *mConfig = config;
347 if (locale) {
348 setLocaleLocked(locale);
349 } else if (config.language[0] != 0) {
Narayan Kamath91447d82014-01-21 15:32:36 +0000350 char spec[RESTABLE_MAX_LOCALE_LEN];
351 config.getBcp47Locale(spec);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800352 setLocaleLocked(spec);
353 } else {
354 updateResourceParamsLocked();
355 }
356}
357
358void AssetManager::getConfiguration(ResTable_config* outConfig) const
359{
360 AutoMutex _l(mLock);
361 *outConfig = *mConfig;
362}
363
364/*
365 * Open an asset.
366 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700367 * The data could be in any asset path. Each asset path could be:
368 * - A directory on disk.
369 * - A Zip archive, uncompressed or compressed.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800370 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700371 * If the file is in a directory, it could have a .gz suffix, meaning it is compressed.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800372 *
373 * We should probably reject requests for "illegal" filenames, e.g. those
374 * with illegal characters or "../" backward relative paths.
375 */
376Asset* AssetManager::open(const char* fileName, AccessMode mode)
377{
378 AutoMutex _l(mLock);
379
380 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
381
Adam Lesinski16c4d152014-01-24 13:27:13 -0800382 String8 assetName(kAssetsRoot);
383 assetName.appendPath(fileName);
384
385 /*
386 * For each top-level asset path, search for the asset.
387 */
388
389 size_t i = mAssetPaths.size();
390 while (i > 0) {
391 i--;
392 ALOGV("Looking for asset '%s' in '%s'\n",
393 assetName.string(), mAssetPaths.itemAt(i).path.string());
394 Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode, mAssetPaths.itemAt(i));
395 if (pAsset != NULL) {
396 return pAsset != kExcludedAsset ? pAsset : NULL;
397 }
398 }
399
400 return NULL;
401}
402
403/*
404 * Open a non-asset file as if it were an asset.
405 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700406 * The "fileName" is the partial path starting from the application name.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800407 */
Adam Lesinskide898ff2014-01-29 18:20:45 -0800408Asset* AssetManager::openNonAsset(const char* fileName, AccessMode mode, int32_t* outCookie)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800409{
410 AutoMutex _l(mLock);
411
412 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
413
Adam Lesinski16c4d152014-01-24 13:27:13 -0800414 /*
415 * For each top-level asset path, search for the asset.
416 */
417
418 size_t i = mAssetPaths.size();
419 while (i > 0) {
420 i--;
421 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
422 Asset* pAsset = openNonAssetInPathLocked(
423 fileName, mode, mAssetPaths.itemAt(i));
424 if (pAsset != NULL) {
Adam Lesinskide898ff2014-01-29 18:20:45 -0800425 if (outCookie != NULL) *outCookie = static_cast<int32_t>(i + 1);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800426 return pAsset != kExcludedAsset ? pAsset : NULL;
427 }
428 }
429
430 return NULL;
431}
432
Narayan Kamatha0c62602014-01-24 13:51:51 +0000433Asset* AssetManager::openNonAsset(const int32_t cookie, const char* fileName, AccessMode mode)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800434{
Narayan Kamatha0c62602014-01-24 13:51:51 +0000435 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800436
437 AutoMutex _l(mLock);
438
439 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
440
Adam Lesinski16c4d152014-01-24 13:27:13 -0800441 if (which < mAssetPaths.size()) {
442 ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
443 mAssetPaths.itemAt(which).path.string());
444 Asset* pAsset = openNonAssetInPathLocked(
445 fileName, mode, mAssetPaths.itemAt(which));
446 if (pAsset != NULL) {
447 return pAsset != kExcludedAsset ? pAsset : NULL;
448 }
449 }
450
451 return NULL;
452}
453
454/*
455 * Get the type of a file in the asset namespace.
456 *
457 * This currently only works for regular files. All others (including
458 * directories) will return kFileTypeNonexistent.
459 */
460FileType AssetManager::getFileType(const char* fileName)
461{
462 Asset* pAsset = NULL;
463
464 /*
465 * Open the asset. This is less efficient than simply finding the
466 * file, but it's not too bad (we don't uncompress or mmap data until
467 * the first read() call).
468 */
469 pAsset = open(fileName, Asset::ACCESS_STREAMING);
470 delete pAsset;
471
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700472 if (pAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800473 return kFileTypeNonexistent;
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700474 } else {
Adam Lesinski16c4d152014-01-24 13:27:13 -0800475 return kFileTypeRegular;
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700476 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800477}
478
Tao Baia6d7e3f2015-09-01 18:49:54 -0700479bool AssetManager::appendPathToResTable(const asset_path& ap, bool appAsLib) const {
Mårten Kongstadcb7b63d2014-11-07 10:57:15 +0100480 // skip those ap's that correspond to system overlays
481 if (ap.isSystemOverlay) {
482 return true;
483 }
484
Martin Kosiba7df36252014-01-16 16:25:56 +0000485 Asset* ass = NULL;
486 ResTable* sharedRes = NULL;
487 bool shared = true;
488 bool onlyEmptyResources = true;
Adam Lesinskib7e1ce02016-04-11 20:03:01 -0700489 ATRACE_NAME(ap.path.string());
Martin Kosiba7df36252014-01-16 16:25:56 +0000490 Asset* idmap = openIdmapLocked(ap);
491 size_t nextEntryIdx = mResources->getTableCount();
492 ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
493 if (ap.type != kFileTypeDirectory) {
494 if (nextEntryIdx == 0) {
495 // The first item is typically the framework resources,
496 // which we want to avoid parsing every time.
497 sharedRes = const_cast<AssetManager*>(this)->
498 mZipSet.getZipResourceTable(ap.path);
499 if (sharedRes != NULL) {
500 // skip ahead the number of system overlay packages preloaded
501 nextEntryIdx = sharedRes->getTableCount();
502 }
503 }
504 if (sharedRes == NULL) {
505 ass = const_cast<AssetManager*>(this)->
506 mZipSet.getZipResourceTableAsset(ap.path);
507 if (ass == NULL) {
508 ALOGV("loading resource table %s\n", ap.path.string());
509 ass = const_cast<AssetManager*>(this)->
510 openNonAssetInPathLocked("resources.arsc",
511 Asset::ACCESS_BUFFER,
512 ap);
513 if (ass != NULL && ass != kExcludedAsset) {
514 ass = const_cast<AssetManager*>(this)->
515 mZipSet.setZipResourceTableAsset(ap.path, ass);
516 }
517 }
518
519 if (nextEntryIdx == 0 && ass != NULL) {
520 // If this is the first resource table in the asset
521 // manager, then we are going to cache it so that we
522 // can quickly copy it out for others.
523 ALOGV("Creating shared resources for %s", ap.path.string());
524 sharedRes = new ResTable();
525 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
Elliott Hughesba3fe562015-08-12 14:49:53 -0700526#ifdef __ANDROID__
Martin Kosiba7df36252014-01-16 16:25:56 +0000527 const char* data = getenv("ANDROID_DATA");
528 LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
529 String8 overlaysListPath(data);
530 overlaysListPath.appendPath(kResourceCache);
531 overlaysListPath.appendPath("overlays.list");
532 addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
533#endif
534 sharedRes = const_cast<AssetManager*>(this)->
535 mZipSet.setZipResourceTable(ap.path, sharedRes);
536 }
537 }
538 } else {
539 ALOGV("loading resource table %s\n", ap.path.string());
540 ass = const_cast<AssetManager*>(this)->
541 openNonAssetInPathLocked("resources.arsc",
542 Asset::ACCESS_BUFFER,
543 ap);
544 shared = false;
545 }
546
547 if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
548 ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
549 if (sharedRes != NULL) {
550 ALOGV("Copying existing resources for %s", ap.path.string());
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800551 mResources->add(sharedRes, ap.isSystemAsset);
Martin Kosiba7df36252014-01-16 16:25:56 +0000552 } else {
553 ALOGV("Parsing resources for %s", ap.path.string());
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800554 mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
Martin Kosiba7df36252014-01-16 16:25:56 +0000555 }
556 onlyEmptyResources = false;
557
558 if (!shared) {
559 delete ass;
560 }
561 } else {
562 ALOGV("Installing empty resources in to table %p\n", mResources);
563 mResources->addEmpty(nextEntryIdx + 1);
564 }
565
566 if (idmap != NULL) {
567 delete idmap;
568 }
Martin Kosiba7df36252014-01-16 16:25:56 +0000569 return onlyEmptyResources;
570}
571
Adam Lesinski16c4d152014-01-24 13:27:13 -0800572const ResTable* AssetManager::getResTable(bool required) const
573{
574 ResTable* rt = mResources;
575 if (rt) {
576 return rt;
577 }
578
579 // Iterate through all asset packages, collecting resources from each.
580
581 AutoMutex _l(mLock);
582
583 if (mResources != NULL) {
584 return mResources;
585 }
586
587 if (required) {
588 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
589 }
590
Adam Lesinskide898ff2014-01-29 18:20:45 -0800591 mResources = new ResTable();
592 updateResourceParamsLocked();
593
594 bool onlyEmptyResources = true;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800595 const size_t N = mAssetPaths.size();
596 for (size_t i=0; i<N; i++) {
Martin Kosiba7df36252014-01-16 16:25:56 +0000597 bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
598 onlyEmptyResources = onlyEmptyResources && empty;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800599 }
600
Adam Lesinskide898ff2014-01-29 18:20:45 -0800601 if (required && onlyEmptyResources) {
602 ALOGW("Unable to find resources file resources.arsc");
603 delete mResources;
604 mResources = NULL;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800605 }
Adam Lesinskide898ff2014-01-29 18:20:45 -0800606
607 return mResources;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800608}
609
610void AssetManager::updateResourceParamsLocked() const
611{
Adam Lesinskib7e1ce02016-04-11 20:03:01 -0700612 ATRACE_CALL();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800613 ResTable* res = mResources;
614 if (!res) {
615 return;
616 }
617
Narayan Kamath91447d82014-01-21 15:32:36 +0000618 if (mLocale) {
619 mConfig->setBcp47Locale(mLocale);
620 } else {
621 mConfig->clearLocale();
Adam Lesinski16c4d152014-01-24 13:27:13 -0800622 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800623
624 res->setParameters(mConfig);
625}
626
627Asset* AssetManager::openIdmapLocked(const struct asset_path& ap) const
628{
629 Asset* ass = NULL;
630 if (ap.idmap.size() != 0) {
631 ass = const_cast<AssetManager*>(this)->
632 openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
633 if (ass) {
634 ALOGV("loading idmap %s\n", ap.idmap.string());
635 } else {
636 ALOGW("failed to load idmap %s\n", ap.idmap.string());
637 }
638 }
639 return ass;
640}
641
Mårten Kongstad48d22322014-01-31 14:43:27 +0100642void AssetManager::addSystemOverlays(const char* pathOverlaysList,
643 const String8& targetPackagePath, ResTable* sharedRes, size_t offset) const
644{
645 FILE* fin = fopen(pathOverlaysList, "r");
646 if (fin == NULL) {
647 return;
648 }
649
650 char buf[1024];
651 while (fgets(buf, sizeof(buf), fin)) {
652 // format of each line:
653 // <path to apk><space><path to idmap><newline>
654 char* space = strchr(buf, ' ');
655 char* newline = strchr(buf, '\n');
656 asset_path oap;
657
658 if (space == NULL || newline == NULL || newline < space) {
659 continue;
660 }
661
662 oap.path = String8(buf, space - buf);
663 oap.type = kFileTypeRegular;
664 oap.idmap = String8(space + 1, newline - space - 1);
Mårten Kongstadcb7b63d2014-11-07 10:57:15 +0100665 oap.isSystemOverlay = true;
Mårten Kongstad48d22322014-01-31 14:43:27 +0100666
667 Asset* oass = const_cast<AssetManager*>(this)->
668 openNonAssetInPathLocked("resources.arsc",
669 Asset::ACCESS_BUFFER,
670 oap);
671
672 if (oass != NULL) {
673 Asset* oidmap = openIdmapLocked(oap);
674 offset++;
Adam Lesinskif90f2f8d2014-06-06 14:27:00 -0700675 sharedRes->add(oass, oidmap, offset + 1, false);
Mårten Kongstad48d22322014-01-31 14:43:27 +0100676 const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
677 const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
678 }
679 }
680 fclose(fin);
681}
682
Adam Lesinski16c4d152014-01-24 13:27:13 -0800683const ResTable& AssetManager::getResources(bool required) const
684{
685 const ResTable* rt = getResTable(required);
686 return *rt;
687}
688
689bool AssetManager::isUpToDate()
690{
691 AutoMutex _l(mLock);
692 return mZipSet.isUpToDate();
693}
694
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800695void AssetManager::getLocales(Vector<String8>* locales, bool includeSystemLocales) const
Adam Lesinski16c4d152014-01-24 13:27:13 -0800696{
697 ResTable* res = mResources;
698 if (res != NULL) {
Roozbeh Pournader7e5f96f2016-06-13 18:10:49 -0700699 res->getLocales(locales, includeSystemLocales, true /* mergeEquivalentLangs */);
Narayan Kamathe4345db2014-06-26 16:01:28 +0100700 }
Adam Lesinski16c4d152014-01-24 13:27:13 -0800701}
702
703/*
704 * Open a non-asset file as if it were an asset, searching for it in the
705 * specified app.
706 *
707 * Pass in a NULL values for "appName" if the common app directory should
708 * be used.
709 */
710Asset* AssetManager::openNonAssetInPathLocked(const char* fileName, AccessMode mode,
711 const asset_path& ap)
712{
713 Asset* pAsset = NULL;
714
715 /* look at the filesystem on disk */
716 if (ap.type == kFileTypeDirectory) {
717 String8 path(ap.path);
718 path.appendPath(fileName);
719
720 pAsset = openAssetFromFileLocked(path, mode);
721
722 if (pAsset == NULL) {
723 /* try again, this time with ".gz" */
724 path.append(".gz");
725 pAsset = openAssetFromFileLocked(path, mode);
726 }
727
728 if (pAsset != NULL) {
729 //printf("FOUND NA '%s' on disk\n", fileName);
730 pAsset->setAssetSource(path);
731 }
732
733 /* look inside the zip file */
734 } else {
735 String8 path(fileName);
736
737 /* check the appropriate Zip file */
Narayan Kamath560566d2013-12-03 13:16:03 +0000738 ZipFileRO* pZip = getZipFileLocked(ap);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800739 if (pZip != NULL) {
740 //printf("GOT zip, checking NA '%s'\n", (const char*) path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000741 ZipEntryRO entry = pZip->findEntryByName(path.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -0800742 if (entry != NULL) {
743 //printf("FOUND NA in Zip file for %s\n", appName ? appName : kAppCommon);
744 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
Narayan Kamath560566d2013-12-03 13:16:03 +0000745 pZip->releaseEntry(entry);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800746 }
747 }
748
749 if (pAsset != NULL) {
750 /* create a "source" name, for debug/display */
751 pAsset->setAssetSource(
752 createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
753 String8(fileName)));
754 }
755 }
756
757 return pAsset;
758}
759
760/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800761 * Create a "source name" for a file from a Zip archive.
762 */
763String8 AssetManager::createZipSourceNameLocked(const String8& zipFileName,
764 const String8& dirName, const String8& fileName)
765{
766 String8 sourceName("zip:");
767 sourceName.append(zipFileName);
768 sourceName.append(":");
769 if (dirName.length() > 0) {
770 sourceName.appendPath(dirName);
771 }
772 sourceName.appendPath(fileName);
773 return sourceName;
774}
775
776/*
Adam Lesinski16c4d152014-01-24 13:27:13 -0800777 * Create a path to a loose asset (asset-base/app/rootDir).
778 */
779String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
780{
781 String8 path(ap.path);
782 if (rootDir != NULL) path.appendPath(rootDir);
783 return path;
784}
785
786/*
787 * Return a pointer to one of our open Zip archives. Returns NULL if no
788 * matching Zip file exists.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800789 */
790ZipFileRO* AssetManager::getZipFileLocked(const asset_path& ap)
791{
792 ALOGV("getZipFileLocked() in %p\n", this);
793
794 return mZipSet.getZip(ap.path);
795}
796
797/*
798 * Try to open an asset from a file on disk.
799 *
800 * If the file is compressed with gzip, we seek to the start of the
801 * deflated data and pass that in (just like we would for a Zip archive).
802 *
803 * For uncompressed data, we may already have an mmap()ed version sitting
804 * around. If so, we want to hand that to the Asset instead.
805 *
806 * This returns NULL if the file doesn't exist, couldn't be opened, or
807 * claims to be a ".gz" but isn't.
808 */
809Asset* AssetManager::openAssetFromFileLocked(const String8& pathName,
810 AccessMode mode)
811{
812 Asset* pAsset = NULL;
813
814 if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
815 //printf("TRYING '%s'\n", (const char*) pathName);
816 pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
817 } else {
818 //printf("TRYING '%s'\n", (const char*) pathName);
819 pAsset = Asset::createFromFile(pathName.string(), mode);
820 }
821
822 return pAsset;
823}
824
825/*
826 * Given an entry in a Zip archive, create a new Asset object.
827 *
828 * If the entry is uncompressed, we may want to create or share a
829 * slice of shared memory.
830 */
831Asset* AssetManager::openAssetFromZipLocked(const ZipFileRO* pZipFile,
832 const ZipEntryRO entry, AccessMode mode, const String8& entryName)
833{
834 Asset* pAsset = NULL;
835
836 // TODO: look for previously-created shared memory slice?
Narayan Kamath407753c2015-06-16 12:02:57 +0100837 uint16_t method;
838 uint32_t uncompressedLen;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800839
840 //printf("USING Zip '%s'\n", pEntry->getFileName());
841
Adam Lesinski16c4d152014-01-24 13:27:13 -0800842 if (!pZipFile->getEntryInfo(entry, &method, &uncompressedLen, NULL, NULL,
843 NULL, NULL))
844 {
845 ALOGW("getEntryInfo failed\n");
846 return NULL;
847 }
848
849 FileMap* dataMap = pZipFile->createEntryFileMap(entry);
850 if (dataMap == NULL) {
851 ALOGW("create map from entry failed\n");
852 return NULL;
853 }
854
855 if (method == ZipFileRO::kCompressStored) {
856 pAsset = Asset::createFromUncompressedMap(dataMap, mode);
857 ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
858 dataMap->getFileName(), mode, pAsset);
859 } else {
Narayan Kamath407753c2015-06-16 12:02:57 +0100860 pAsset = Asset::createFromCompressedMap(dataMap,
861 static_cast<size_t>(uncompressedLen), mode);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800862 ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
863 dataMap->getFileName(), mode, pAsset);
864 }
865 if (pAsset == NULL) {
866 /* unexpected */
867 ALOGW("create from segment failed\n");
868 }
869
870 return pAsset;
871}
872
Adam Lesinski16c4d152014-01-24 13:27:13 -0800873/*
874 * Open a directory in the asset namespace.
875 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700876 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800877 *
878 * Pass in "" for the root dir.
879 */
880AssetDir* AssetManager::openDir(const char* dirName)
881{
882 AutoMutex _l(mLock);
883
884 AssetDir* pDir = NULL;
885 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
886
887 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
888 assert(dirName != NULL);
889
890 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
891
Adam Lesinski16c4d152014-01-24 13:27:13 -0800892 pDir = new AssetDir;
893
894 /*
895 * Scan the various directories, merging what we find into a single
896 * vector. We want to scan them in reverse priority order so that
897 * the ".EXCLUDE" processing works correctly. Also, if we decide we
898 * want to remember where the file is coming from, we'll get the right
899 * version.
900 *
901 * We start with Zip archives, then do loose files.
902 */
903 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
904
905 size_t i = mAssetPaths.size();
906 while (i > 0) {
907 i--;
908 const asset_path& ap = mAssetPaths.itemAt(i);
909 if (ap.type == kFileTypeRegular) {
910 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
911 scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
912 } else {
913 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
914 scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
915 }
916 }
917
918#if 0
919 printf("FILE LIST:\n");
920 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
921 printf(" %d: (%d) '%s'\n", i,
922 pMergedInfo->itemAt(i).getFileType(),
923 (const char*) pMergedInfo->itemAt(i).getFileName());
924 }
925#endif
926
927 pDir->setFileList(pMergedInfo);
928 return pDir;
929}
930
931/*
932 * Open a directory in the non-asset namespace.
933 *
Adam Lesinskife90eaf2016-10-04 13:31:31 -0700934 * An "asset directory" is simply the combination of all asset paths' "assets/" directories.
Adam Lesinski16c4d152014-01-24 13:27:13 -0800935 *
936 * Pass in "" for the root dir.
937 */
Narayan Kamatha0c62602014-01-24 13:51:51 +0000938AssetDir* AssetManager::openNonAssetDir(const int32_t cookie, const char* dirName)
Adam Lesinski16c4d152014-01-24 13:27:13 -0800939{
940 AutoMutex _l(mLock);
941
942 AssetDir* pDir = NULL;
943 SortedVector<AssetDir::FileInfo>* pMergedInfo = NULL;
944
945 LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
946 assert(dirName != NULL);
947
948 //printf("+++ openDir(%s) in '%s'\n", dirName, (const char*) mAssetBase);
949
Adam Lesinski16c4d152014-01-24 13:27:13 -0800950 pDir = new AssetDir;
951
952 pMergedInfo = new SortedVector<AssetDir::FileInfo>;
953
Narayan Kamatha0c62602014-01-24 13:51:51 +0000954 const size_t which = static_cast<size_t>(cookie) - 1;
Adam Lesinski16c4d152014-01-24 13:27:13 -0800955
956 if (which < mAssetPaths.size()) {
957 const asset_path& ap = mAssetPaths.itemAt(which);
958 if (ap.type == kFileTypeRegular) {
959 ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
960 scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
961 } else {
962 ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
963 scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
964 }
965 }
966
967#if 0
968 printf("FILE LIST:\n");
969 for (i = 0; i < (size_t) pMergedInfo->size(); i++) {
970 printf(" %d: (%d) '%s'\n", i,
971 pMergedInfo->itemAt(i).getFileType(),
972 (const char*) pMergedInfo->itemAt(i).getFileName());
973 }
974#endif
975
976 pDir->setFileList(pMergedInfo);
977 return pDir;
978}
979
980/*
981 * Scan the contents of the specified directory and merge them into the
982 * "pMergedInfo" vector, removing previous entries if we find "exclude"
983 * directives.
984 *
985 * Returns "false" if we found nothing to contribute.
986 */
987bool AssetManager::scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
988 const asset_path& ap, const char* rootDir, const char* dirName)
989{
Adam Lesinski16c4d152014-01-24 13:27:13 -0800990 assert(pMergedInfo != NULL);
991
Adam Lesinskia77685f2016-10-03 16:26:28 -0700992 //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800993
Adam Lesinskia77685f2016-10-03 16:26:28 -0700994 String8 path = createPathNameLocked(ap, rootDir);
995 if (dirName[0] != '\0')
996 path.appendPath(dirName);
Adam Lesinski16c4d152014-01-24 13:27:13 -0800997
Adam Lesinskia77685f2016-10-03 16:26:28 -0700998 SortedVector<AssetDir::FileInfo>* pContents = scanDirLocked(path);
999 if (pContents == NULL)
1000 return false;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001001
1002 // if we wanted to do an incremental cache fill, we would do it here
1003
1004 /*
1005 * Process "exclude" directives. If we find a filename that ends with
1006 * ".EXCLUDE", we look for a matching entry in the "merged" set, and
1007 * remove it if we find it. We also delete the "exclude" entry.
1008 */
1009 int i, count, exclExtLen;
1010
1011 count = pContents->size();
1012 exclExtLen = strlen(kExcludeExtension);
1013 for (i = 0; i < count; i++) {
1014 const char* name;
1015 int nameLen;
1016
1017 name = pContents->itemAt(i).getFileName().string();
1018 nameLen = strlen(name);
1019 if (nameLen > exclExtLen &&
1020 strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
1021 {
1022 String8 match(name, nameLen - exclExtLen);
1023 int matchIdx;
1024
1025 matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
1026 if (matchIdx > 0) {
1027 ALOGV("Excluding '%s' [%s]\n",
1028 pMergedInfo->itemAt(matchIdx).getFileName().string(),
1029 pMergedInfo->itemAt(matchIdx).getSourceName().string());
1030 pMergedInfo->removeAt(matchIdx);
1031 } else {
1032 //printf("+++ no match on '%s'\n", (const char*) match);
1033 }
1034
1035 ALOGD("HEY: size=%d removing %d\n", (int)pContents->size(), i);
1036 pContents->removeAt(i);
1037 i--; // adjust "for" loop
1038 count--; // and loop limit
1039 }
1040 }
1041
1042 mergeInfoLocked(pMergedInfo, pContents);
1043
1044 delete pContents;
1045
1046 return true;
1047}
1048
1049/*
1050 * Scan the contents of the specified directory, and stuff what we find
1051 * into a newly-allocated vector.
1052 *
1053 * Files ending in ".gz" will have their extensions removed.
1054 *
1055 * We should probably think about skipping files with "illegal" names,
1056 * e.g. illegal characters (/\:) or excessive length.
1057 *
1058 * Returns NULL if the specified directory doesn't exist.
1059 */
1060SortedVector<AssetDir::FileInfo>* AssetManager::scanDirLocked(const String8& path)
1061{
1062 SortedVector<AssetDir::FileInfo>* pContents = NULL;
1063 DIR* dir;
1064 struct dirent* entry;
1065 FileType fileType;
1066
1067 ALOGV("Scanning dir '%s'\n", path.string());
1068
1069 dir = opendir(path.string());
1070 if (dir == NULL)
1071 return NULL;
1072
1073 pContents = new SortedVector<AssetDir::FileInfo>;
1074
1075 while (1) {
1076 entry = readdir(dir);
1077 if (entry == NULL)
1078 break;
1079
1080 if (strcmp(entry->d_name, ".") == 0 ||
1081 strcmp(entry->d_name, "..") == 0)
1082 continue;
1083
1084#ifdef _DIRENT_HAVE_D_TYPE
1085 if (entry->d_type == DT_REG)
1086 fileType = kFileTypeRegular;
1087 else if (entry->d_type == DT_DIR)
1088 fileType = kFileTypeDirectory;
1089 else
1090 fileType = kFileTypeUnknown;
1091#else
1092 // stat the file
1093 fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
1094#endif
1095
1096 if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
1097 continue;
1098
1099 AssetDir::FileInfo info;
1100 info.set(String8(entry->d_name), fileType);
1101 if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
1102 info.setFileName(info.getFileName().getBasePath());
1103 info.setSourceName(path.appendPathCopy(info.getFileName()));
1104 pContents->add(info);
1105 }
1106
1107 closedir(dir);
1108 return pContents;
1109}
1110
1111/*
1112 * Scan the contents out of the specified Zip archive, and merge what we
1113 * find into "pMergedInfo". If the Zip archive in question doesn't exist,
1114 * we return immediately.
1115 *
1116 * Returns "false" if we found nothing to contribute.
1117 */
1118bool AssetManager::scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1119 const asset_path& ap, const char* rootDir, const char* baseDirName)
1120{
1121 ZipFileRO* pZip;
1122 Vector<String8> dirs;
1123 AssetDir::FileInfo info;
1124 SortedVector<AssetDir::FileInfo> contents;
1125 String8 sourceName, zipName, dirName;
1126
1127 pZip = mZipSet.getZip(ap.path);
1128 if (pZip == NULL) {
1129 ALOGW("Failure opening zip %s\n", ap.path.string());
1130 return false;
1131 }
1132
1133 zipName = ZipSet::getPathName(ap.path.string());
1134
1135 /* convert "sounds" to "rootDir/sounds" */
1136 if (rootDir != NULL) dirName = rootDir;
1137 dirName.appendPath(baseDirName);
1138
1139 /*
1140 * Scan through the list of files, looking for a match. The files in
1141 * the Zip table of contents are not in sorted order, so we have to
1142 * process the entire list. We're looking for a string that begins
1143 * with the characters in "dirName", is followed by a '/', and has no
1144 * subsequent '/' in the stuff that follows.
1145 *
1146 * What makes this especially fun is that directories are not stored
1147 * explicitly in Zip archives, so we have to infer them from context.
1148 * When we see "sounds/foo.wav" we have to leave a note to ourselves
1149 * to insert a directory called "sounds" into the list. We store
1150 * these in temporary vector so that we only return each one once.
1151 *
1152 * Name comparisons are case-sensitive to match UNIX filesystem
1153 * semantics.
1154 */
1155 int dirNameLen = dirName.length();
Narayan Kamath560566d2013-12-03 13:16:03 +00001156 void *iterationCookie;
Yusuke Sato05f648e2015-08-03 16:21:10 -07001157 if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
Narayan Kamath560566d2013-12-03 13:16:03 +00001158 ALOGW("ZipFileRO::startIteration returned false");
1159 return false;
1160 }
1161
1162 ZipEntryRO entry;
1163 while ((entry = pZip->nextEntry(iterationCookie)) != NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001164 char nameBuf[256];
1165
Adam Lesinski16c4d152014-01-24 13:27:13 -08001166 if (pZip->getEntryFileName(entry, nameBuf, sizeof(nameBuf)) != 0) {
1167 // TODO: fix this if we expect to have long names
1168 ALOGE("ARGH: name too long?\n");
1169 continue;
1170 }
1171 //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
Yusuke Sato05f648e2015-08-03 16:21:10 -07001172 if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
Adam Lesinski16c4d152014-01-24 13:27:13 -08001173 {
1174 const char* cp;
1175 const char* nextSlash;
1176
1177 cp = nameBuf + dirNameLen;
1178 if (dirNameLen != 0)
1179 cp++; // advance past the '/'
1180
1181 nextSlash = strchr(cp, '/');
1182//xxx this may break if there are bare directory entries
1183 if (nextSlash == NULL) {
1184 /* this is a file in the requested directory */
1185
1186 info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
1187
1188 info.setSourceName(
1189 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1190
1191 contents.add(info);
1192 //printf("FOUND: file '%s'\n", info.getFileName().string());
1193 } else {
1194 /* this is a subdir; add it if we don't already have it*/
1195 String8 subdirName(cp, nextSlash - cp);
1196 size_t j;
1197 size_t N = dirs.size();
1198
1199 for (j = 0; j < N; j++) {
1200 if (subdirName == dirs[j]) {
1201 break;
1202 }
1203 }
1204 if (j == N) {
1205 dirs.add(subdirName);
1206 }
1207
1208 //printf("FOUND: dir '%s'\n", subdirName.string());
1209 }
1210 }
1211 }
1212
Narayan Kamath560566d2013-12-03 13:16:03 +00001213 pZip->endIteration(iterationCookie);
1214
Adam Lesinski16c4d152014-01-24 13:27:13 -08001215 /*
1216 * Add the set of unique directories.
1217 */
1218 for (int i = 0; i < (int) dirs.size(); i++) {
1219 info.set(dirs[i], kFileTypeDirectory);
1220 info.setSourceName(
1221 createZipSourceNameLocked(zipName, dirName, info.getFileName()));
1222 contents.add(info);
1223 }
1224
1225 mergeInfoLocked(pMergedInfo, &contents);
1226
1227 return true;
1228}
1229
1230
1231/*
1232 * Merge two vectors of FileInfo.
1233 *
1234 * The merged contents will be stuffed into *pMergedInfo.
1235 *
1236 * If an entry for a file exists in both "pMergedInfo" and "pContents",
1237 * we use the newer "pContents" entry.
1238 */
1239void AssetManager::mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
1240 const SortedVector<AssetDir::FileInfo>* pContents)
1241{
1242 /*
1243 * Merge what we found in this directory with what we found in
1244 * other places.
1245 *
1246 * Two basic approaches:
1247 * (1) Create a new array that holds the unique values of the two
1248 * arrays.
1249 * (2) Take the elements from pContents and shove them into pMergedInfo.
1250 *
1251 * Because these are vectors of complex objects, moving elements around
1252 * inside the vector requires constructing new objects and allocating
1253 * storage for members. With approach #1, we're always adding to the
1254 * end, whereas with #2 we could be inserting multiple elements at the
1255 * front of the vector. Approach #1 requires a full copy of the
1256 * contents of pMergedInfo, but approach #2 requires the same copy for
1257 * every insertion at the front of pMergedInfo.
1258 *
1259 * (We should probably use a SortedVector interface that allows us to
1260 * just stuff items in, trusting us to maintain the sort order.)
1261 */
1262 SortedVector<AssetDir::FileInfo>* pNewSorted;
1263 int mergeMax, contMax;
1264 int mergeIdx, contIdx;
1265
1266 pNewSorted = new SortedVector<AssetDir::FileInfo>;
1267 mergeMax = pMergedInfo->size();
1268 contMax = pContents->size();
1269 mergeIdx = contIdx = 0;
1270
1271 while (mergeIdx < mergeMax || contIdx < contMax) {
1272 if (mergeIdx == mergeMax) {
1273 /* hit end of "merge" list, copy rest of "contents" */
1274 pNewSorted->add(pContents->itemAt(contIdx));
1275 contIdx++;
1276 } else if (contIdx == contMax) {
1277 /* hit end of "cont" list, copy rest of "merge" */
1278 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1279 mergeIdx++;
1280 } else if (pMergedInfo->itemAt(mergeIdx) == pContents->itemAt(contIdx))
1281 {
1282 /* items are identical, add newer and advance both indices */
1283 pNewSorted->add(pContents->itemAt(contIdx));
1284 mergeIdx++;
1285 contIdx++;
1286 } else if (pMergedInfo->itemAt(mergeIdx) < pContents->itemAt(contIdx))
1287 {
1288 /* "merge" is lower, add that one */
1289 pNewSorted->add(pMergedInfo->itemAt(mergeIdx));
1290 mergeIdx++;
1291 } else {
1292 /* "cont" is lower, add that one */
1293 assert(pContents->itemAt(contIdx) < pMergedInfo->itemAt(mergeIdx));
1294 pNewSorted->add(pContents->itemAt(contIdx));
1295 contIdx++;
1296 }
1297 }
1298
1299 /*
1300 * Overwrite the "merged" list with the new stuff.
1301 */
1302 *pMergedInfo = *pNewSorted;
1303 delete pNewSorted;
1304
1305#if 0 // for Vector, rather than SortedVector
1306 int i, j;
1307 for (i = pContents->size() -1; i >= 0; i--) {
1308 bool add = true;
1309
1310 for (j = pMergedInfo->size() -1; j >= 0; j--) {
1311 /* case-sensitive comparisons, to behave like UNIX fs */
1312 if (strcmp(pContents->itemAt(i).mFileName,
1313 pMergedInfo->itemAt(j).mFileName) == 0)
1314 {
1315 /* match, don't add this entry */
1316 add = false;
1317 break;
1318 }
1319 }
1320
1321 if (add)
1322 pMergedInfo->add(pContents->itemAt(i));
1323 }
1324#endif
1325}
1326
Adam Lesinski16c4d152014-01-24 13:27:13 -08001327/*
1328 * ===========================================================================
1329 * AssetManager::SharedZip
1330 * ===========================================================================
1331 */
1332
1333
1334Mutex AssetManager::SharedZip::gLock;
1335DefaultKeyedVector<String8, wp<AssetManager::SharedZip> > AssetManager::SharedZip::gOpen;
1336
1337AssetManager::SharedZip::SharedZip(const String8& path, time_t modWhen)
1338 : mPath(path), mZipFile(NULL), mModWhen(modWhen),
1339 mResourceTableAsset(NULL), mResourceTable(NULL)
1340{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001341 if (kIsDebug) {
1342 ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
1343 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001344 ALOGV("+++ opening zip '%s'\n", mPath.string());
Narayan Kamath560566d2013-12-03 13:16:03 +00001345 mZipFile = ZipFileRO::open(mPath.string());
1346 if (mZipFile == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001347 ALOGD("failed to open Zip archive '%s'\n", mPath.string());
Adam Lesinski16c4d152014-01-24 13:27:13 -08001348 }
1349}
1350
Mårten Kongstad48d22322014-01-31 14:43:27 +01001351sp<AssetManager::SharedZip> AssetManager::SharedZip::get(const String8& path,
1352 bool createIfNotPresent)
Adam Lesinski16c4d152014-01-24 13:27:13 -08001353{
1354 AutoMutex _l(gLock);
1355 time_t modWhen = getFileModDate(path);
1356 sp<SharedZip> zip = gOpen.valueFor(path).promote();
1357 if (zip != NULL && zip->mModWhen == modWhen) {
1358 return zip;
1359 }
Mårten Kongstad48d22322014-01-31 14:43:27 +01001360 if (zip == NULL && !createIfNotPresent) {
1361 return NULL;
1362 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001363 zip = new SharedZip(path, modWhen);
1364 gOpen.add(path, zip);
1365 return zip;
1366
1367}
1368
1369ZipFileRO* AssetManager::SharedZip::getZip()
1370{
1371 return mZipFile;
1372}
1373
1374Asset* AssetManager::SharedZip::getResourceTableAsset()
1375{
songjinshi49921f22016-09-08 15:24:30 +08001376 AutoMutex _l(gLock);
Adam Lesinski16c4d152014-01-24 13:27:13 -08001377 ALOGV("Getting from SharedZip %p resource asset %p\n", this, mResourceTableAsset);
1378 return mResourceTableAsset;
1379}
1380
1381Asset* AssetManager::SharedZip::setResourceTableAsset(Asset* asset)
1382{
1383 {
1384 AutoMutex _l(gLock);
1385 if (mResourceTableAsset == NULL) {
Adam Lesinski16c4d152014-01-24 13:27:13 -08001386 // This is not thread safe the first time it is called, so
1387 // do it here with the global lock held.
1388 asset->getBuffer(true);
songjinshi49921f22016-09-08 15:24:30 +08001389 mResourceTableAsset = asset;
Adam Lesinski16c4d152014-01-24 13:27:13 -08001390 return asset;
1391 }
1392 }
1393 delete asset;
1394 return mResourceTableAsset;
1395}
1396
1397ResTable* AssetManager::SharedZip::getResourceTable()
1398{
1399 ALOGV("Getting from SharedZip %p resource table %p\n", this, mResourceTable);
1400 return mResourceTable;
1401}
1402
1403ResTable* AssetManager::SharedZip::setResourceTable(ResTable* res)
1404{
1405 {
1406 AutoMutex _l(gLock);
1407 if (mResourceTable == NULL) {
1408 mResourceTable = res;
1409 return res;
1410 }
1411 }
1412 delete res;
1413 return mResourceTable;
1414}
1415
1416bool AssetManager::SharedZip::isUpToDate()
1417{
1418 time_t modWhen = getFileModDate(mPath.string());
1419 return mModWhen == modWhen;
1420}
1421
Mårten Kongstad48d22322014-01-31 14:43:27 +01001422void AssetManager::SharedZip::addOverlay(const asset_path& ap)
1423{
1424 mOverlays.add(ap);
1425}
1426
1427bool AssetManager::SharedZip::getOverlay(size_t idx, asset_path* out) const
1428{
1429 if (idx >= mOverlays.size()) {
1430 return false;
1431 }
1432 *out = mOverlays[idx];
1433 return true;
1434}
1435
Adam Lesinski16c4d152014-01-24 13:27:13 -08001436AssetManager::SharedZip::~SharedZip()
1437{
Andreas Gampe2204f0b2014-10-21 23:04:54 -07001438 if (kIsDebug) {
1439 ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
1440 }
Adam Lesinski16c4d152014-01-24 13:27:13 -08001441 if (mResourceTable != NULL) {
1442 delete mResourceTable;
1443 }
1444 if (mResourceTableAsset != NULL) {
1445 delete mResourceTableAsset;
1446 }
1447 if (mZipFile != NULL) {
1448 delete mZipFile;
1449 ALOGV("Closed '%s'\n", mPath.string());
1450 }
1451}
1452
1453/*
1454 * ===========================================================================
1455 * AssetManager::ZipSet
1456 * ===========================================================================
1457 */
1458
1459/*
Adam Lesinski16c4d152014-01-24 13:27:13 -08001460 * Destructor. Close any open archives.
1461 */
1462AssetManager::ZipSet::~ZipSet(void)
1463{
1464 size_t N = mZipFile.size();
1465 for (size_t i = 0; i < N; i++)
1466 closeZip(i);
1467}
1468
1469/*
1470 * Close a Zip file and reset the entry.
1471 */
1472void AssetManager::ZipSet::closeZip(int idx)
1473{
1474 mZipFile.editItemAt(idx) = NULL;
1475}
1476
1477
1478/*
1479 * Retrieve the appropriate Zip file from the set.
1480 */
1481ZipFileRO* AssetManager::ZipSet::getZip(const String8& path)
1482{
1483 int idx = getIndex(path);
1484 sp<SharedZip> zip = mZipFile[idx];
1485 if (zip == NULL) {
1486 zip = SharedZip::get(path);
1487 mZipFile.editItemAt(idx) = zip;
1488 }
1489 return zip->getZip();
1490}
1491
1492Asset* AssetManager::ZipSet::getZipResourceTableAsset(const String8& path)
1493{
1494 int idx = getIndex(path);
1495 sp<SharedZip> zip = mZipFile[idx];
1496 if (zip == NULL) {
1497 zip = SharedZip::get(path);
1498 mZipFile.editItemAt(idx) = zip;
1499 }
1500 return zip->getResourceTableAsset();
1501}
1502
1503Asset* AssetManager::ZipSet::setZipResourceTableAsset(const String8& path,
1504 Asset* asset)
1505{
1506 int idx = getIndex(path);
1507 sp<SharedZip> zip = mZipFile[idx];
1508 // doesn't make sense to call before previously accessing.
1509 return zip->setResourceTableAsset(asset);
1510}
1511
1512ResTable* AssetManager::ZipSet::getZipResourceTable(const String8& path)
1513{
1514 int idx = getIndex(path);
1515 sp<SharedZip> zip = mZipFile[idx];
1516 if (zip == NULL) {
1517 zip = SharedZip::get(path);
1518 mZipFile.editItemAt(idx) = zip;
1519 }
1520 return zip->getResourceTable();
1521}
1522
1523ResTable* AssetManager::ZipSet::setZipResourceTable(const String8& path,
1524 ResTable* res)
1525{
1526 int idx = getIndex(path);
1527 sp<SharedZip> zip = mZipFile[idx];
1528 // doesn't make sense to call before previously accessing.
1529 return zip->setResourceTable(res);
1530}
1531
1532/*
1533 * Generate the partial pathname for the specified archive. The caller
1534 * gets to prepend the asset root directory.
1535 *
1536 * Returns something like "common/en-US-noogle.jar".
1537 */
1538/*static*/ String8 AssetManager::ZipSet::getPathName(const char* zipPath)
1539{
1540 return String8(zipPath);
1541}
1542
1543bool AssetManager::ZipSet::isUpToDate()
1544{
1545 const size_t N = mZipFile.size();
1546 for (size_t i=0; i<N; i++) {
1547 if (mZipFile[i] != NULL && !mZipFile[i]->isUpToDate()) {
1548 return false;
1549 }
1550 }
1551 return true;
1552}
1553
Mårten Kongstad48d22322014-01-31 14:43:27 +01001554void AssetManager::ZipSet::addOverlay(const String8& path, const asset_path& overlay)
1555{
1556 int idx = getIndex(path);
1557 sp<SharedZip> zip = mZipFile[idx];
1558 zip->addOverlay(overlay);
1559}
1560
1561bool AssetManager::ZipSet::getOverlay(const String8& path, size_t idx, asset_path* out) const
1562{
1563 sp<SharedZip> zip = SharedZip::get(path, false);
1564 if (zip == NULL) {
1565 return false;
1566 }
1567 return zip->getOverlay(idx, out);
1568}
1569
Adam Lesinski16c4d152014-01-24 13:27:13 -08001570/*
1571 * Compute the zip file's index.
1572 *
1573 * "appName", "locale", and "vendor" should be set to NULL to indicate the
1574 * default directory.
1575 */
1576int AssetManager::ZipSet::getIndex(const String8& zip) const
1577{
1578 const size_t N = mZipPath.size();
1579 for (size_t i=0; i<N; i++) {
1580 if (mZipPath[i] == zip) {
1581 return i;
1582 }
1583 }
1584
1585 mZipPath.add(zip);
1586 mZipFile.add(NULL);
1587
1588 return mZipPath.size()-1;
1589}