blob: 415d3e36adf9af2a372d090be9740763805d9f83 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 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#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
Adam Lesinski30080e22017-10-16 16:18:09 -070021#include <iterator>
Adam Lesinski0c405242017-01-13 20:47:26 -080022#include <set>
23
Adam Lesinski7ad11102016-10-28 16:39:15 -070024#include "android-base/logging.h"
25#include "android-base/stringprintf.h"
26#include "utils/ByteOrder.h"
27#include "utils/Trace.h"
28
29#ifdef _WIN32
30#ifdef ERROR
31#undef ERROR
32#endif
33#endif
34
Adam Lesinski929d6512017-01-16 19:11:19 -080035#include "androidfw/ResourceUtils.h"
36
Adam Lesinski7ad11102016-10-28 16:39:15 -070037namespace android {
38
Adam Lesinski970bd8d2017-09-25 13:21:55 -070039AssetManager2::AssetManager2() {
40 memset(&configuration_, 0, sizeof(configuration_));
41}
Adam Lesinski7ad11102016-10-28 16:39:15 -070042
43bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
44 bool invalidate_caches) {
45 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050046 BuildDynamicRefTable();
Adam Lesinski7ad11102016-10-28 16:39:15 -070047 if (invalidate_caches) {
48 InvalidateCaches(static_cast<uint32_t>(-1));
49 }
50 return true;
51}
52
Adam Lesinskida431a22016-12-29 16:08:16 -050053void AssetManager2::BuildDynamicRefTable() {
54 package_groups_.clear();
55 package_ids_.fill(0xff);
56
57 // 0x01 is reserved for the android package.
58 int next_package_id = 0x02;
59 const size_t apk_assets_count = apk_assets_.size();
60 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070061 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
62
63 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050064 // Get the package ID or assign one if a shared library.
65 int package_id;
66 if (package->IsDynamic()) {
67 package_id = next_package_id++;
68 } else {
69 package_id = package->GetPackageId();
70 }
71
72 // Add the mapping for package ID to index if not present.
73 uint8_t idx = package_ids_[package_id];
74 if (idx == 0xff) {
75 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
76 package_groups_.push_back({});
77 package_groups_.back().dynamic_ref_table.mAssignedPackageId = package_id;
78 }
79 PackageGroup* package_group = &package_groups_[idx];
80
81 // Add the package and to the set of packages with the same ID.
82 package_group->packages_.push_back(package.get());
83 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
84
85 // Add the package name -> build time ID mappings.
86 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
87 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
88 package_group->dynamic_ref_table.mEntries.replaceValueFor(
89 package_name, static_cast<uint8_t>(entry.package_id));
90 }
91 }
92 }
93
94 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
95 const auto package_groups_end = package_groups_.end();
96 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
97 const std::string& package_name = iter->packages_[0]->GetPackageName();
98 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
99 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
100 iter->dynamic_ref_table.mAssignedPackageId);
101 }
102 }
103}
104
105void AssetManager2::DumpToLog() const {
106 base::ScopedLogSeverity _log(base::INFO);
107
108 std::string list;
109 for (size_t i = 0; i < package_ids_.size(); i++) {
110 if (package_ids_[i] != 0xff) {
111 base::StringAppendF(&list, "%02x -> %d, ", (int) i, package_ids_[i]);
112 }
113 }
114 LOG(INFO) << "Package ID map: " << list;
115
116 for (const auto& package_group: package_groups_) {
117 list = "";
118 for (const auto& package : package_group.packages_) {
119 base::StringAppendF(&list, "%s(%02x), ", package->GetPackageName().c_str(), package->GetPackageId());
120 }
121 LOG(INFO) << base::StringPrintf("PG (%02x): ", package_group.dynamic_ref_table.mAssignedPackageId) << list;
122 }
123}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700124
125const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
126 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
127 return nullptr;
128 }
129 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
130}
131
Adam Lesinskida431a22016-12-29 16:08:16 -0500132const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
133 if (package_id >= package_ids_.size()) {
134 return nullptr;
135 }
136
137 const size_t idx = package_ids_[package_id];
138 if (idx == 0xff) {
139 return nullptr;
140 }
141 return &package_groups_[idx].dynamic_ref_table;
142}
143
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800144const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
145 for (const PackageGroup& package_group : package_groups_) {
146 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
147 if (package_cookie == cookie) {
148 return &package_group.dynamic_ref_table;
149 }
150 }
151 }
152 return nullptr;
153}
154
Adam Lesinski7ad11102016-10-28 16:39:15 -0700155void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
156 const int diff = configuration_.diff(configuration);
157 configuration_ = configuration;
158
159 if (diff) {
160 InvalidateCaches(static_cast<uint32_t>(diff));
161 }
162}
163
Adam Lesinski0c405242017-01-13 20:47:26 -0800164std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
165 bool exclude_mipmap) {
166 ATRACE_CALL();
167 std::set<ResTable_config> configurations;
168 for (const PackageGroup& package_group : package_groups_) {
169 for (const LoadedPackage* package : package_group.packages_) {
170 if (exclude_system && package->IsSystem()) {
171 continue;
172 }
173 package->CollectConfigurations(exclude_mipmap, &configurations);
174 }
175 }
176 return configurations;
177}
178
179std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
180 bool merge_equivalent_languages) {
181 ATRACE_CALL();
182 std::set<std::string> locales;
183 for (const PackageGroup& package_group : package_groups_) {
184 for (const LoadedPackage* package : package_group.packages_) {
185 if (exclude_system && package->IsSystem()) {
186 continue;
187 }
188 package->CollectLocales(merge_equivalent_languages, &locales);
189 }
190 }
191 return locales;
192}
193
Adam Lesinski7ad11102016-10-28 16:39:15 -0700194std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, Asset::AccessMode mode) {
195 const std::string new_path = "assets/" + filename;
196 return OpenNonAsset(new_path, mode);
197}
198
199std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
200 Asset::AccessMode mode) {
201 const std::string new_path = "assets/" + filename;
202 return OpenNonAsset(new_path, cookie, mode);
203}
204
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800205std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) {
206 ATRACE_CALL();
207
208 std::string full_path = "assets/" + dirname;
209 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
210 util::make_unique<SortedVector<AssetDir::FileInfo>>();
211
212 // Start from the back.
213 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
214 const ApkAssets* apk_assets = *iter;
215
216 auto func = [&](const StringPiece& name, FileType type) {
217 AssetDir::FileInfo info;
218 info.setFileName(String8(name.data(), name.size()));
219 info.setFileType(type);
220 info.setSourceName(String8(apk_assets->GetPath().c_str()));
221 files->add(info);
222 };
223
224 if (!apk_assets->ForEachFile(full_path, func)) {
225 return {};
226 }
227 }
228
229 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
230 asset_dir->setFileList(files.release());
231 return asset_dir;
232}
233
Adam Lesinski7ad11102016-10-28 16:39:15 -0700234// Search in reverse because that's how we used to do it and we need to preserve behaviour.
235// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
236// is inconsistent for split APKs.
237std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
238 Asset::AccessMode mode,
239 ApkAssetsCookie* out_cookie) {
240 ATRACE_CALL();
241 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
242 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
243 if (asset) {
244 if (out_cookie != nullptr) {
245 *out_cookie = i;
246 }
247 return asset;
248 }
249 }
250
251 if (out_cookie != nullptr) {
252 *out_cookie = kInvalidCookie;
253 }
254 return {};
255}
256
257std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
258 ApkAssetsCookie cookie, Asset::AccessMode mode) {
259 ATRACE_CALL();
260 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
261 return {};
262 }
263 return apk_assets_[cookie]->Open(filename, mode);
264}
265
266ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700267 bool stop_at_first_match, FindEntryResult* out_entry) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700268 ATRACE_CALL();
269
270 // Might use this if density_override != 0.
271 ResTable_config density_override_config;
272
273 // Select our configuration or generate a density override configuration.
274 ResTable_config* desired_config = &configuration_;
275 if (density_override != 0 && density_override != configuration_.density) {
276 density_override_config = configuration_;
277 density_override_config.density = density_override;
278 desired_config = &density_override_config;
279 }
280
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800281 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500282 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
283 return kInvalidCookie;
284 }
285
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800286 const uint32_t package_id = get_package_id(resid);
287 const uint8_t type_idx = get_type_id(resid) - 1;
288 const uint16_t entry_id = get_entry_id(resid);
289
Adam Lesinskida431a22016-12-29 16:08:16 -0500290 const uint8_t idx = package_ids_[package_id];
291 if (idx == 0xff) {
292 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
293 return kInvalidCookie;
294 }
295
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700296 FindEntryResult best_entry;
Adam Lesinskida431a22016-12-29 16:08:16 -0500297 ApkAssetsCookie best_cookie = kInvalidCookie;
298 uint32_t cumulated_flags = 0u;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700299
Adam Lesinskida431a22016-12-29 16:08:16 -0500300 const PackageGroup& package_group = package_groups_[idx];
301 const size_t package_count = package_group.packages_.size();
Adam Lesinski498f6052017-11-29 13:24:29 -0800302 FindEntryResult current_entry;
Adam Lesinskida431a22016-12-29 16:08:16 -0500303 for (size_t i = 0; i < package_count; i++) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500304 const LoadedPackage* loaded_package = package_group.packages_[i];
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700305 if (!loaded_package->FindEntry(type_idx, entry_id, *desired_config, &current_entry)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700306 continue;
307 }
308
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700309 cumulated_flags |= current_entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700310
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700311 const ResTable_config* current_config = current_entry.config;
312 const ResTable_config* best_config = best_entry.config;
313 if (best_cookie == kInvalidCookie ||
314 current_config->isBetterThan(*best_config, desired_config) ||
315 (loaded_package->IsOverlay() && current_config->compare(*best_config) == 0)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700316 best_entry = current_entry;
Adam Lesinskida431a22016-12-29 16:08:16 -0500317 best_cookie = package_group.cookies_[i];
Adam Lesinski7ad11102016-10-28 16:39:15 -0700318 if (stop_at_first_match) {
319 break;
320 }
321 }
322 }
323
Adam Lesinskida431a22016-12-29 16:08:16 -0500324 if (best_cookie == kInvalidCookie) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700325 return kInvalidCookie;
326 }
327
328 *out_entry = best_entry;
Adam Lesinskida431a22016-12-29 16:08:16 -0500329 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700330 out_entry->type_flags = cumulated_flags;
Adam Lesinskida431a22016-12-29 16:08:16 -0500331 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700332}
333
334bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) {
335 ATRACE_CALL();
336
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700337 FindEntryResult entry;
338 ApkAssetsCookie cookie =
339 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700340 if (cookie == kInvalidCookie) {
341 return false;
342 }
343
Adam Lesinskida431a22016-12-29 16:08:16 -0500344 const LoadedPackage* package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageForId(resid);
345 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700346 return false;
347 }
348
Adam Lesinskida431a22016-12-29 16:08:16 -0500349 out_name->package = package->GetPackageName().data();
350 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700351
352 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
353 out_name->type16 = nullptr;
354 if (out_name->type == nullptr) {
355 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
356 if (out_name->type16 == nullptr) {
357 return false;
358 }
359 }
360
361 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
362 out_name->entry16 = nullptr;
363 if (out_name->entry == nullptr) {
364 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
365 if (out_name->entry16 == nullptr) {
366 return false;
367 }
368 }
369 return true;
370}
371
372bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700373 FindEntryResult entry;
374 ApkAssetsCookie cookie =
375 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
376 if (cookie != kInvalidCookie) {
377 *out_flags = entry.type_flags;
378 return cookie;
379 }
380 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700381}
382
383ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
384 uint16_t density_override, Res_value* out_value,
385 ResTable_config* out_selected_config,
386 uint32_t* out_flags) {
387 ATRACE_CALL();
388
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700389 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700390 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700391 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700392 if (cookie == kInvalidCookie) {
393 return kInvalidCookie;
394 }
395
Adam Lesinski498f6052017-11-29 13:24:29 -0800396 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700397 if (!may_be_bag) {
398 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800399 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700400 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800401
402 // Create a reference since we can't represent this complex type as a Res_value.
403 out_value->dataType = Res_value::TYPE_REFERENCE;
404 out_value->data = resid;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700405 *out_selected_config = *entry.config;
406 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800407 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700408 }
409
410 const Res_value* device_value = reinterpret_cast<const Res_value*>(
411 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
412 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500413
414 // Convert the package ID to the runtime assigned package ID.
415 entry.dynamic_ref_table->lookupResourceValue(out_value);
416
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700417 *out_selected_config = *entry.config;
418 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700419 return cookie;
420}
421
Adam Lesinski0c405242017-01-13 20:47:26 -0800422ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
423 ResTable_config* in_out_selected_config,
424 uint32_t* in_out_flags,
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800425 uint32_t* out_last_reference) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800426 ATRACE_CALL();
427 constexpr const int kMaxIterations = 20;
428
Adam Lesinski0c405242017-01-13 20:47:26 -0800429 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
430 in_out_value->data != 0u && iteration < kMaxIterations;
431 iteration++) {
432 if (out_last_reference != nullptr) {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800433 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800434 }
435 uint32_t new_flags = 0u;
436 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
437 in_out_value, in_out_selected_config, &new_flags);
438 if (cookie == kInvalidCookie) {
439 return kInvalidCookie;
440 }
441 if (in_out_flags != nullptr) {
442 *in_out_flags |= new_flags;
443 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800444 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800445 // This reference can't be resolved, so exit now and let the caller deal with it.
446 return cookie;
447 }
448 }
449 return cookie;
450}
451
Adam Lesinski7ad11102016-10-28 16:39:15 -0700452const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
453 ATRACE_CALL();
454
455 auto cached_iter = cached_bags_.find(resid);
456 if (cached_iter != cached_bags_.end()) {
457 return cached_iter->second.get();
458 }
459
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700460 FindEntryResult entry;
461 ApkAssetsCookie cookie =
462 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700463 if (cookie == kInvalidCookie) {
464 return nullptr;
465 }
466
467 // Check that the size of the entry header is at least as big as
468 // the desired ResTable_map_entry. Also verify that the entry
469 // was intended to be a map.
470 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
471 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
472 // Not a bag, nothing to do.
473 return nullptr;
474 }
475
476 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
477 const ResTable_map* map_entry =
478 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
479 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
480
Adam Lesinskida431a22016-12-29 16:08:16 -0500481 uint32_t parent_resid = dtohl(map->parent.ident);
482 if (parent_resid == 0) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700483 // There is no parent, meaning there is nothing to inherit and we can do a simple
484 // copy of the entries in the map.
485 const size_t entry_count = map_entry_end - map_entry;
486 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
487 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
488 ResolvedBag::Entry* new_entry = new_bag->entries;
489 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500490 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800491 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500492 // Attributes, arrays, etc don't have a resource id as the name. They specify
493 // other data, which would be wrong to change via a lookup.
494 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
495 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key, resid);
496 return nullptr;
497 }
498 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700499 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500500 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700501 new_entry->key_pool = nullptr;
502 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700503 new_entry->value.copyFrom_dtoh(map_entry->value);
504 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
505 if (err != NO_ERROR) {
506 LOG(ERROR) << base::StringPrintf(
507 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
508 new_entry->value.data, new_key);
509 return nullptr;
510 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700511 ++new_entry;
512 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700513 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700514 new_bag->entry_count = static_cast<uint32_t>(entry_count);
515 ResolvedBag* result = new_bag.get();
516 cached_bags_[resid] = std::move(new_bag);
517 return result;
518 }
519
Adam Lesinskida431a22016-12-29 16:08:16 -0500520 // In case the parent is a dynamic reference, resolve it.
521 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
522
Adam Lesinski7ad11102016-10-28 16:39:15 -0700523 // Get the parent and do a merge of the keys.
Adam Lesinskida431a22016-12-29 16:08:16 -0500524 const ResolvedBag* parent_bag = GetBag(parent_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700525 if (parent_bag == nullptr) {
526 // Failed to get the parent that should exist.
Adam Lesinskida431a22016-12-29 16:08:16 -0500527 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid, resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700528 return nullptr;
529 }
530
Adam Lesinski7ad11102016-10-28 16:39:15 -0700531 // Create the max possible entries we can make. Once we construct the bag,
532 // we will realloc to fit to size.
533 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700534 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
535 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700536 ResolvedBag::Entry* new_entry = new_bag->entries;
537
538 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
539 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
540
541 // The keys are expected to be in sorted order. Merge the two bags.
542 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500543 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800544 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500545 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
546 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key, resid);
547 return nullptr;
548 }
549 }
550
Adam Lesinski7ad11102016-10-28 16:39:15 -0700551 if (child_key <= parent_entry->key) {
552 // Use the child key if it comes before the parent
553 // or is equal to the parent (overrides).
554 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700555 new_entry->key = child_key;
556 new_entry->key_pool = nullptr;
557 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700558 new_entry->value.copyFrom_dtoh(map_entry->value);
559 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
560 if (err != NO_ERROR) {
561 LOG(ERROR) << base::StringPrintf(
562 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
563 new_entry->value.data, child_key);
564 return nullptr;
565 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700566 ++map_entry;
567 } else {
568 // Take the parent entry as-is.
569 memcpy(new_entry, parent_entry, sizeof(*new_entry));
570 }
571
572 if (child_key >= parent_entry->key) {
573 // Move to the next parent entry if we used it or it was overridden.
574 ++parent_entry;
575 }
576 // Increment to the next entry to fill.
577 ++new_entry;
578 }
579
580 // Finish the child entries if they exist.
581 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500582 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800583 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500584 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
585 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key, resid);
586 return nullptr;
587 }
588 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700589 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500590 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700591 new_entry->key_pool = nullptr;
592 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700593 new_entry->value.copyFrom_dtoh(map_entry->value);
594 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
595 if (err != NO_ERROR) {
596 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
597 new_entry->value.dataType, new_entry->value.data, new_key);
598 return nullptr;
599 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700600 ++map_entry;
601 ++new_entry;
602 }
603
604 // Finish the parent entries if they exist.
605 if (parent_entry != parent_entry_end) {
606 // Take the rest of the parent entries as-is.
607 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
608 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
609 new_entry += num_entries_to_copy;
610 }
611
612 // Resize the resulting array to fit.
613 const size_t actual_count = new_entry - new_bag->entries;
614 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700615 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
616 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700617 }
618
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700619 // Combine flags from the parent and our own bag.
620 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700621 new_bag->entry_count = static_cast<uint32_t>(actual_count);
622 ResolvedBag* result = new_bag.get();
623 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700624 return result;
625}
626
Adam Lesinski929d6512017-01-16 19:11:19 -0800627static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
628 ssize_t len =
629 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
630 if (len < 0) {
631 return false;
632 }
633 out->resize(static_cast<size_t>(len));
634 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
635 static_cast<size_t>(len + 1));
636 return true;
637}
638
Adam Lesinski0c405242017-01-13 20:47:26 -0800639uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
640 const std::string& fallback_type,
641 const std::string& fallback_package) {
Adam Lesinski929d6512017-01-16 19:11:19 -0800642 StringPiece package_name, type, entry;
643 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
644 return 0u;
645 }
646
647 if (entry.empty()) {
648 return 0u;
649 }
650
651 if (package_name.empty()) {
652 package_name = fallback_package;
653 }
654
655 if (type.empty()) {
656 type = fallback_type;
657 }
658
659 std::u16string type16;
660 if (!Utf8ToUtf16(type, &type16)) {
661 return 0u;
662 }
663
664 std::u16string entry16;
665 if (!Utf8ToUtf16(entry, &entry16)) {
666 return 0u;
667 }
668
669 const StringPiece16 kAttr16 = u"attr";
670 const static std::u16string kAttrPrivate16 = u"^attr-private";
671
672 for (const PackageGroup& package_group : package_groups_) {
673 for (const LoadedPackage* package : package_group.packages_) {
674 if (package_name != package->GetPackageName()) {
675 // All packages in the same group are expected to have the same package name.
676 break;
677 }
678
679 uint32_t resid = package->FindEntryByName(type16, entry16);
680 if (resid == 0u && kAttr16 == type16) {
681 // Private attributes in libraries (such as the framework) are sometimes encoded
682 // under the type '^attr-private' in order to leave the ID space of public 'attr'
683 // free for future additions. Check '^attr-private' for the same name.
684 resid = package->FindEntryByName(kAttrPrivate16, entry16);
685 }
686
687 if (resid != 0u) {
688 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
689 }
690 }
691 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800692 return 0u;
693}
694
Adam Lesinski7ad11102016-10-28 16:39:15 -0700695void AssetManager2::InvalidateCaches(uint32_t diff) {
696 if (diff == 0xffffffffu) {
697 // Everything must go.
698 cached_bags_.clear();
699 return;
700 }
701
702 // Be more conservative with what gets purged. Only if the bag has other possible
703 // variations with respect to what changed (diff) should we remove it.
704 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
705 if (diff & iter->second->type_spec_flags) {
706 iter = cached_bags_.erase(iter);
707 } else {
708 ++iter;
709 }
710 }
711}
712
Adam Lesinski30080e22017-10-16 16:18:09 -0700713std::unique_ptr<Theme> AssetManager2::NewTheme() {
714 return std::unique_ptr<Theme>(new Theme(this));
715}
716
717Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
718}
719
720Theme::~Theme() = default;
721
722namespace {
723
724struct ThemeEntry {
725 ApkAssetsCookie cookie;
726 uint32_t type_spec_flags;
727 Res_value value;
728};
729
730struct ThemeType {
731 int entry_count;
732 ThemeEntry entries[0];
733};
734
735constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
736
737} // namespace
738
739struct Theme::Package {
740 // Each element of Type will be a dynamically sized object
741 // allocated to have the entries stored contiguously with the Type.
742 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
743};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700744
745bool Theme::ApplyStyle(uint32_t resid, bool force) {
746 ATRACE_CALL();
747
748 const ResolvedBag* bag = asset_manager_->GetBag(resid);
749 if (bag == nullptr) {
750 return false;
751 }
752
753 // Merge the flags from this style.
754 type_spec_flags_ |= bag->type_spec_flags;
755
Adam Lesinski30080e22017-10-16 16:18:09 -0700756 int last_type_idx = -1;
757 int last_package_idx = -1;
758 Package* last_package = nullptr;
759 ThemeType* last_type = nullptr;
760
761 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
762 // need to perform one resize per type.
763 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
764 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
765 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700766 const uint32_t attr_resid = bag_iter->key;
767
Adam Lesinski30080e22017-10-16 16:18:09 -0700768 // If the resource ID passed in is not a style, the key can be some other identifier that is not
769 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800770 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700771 return false;
772 }
773
Adam Lesinski30080e22017-10-16 16:18:09 -0700774 // We don't use the 0-based index for the type so that we can avoid doing ID validation
775 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
776 // the construction of this type is guarded with a resource ID check, it will never be
777 // populated, and querying type ID 0 will always fail.
778 const int package_idx = get_package_id(attr_resid);
779 const int type_idx = get_type_id(attr_resid);
780 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700781
Adam Lesinski30080e22017-10-16 16:18:09 -0700782 if (last_package_idx != package_idx) {
783 std::unique_ptr<Package>& package = packages_[package_idx];
784 if (package == nullptr) {
785 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700786 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700787 last_package_idx = package_idx;
788 last_package = package.get();
789 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700790 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700791
792 if (last_type_idx != type_idx) {
793 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
794 if (type == nullptr) {
795 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
796 // a sorted list of attributes, this shouldn't be resized again during this method call.
797 type.reset(reinterpret_cast<ThemeType*>(
798 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
799 type->entry_count = entry_idx + 1;
800 } else if (entry_idx >= type->entry_count) {
801 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
802 // a sorted list of attributes, this shouldn't be resized again during this method call.
803 const int new_count = entry_idx + 1;
804 type.reset(reinterpret_cast<ThemeType*>(
805 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
806
807 // Clear out the newly allocated space (which isn't zeroed).
808 memset(type->entries + type->entry_count, 0,
809 (new_count - type->entry_count) * sizeof(ThemeEntry));
810 type->entry_count = new_count;
811 }
812 last_type_idx = type_idx;
813 last_type = type.get();
814 }
815
816 ThemeEntry& entry = last_type->entries[entry_idx];
817 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
818 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700819 entry.cookie = bag_iter->cookie;
820 entry.type_spec_flags |= bag->type_spec_flags;
821 entry.value = bag_iter->value;
822 }
823 }
824 return true;
825}
826
827ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
828 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -0700829 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700830
831 uint32_t type_spec_flags = 0u;
832
Adam Lesinski30080e22017-10-16 16:18:09 -0700833 do {
834 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700835 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -0700836 if (package != nullptr) {
837 // The themes are constructed with a 1-based type ID, so no need to decrement here.
838 const int type_idx = get_type_id(resid);
839 const ThemeType* type = package->types[type_idx].get();
840 if (type != nullptr) {
841 const int entry_idx = get_entry_id(resid);
842 if (entry_idx < type->entry_count) {
843 const ThemeEntry& entry = type->entries[entry_idx];
844 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700845
Adam Lesinski30080e22017-10-16 16:18:09 -0700846 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
847 if (cnt > 0) {
848 cnt--;
849 resid = entry.value.data;
850 continue;
851 }
852 return kInvalidCookie;
853 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700854
Adam Lesinski30080e22017-10-16 16:18:09 -0700855 // @null is different than @empty.
856 if (entry.value.dataType == Res_value::TYPE_NULL &&
857 entry.value.data != Res_value::DATA_NULL_EMPTY) {
858 return kInvalidCookie;
859 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700860
Adam Lesinski30080e22017-10-16 16:18:09 -0700861 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -0500862 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -0700863 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500864 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500865 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700866 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700867 break;
868 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700869 return kInvalidCookie;
870}
871
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800872ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
873 ResTable_config* in_out_selected_config,
874 uint32_t* in_out_type_spec_flags,
875 uint32_t* out_last_ref) {
876 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
877 uint32_t new_flags;
878 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
879 if (cookie == kInvalidCookie) {
880 return kInvalidCookie;
881 }
882
883 if (in_out_type_spec_flags != nullptr) {
884 *in_out_type_spec_flags |= new_flags;
885 }
886 }
887 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
888 in_out_type_spec_flags, out_last_ref);
889}
890
Adam Lesinski7ad11102016-10-28 16:39:15 -0700891void Theme::Clear() {
892 type_spec_flags_ = 0u;
893 for (std::unique_ptr<Package>& package : packages_) {
894 package.reset();
895 }
896}
897
898bool Theme::SetTo(const Theme& o) {
899 if (this == &o) {
900 return true;
901 }
902
Adam Lesinski7ad11102016-10-28 16:39:15 -0700903 type_spec_flags_ = o.type_spec_flags_;
904
Adam Lesinski03ebac82017-09-25 13:10:14 -0700905 const bool copy_only_system = asset_manager_ != o.asset_manager_;
906
Adam Lesinskida431a22016-12-29 16:08:16 -0500907 for (size_t p = 0; p < packages_.size(); p++) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700908 const Package* package = o.packages_[p].get();
Adam Lesinski03ebac82017-09-25 13:10:14 -0700909 if (package == nullptr || (copy_only_system && p != 0x01)) {
910 // The other theme doesn't have this package, clear ours.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700911 packages_[p].reset();
912 continue;
913 }
914
Adam Lesinski03ebac82017-09-25 13:10:14 -0700915 if (packages_[p] == nullptr) {
916 // The other theme has this package, but we don't. Make one.
917 packages_[p].reset(new Package());
918 }
919
Adam Lesinskida431a22016-12-29 16:08:16 -0500920 for (size_t t = 0; t < package->types.size(); t++) {
Adam Lesinski30080e22017-10-16 16:18:09 -0700921 const ThemeType* type = package->types[t].get();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700922 if (type == nullptr) {
Adam Lesinski03ebac82017-09-25 13:10:14 -0700923 // The other theme doesn't have this type, clear ours.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700924 packages_[p]->types[t].reset();
925 continue;
926 }
927
Adam Lesinski03ebac82017-09-25 13:10:14 -0700928 // Create a new type and update it to theirs.
Adam Lesinski30080e22017-10-16 16:18:09 -0700929 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700930 void* copied_data = malloc(type_alloc_size);
931 memcpy(copied_data, type, type_alloc_size);
Adam Lesinski30080e22017-10-16 16:18:09 -0700932 packages_[p]->types[t].reset(reinterpret_cast<ThemeType*>(copied_data));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700933 }
934 }
935 return true;
936}
937
938} // namespace android