blob: d7b84ff1060d28165d1cc5c7d71bfa49b234fc4e [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
y57cd1952018-04-12 14:26:23 -070021#include <algorithm>
Adam Lesinski30080e22017-10-16 16:18:09 -070022#include <iterator>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070023#include <map>
Winson2f3669b2019-01-11 11:28:34 -080024#include <set>
25#include <sstream>
Adam Lesinski0c405242017-01-13 20:47:26 -080026
Adam Lesinski7ad11102016-10-28 16:39:15 -070027#include "android-base/logging.h"
28#include "android-base/stringprintf.h"
29#include "utils/ByteOrder.h"
30#include "utils/Trace.h"
31
32#ifdef _WIN32
33#ifdef ERROR
34#undef ERROR
35#endif
36#endif
37
Adam Lesinski929d6512017-01-16 19:11:19 -080038#include "androidfw/ResourceUtils.h"
39
Adam Lesinski7ad11102016-10-28 16:39:15 -070040namespace android {
41
Adam Lesinskibebfcc42018-02-12 14:27:46 -080042struct FindEntryResult {
43 // A pointer to the resource table entry for this resource.
44 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
45 // a ResTable_map_entry and processed as a bag/map.
46 const ResTable_entry* entry;
47
48 // The configuration for which the resulting entry was defined. This is already swapped to host
49 // endianness.
50 ResTable_config config;
51
52 // The bitmask of configuration axis with which the resource value varies.
53 uint32_t type_flags;
54
55 // The dynamic package ID map for the package from which this resource came from.
56 const DynamicRefTable* dynamic_ref_table;
57
58 // The string pool reference to the type's name. This uses a different string pool than
59 // the global string pool, but this is hidden from the caller.
60 StringPoolRef type_string_ref;
61
62 // The string pool reference to the entry's name. This uses a different string pool than
63 // the global string pool, but this is hidden from the caller.
64 StringPoolRef entry_string_ref;
65};
66
Adam Lesinski970bd8d2017-09-25 13:21:55 -070067AssetManager2::AssetManager2() {
68 memset(&configuration_, 0, sizeof(configuration_));
69}
Adam Lesinski7ad11102016-10-28 16:39:15 -070070
71bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020072 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070073 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050074 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020075 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070076 if (invalidate_caches) {
77 InvalidateCaches(static_cast<uint32_t>(-1));
78 }
79 return true;
80}
81
Adam Lesinskida431a22016-12-29 16:08:16 -050082void AssetManager2::BuildDynamicRefTable() {
83 package_groups_.clear();
84 package_ids_.fill(0xff);
85
86 // 0x01 is reserved for the android package.
87 int next_package_id = 0x02;
88 const size_t apk_assets_count = apk_assets_.size();
89 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070090 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
91
92 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050093 // Get the package ID or assign one if a shared library.
94 int package_id;
95 if (package->IsDynamic()) {
96 package_id = next_package_id++;
97 } else {
98 package_id = package->GetPackageId();
99 }
100
101 // Add the mapping for package ID to index if not present.
102 uint8_t idx = package_ids_[package_id];
103 if (idx == 0xff) {
104 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
105 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800106 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
107 ref_table.mAssignedPackageId = package_id;
108 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500109 }
110 PackageGroup* package_group = &package_groups_[idx];
111
112 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800113 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500114 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
115
116 // Add the package name -> build time ID mappings.
117 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
118 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
119 package_group->dynamic_ref_table.mEntries.replaceValueFor(
120 package_name, static_cast<uint8_t>(entry.package_id));
121 }
122 }
123 }
124
125 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
126 const auto package_groups_end = package_groups_.end();
127 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800128 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500129 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
130 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
131 iter->dynamic_ref_table.mAssignedPackageId);
132 }
133 }
134}
135
136void AssetManager2::DumpToLog() const {
137 base::ScopedLogSeverity _log(base::INFO);
138
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800139 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
140
Adam Lesinskida431a22016-12-29 16:08:16 -0500141 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800142 for (const auto& apk_assets : apk_assets_) {
143 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
144 }
145 LOG(INFO) << "ApkAssets: " << list;
146
147 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500148 for (size_t i = 0; i < package_ids_.size(); i++) {
149 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800150 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500151 }
152 }
153 LOG(INFO) << "Package ID map: " << list;
154
Adam Lesinski0dd36992018-01-25 15:38:38 -0800155 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800156 list = "";
157 for (const auto& package : package_group.packages_) {
158 const LoadedPackage* loaded_package = package.loaded_package_;
159 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
160 loaded_package->GetPackageId(),
161 (loaded_package->IsDynamic() ? " dynamic" : ""));
162 }
163 LOG(INFO) << base::StringPrintf("PG (%02x): ",
164 package_group.dynamic_ref_table.mAssignedPackageId)
165 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800166
167 for (size_t i = 0; i < 256; i++) {
168 if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
169 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
170 package_group.dynamic_ref_table.mLookupTable[i]);
171 }
172 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500173 }
174}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700175
176const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
177 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
178 return nullptr;
179 }
180 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
181}
182
Adam Lesinskida431a22016-12-29 16:08:16 -0500183const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
184 if (package_id >= package_ids_.size()) {
185 return nullptr;
186 }
187
188 const size_t idx = package_ids_[package_id];
189 if (idx == 0xff) {
190 return nullptr;
191 }
192 return &package_groups_[idx].dynamic_ref_table;
193}
194
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800195const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
196 for (const PackageGroup& package_group : package_groups_) {
197 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
198 if (package_cookie == cookie) {
199 return &package_group.dynamic_ref_table;
200 }
201 }
202 }
203 return nullptr;
204}
205
Mårten Kongstadc92c4dd2019-02-05 01:29:59 +0100206const std::unordered_map<std::string, std::string>*
207 AssetManager2::GetOverlayableMapForPackage(uint32_t package_id) const {
208
209 if (package_id >= package_ids_.size()) {
210 return nullptr;
211 }
212
213 const size_t idx = package_ids_[package_id];
214 if (idx == 0xff) {
215 return nullptr;
216 }
217
218 const PackageGroup& package_group = package_groups_[idx];
219 if (package_group.packages_.size() == 0) {
220 return nullptr;
221 }
222
223 const auto loaded_package = package_group.packages_[0].loaded_package_;
224 return &loaded_package->GetOverlayableMap();
225}
226
Adam Lesinski7ad11102016-10-28 16:39:15 -0700227void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
228 const int diff = configuration_.diff(configuration);
229 configuration_ = configuration;
230
231 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800232 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700233 InvalidateCaches(static_cast<uint32_t>(diff));
234 }
235}
236
Adam Lesinski0c405242017-01-13 20:47:26 -0800237std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800238 bool exclude_mipmap) const {
239 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800240 std::set<ResTable_config> configurations;
241 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800242 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800243 for (const ConfiguredPackage& package : package_group.packages_) {
244 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800245 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800246 continue;
247 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800248
249 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
250 // Overlays must appear after the target package to take effect. Any overlay found in the
251 // same package as a system package is able to overlay system resources.
252 continue;
253 }
254
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800255 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800256 }
257 }
258 return configurations;
259}
260
261std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800262 bool merge_equivalent_languages) const {
263 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800264 std::set<std::string> locales;
265 for (const PackageGroup& package_group : package_groups_) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800266 bool found_system_package = false;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800267 for (const ConfiguredPackage& package : package_group.packages_) {
268 if (exclude_system && package.loaded_package_->IsSystem()) {
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800269 found_system_package = true;
Adam Lesinski0c405242017-01-13 20:47:26 -0800270 continue;
271 }
Ryan Mitchell449a54f2018-11-30 15:22:31 -0800272
273 if (exclude_system && package.loaded_package_->IsOverlay() && found_system_package) {
274 // Overlays must appear after the target package to take effect. Any overlay found in the
275 // same package as a system package is able to overlay system resources.
276 continue;
277 }
278
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800279 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800280 }
281 }
282 return locales;
283}
284
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800285std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
286 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700287 const std::string new_path = "assets/" + filename;
288 return OpenNonAsset(new_path, mode);
289}
290
291std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800292 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700293 const std::string new_path = "assets/" + filename;
294 return OpenNonAsset(new_path, cookie, mode);
295}
296
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800297std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
298 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800299
300 std::string full_path = "assets/" + dirname;
301 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
302 util::make_unique<SortedVector<AssetDir::FileInfo>>();
303
304 // Start from the back.
305 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
306 const ApkAssets* apk_assets = *iter;
307
308 auto func = [&](const StringPiece& name, FileType type) {
309 AssetDir::FileInfo info;
310 info.setFileName(String8(name.data(), name.size()));
311 info.setFileType(type);
312 info.setSourceName(String8(apk_assets->GetPath().c_str()));
313 files->add(info);
314 };
315
316 if (!apk_assets->ForEachFile(full_path, func)) {
317 return {};
318 }
319 }
320
321 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
322 asset_dir->setFileList(files.release());
323 return asset_dir;
324}
325
Adam Lesinski7ad11102016-10-28 16:39:15 -0700326// Search in reverse because that's how we used to do it and we need to preserve behaviour.
327// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
328// is inconsistent for split APKs.
329std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
330 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800331 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700332 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
333 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
334 if (asset) {
335 if (out_cookie != nullptr) {
336 *out_cookie = i;
337 }
338 return asset;
339 }
340 }
341
342 if (out_cookie != nullptr) {
343 *out_cookie = kInvalidCookie;
344 }
345 return {};
346}
347
348std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800349 ApkAssetsCookie cookie,
350 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700351 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
352 return {};
353 }
354 return apk_assets_[cookie]->Open(filename, mode);
355}
356
357ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800358 bool /*stop_at_first_match*/,
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800359 bool ignore_configuration,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800360 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700361 // Might use this if density_override != 0.
362 ResTable_config density_override_config;
363
364 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800365 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700366 if (density_override != 0 && density_override != configuration_.density) {
367 density_override_config = configuration_;
368 density_override_config.density = density_override;
369 desired_config = &density_override_config;
370 }
371
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800372 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500373 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
374 return kInvalidCookie;
375 }
376
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800377 const uint32_t package_id = get_package_id(resid);
378 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800379 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800380
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800381 const uint8_t package_idx = package_ids_[package_id];
382 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500383 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
384 return kInvalidCookie;
385 }
386
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800387 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800388 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800389
390 ApkAssetsCookie best_cookie = kInvalidCookie;
391 const LoadedPackage* best_package = nullptr;
392 const ResTable_type* best_type = nullptr;
393 const ResTable_config* best_config = nullptr;
394 ResTable_config best_config_copy;
395 uint32_t best_offset = 0u;
396 uint32_t type_flags = 0u;
397
Winson2f3669b2019-01-11 11:28:34 -0800398 Resolution::Step::Type resolution_type;
399 std::vector<Resolution::Step> resolution_steps;
400
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800401 // If desired_config is the same as the set configuration, then we can use our filtered list
402 // and we don't need to match the configurations, since they already matched.
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800403 const bool use_fast_path = !ignore_configuration && desired_config == &configuration_;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800404
405 for (size_t pi = 0; pi < package_count; pi++) {
406 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
407 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
408 ApkAssetsCookie cookie = package_group.cookies_[pi];
409
410 // If the type IDs are offset in this package, we need to take that into account when searching
411 // for a type.
412 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
413 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700414 continue;
415 }
416
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800417 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700418
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800419 // If there is an IDMAP supplied with this package, translate the entry ID.
420 if (type_spec->idmap_entries != nullptr) {
421 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
422 // There is no mapping, so the resource is not meant to be in this overlay package.
423 continue;
424 }
425 }
426
427 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
428
429 // If the package is an overlay, then even configurations that are the same MUST be chosen.
430 const bool package_is_overlay = loaded_package->IsOverlay();
431
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800432 if (use_fast_path) {
Winson2f3669b2019-01-11 11:28:34 -0800433 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800434 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
435 const size_t type_count = candidate_configs.size();
436 for (uint32_t i = 0; i < type_count; i++) {
437 const ResTable_config& this_config = candidate_configs[i];
438
439 // We can skip calling ResTable_config::match() because we know that all candidate
440 // configurations that do NOT match have been filtered-out.
Winson2f3669b2019-01-11 11:28:34 -0800441 if (best_config == nullptr) {
442 resolution_type = Resolution::Step::Type::INITIAL;
443 } else if (this_config.isBetterThan(*best_config, desired_config)) {
444 resolution_type = Resolution::Step::Type::BETTER_MATCH;
445 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
446 resolution_type = Resolution::Step::Type::OVERLAID;
447 } else {
448 continue;
449 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800450
Winson2f3669b2019-01-11 11:28:34 -0800451 // The configuration matches and is better than the previous selection.
452 // Find the entry value if it exists for this configuration.
453 const ResTable_type* type = filtered_group.types[i];
454 const uint32_t offset = LoadedPackage::GetEntryOffset(type, local_entry_idx);
455 if (offset == ResTable_type::NO_ENTRY) {
456 continue;
457 }
458
459 best_cookie = cookie;
460 best_package = loaded_package;
461 best_type = type;
462 best_config = &this_config;
463 best_offset = offset;
464
465 if (resource_resolution_logging_enabled_) {
466 resolution_steps.push_back(Resolution::Step{resolution_type,
467 this_config.toString(),
468 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800469 }
470 }
471 } else {
472 // This is the slower path, which doesn't use the filtered list of configurations.
473 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
474 // and fill in any new fields that did not exist when the APK was compiled.
475 // Furthermore when selecting configurations we can't just record the pointer to the
476 // ResTable_config, we must copy it.
477 const auto iter_end = type_spec->types + type_spec->type_count;
478 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800479 ResTable_config this_config{};
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800480
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800481 if (!ignore_configuration) {
482 this_config.copyFromDtoH((*iter)->config);
483 if (!this_config.match(*desired_config)) {
484 continue;
485 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800486
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800487 if (best_config == nullptr) {
488 resolution_type = Resolution::Step::Type::INITIAL;
489 } else if (this_config.isBetterThan(*best_config, desired_config)) {
490 resolution_type = Resolution::Step::Type::BETTER_MATCH;
491 } else if (package_is_overlay && this_config.compare(*best_config) == 0) {
492 resolution_type = Resolution::Step::Type::OVERLAID;
493 } else {
494 continue;
495 }
Winson2f3669b2019-01-11 11:28:34 -0800496 }
497
498 // The configuration matches and is better than the previous selection.
499 // Find the entry value if it exists for this configuration.
500 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
501 if (offset == ResTable_type::NO_ENTRY) {
502 continue;
503 }
504
505 best_cookie = cookie;
506 best_package = loaded_package;
507 best_type = *iter;
508 best_config_copy = this_config;
509 best_config = &best_config_copy;
510 best_offset = offset;
511
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800512 if (ignore_configuration) {
513 // Any configuration will suffice, so break.
514 break;
515 }
516
Winson2f3669b2019-01-11 11:28:34 -0800517 if (resource_resolution_logging_enabled_) {
518 resolution_steps.push_back(Resolution::Step{resolution_type,
519 this_config.toString(),
520 &loaded_package->GetPackageName()});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800521 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700522 }
523 }
524 }
525
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800526 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700527 return kInvalidCookie;
528 }
529
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800530 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
531 if (UNLIKELY(best_entry == nullptr)) {
532 return kInvalidCookie;
533 }
534
535 out_entry->entry = best_entry;
536 out_entry->config = *best_config;
537 out_entry->type_flags = type_flags;
538 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
539 out_entry->entry_string_ref =
540 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500541 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Winson2f3669b2019-01-11 11:28:34 -0800542
543 if (resource_resolution_logging_enabled_) {
544 last_resolution.resid = resid;
545 last_resolution.cookie = best_cookie;
546 last_resolution.steps = resolution_steps;
547
548 // Cache only the type/entry refs since that's all that's needed to build name
549 last_resolution.type_string_ref =
550 StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
551 last_resolution.entry_string_ref =
552 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
553 }
554
Adam Lesinskida431a22016-12-29 16:08:16 -0500555 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700556}
557
Winson2f3669b2019-01-11 11:28:34 -0800558void AssetManager2::SetResourceResolutionLoggingEnabled(bool enabled) {
559 resource_resolution_logging_enabled_ = enabled;
560
561 if (!enabled) {
562 last_resolution.cookie = kInvalidCookie;
563 last_resolution.resid = 0;
564 last_resolution.steps.clear();
565 last_resolution.type_string_ref = StringPoolRef();
566 last_resolution.entry_string_ref = StringPoolRef();
567 }
568}
569
570std::string AssetManager2::GetLastResourceResolution() const {
571 if (!resource_resolution_logging_enabled_) {
572 LOG(ERROR) << "Must enable resource resolution logging before getting path.";
573 return std::string();
574 }
575
576 auto cookie = last_resolution.cookie;
577 if (cookie == kInvalidCookie) {
578 LOG(ERROR) << "AssetManager hasn't resolved a resource to read resolution path.";
579 return std::string();
580 }
581
582 uint32_t resid = last_resolution.resid;
583 std::vector<Resolution::Step>& steps = last_resolution.steps;
584
585 ResourceName resource_name;
586 std::string resource_name_string;
587
588 const LoadedPackage* package =
589 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
590
591 if (package != nullptr) {
592 ToResourceName(last_resolution.type_string_ref,
593 last_resolution.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800594 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800595 &resource_name);
596 resource_name_string = ToFormattedResourceString(&resource_name);
597 }
598
599 std::stringstream log_stream;
600 log_stream << base::StringPrintf("Resolution for 0x%08x ", resid)
601 << resource_name_string
602 << "\n\tFor config -"
603 << configuration_.toString();
604
605 std::string prefix;
606 for (Resolution::Step step : steps) {
607 switch (step.type) {
608 case Resolution::Step::Type::INITIAL:
609 prefix = "Found initial";
610 break;
611 case Resolution::Step::Type::BETTER_MATCH:
612 prefix = "Found better";
613 break;
614 case Resolution::Step::Type::OVERLAID:
615 prefix = "Overlaid";
616 break;
617 }
618
619 if (!prefix.empty()) {
620 log_stream << "\n\t" << prefix << ": " << *step.package_name;
621
622 if (!step.config_name.isEmpty()) {
623 log_stream << " -" << step.config_name;
624 }
625 }
626 }
627
628 return log_stream.str();
629}
630
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800631bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700632 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800633 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
634 true /* stop_at_first_match */,
635 true /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700636 if (cookie == kInvalidCookie) {
637 return false;
638 }
639
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800640 const uint8_t package_idx = package_ids_[get_package_id(resid)];
641 if (package_idx == 0xff) {
642 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.",
643 get_package_id(resid), resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700644 return false;
645 }
646
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800647 const PackageGroup& package_group = package_groups_[package_idx];
648 auto cookie_iter = std::find(package_group.cookies_.begin(),
649 package_group.cookies_.end(), cookie);
650 if (cookie_iter == package_group.cookies_.end()) {
651 return false;
652 }
653
654 long package_pos = std::distance(package_group.cookies_.begin(), cookie_iter);
655 const LoadedPackage* package = package_group.packages_[package_pos].loaded_package_;
Winson2f3669b2019-01-11 11:28:34 -0800656 return ToResourceName(entry.type_string_ref,
657 entry.entry_string_ref,
Ryan Mitchell741e96f2019-01-23 16:56:51 -0800658 package->GetPackageName(),
Winson2f3669b2019-01-11 11:28:34 -0800659 out_name);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700660}
661
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800662bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700663 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800664 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
665 false /* stop_at_first_match */,
666 true /* ignore_configuration */, &entry);
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700667 if (cookie != kInvalidCookie) {
668 *out_flags = entry.type_flags;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800669 return true;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700670 }
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800671 return false;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700672}
673
674ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
675 uint16_t density_override, Res_value* out_value,
676 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800677 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700678 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800679 ApkAssetsCookie cookie = FindEntry(resid, density_override, false /* stop_at_first_match */,
680 false /* ignore_configuration */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700681 if (cookie == kInvalidCookie) {
682 return kInvalidCookie;
683 }
684
Adam Lesinski498f6052017-11-29 13:24:29 -0800685 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700686 if (!may_be_bag) {
687 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800688 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700689 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800690
691 // Create a reference since we can't represent this complex type as a Res_value.
692 out_value->dataType = Res_value::TYPE_REFERENCE;
693 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800694 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700695 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800696 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700697 }
698
699 const Res_value* device_value = reinterpret_cast<const Res_value*>(
700 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
701 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500702
703 // Convert the package ID to the runtime assigned package ID.
704 entry.dynamic_ref_table->lookupResourceValue(out_value);
705
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800706 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700707 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700708 return cookie;
709}
710
Adam Lesinski0c405242017-01-13 20:47:26 -0800711ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
712 ResTable_config* in_out_selected_config,
713 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800714 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800715 constexpr const int kMaxIterations = 20;
716
Adam Lesinski0c405242017-01-13 20:47:26 -0800717 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
718 in_out_value->data != 0u && iteration < kMaxIterations;
719 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800720 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800721 uint32_t new_flags = 0u;
722 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
723 in_out_value, in_out_selected_config, &new_flags);
724 if (cookie == kInvalidCookie) {
725 return kInvalidCookie;
726 }
727 if (in_out_flags != nullptr) {
728 *in_out_flags |= new_flags;
729 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800730 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800731 // This reference can't be resolved, so exit now and let the caller deal with it.
732 return cookie;
733 }
734 }
735 return cookie;
736}
737
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800738const std::vector<uint32_t> AssetManager2::GetBagResIdStack(uint32_t resid) {
739 auto cached_iter = cached_bag_resid_stacks_.find(resid);
740 if (cached_iter != cached_bag_resid_stacks_.end()) {
741 return cached_iter->second;
742 } else {
743 auto found_resids = std::vector<uint32_t>();
744 GetBag(resid, found_resids);
745 // Cache style stacks if they are not already cached.
746 cached_bag_resid_stacks_[resid] = found_resids;
747 return found_resids;
748 }
749}
750
Adam Lesinski7ad11102016-10-28 16:39:15 -0700751const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700752 auto found_resids = std::vector<uint32_t>();
Aurimas Liutikas8f004c82019-01-17 17:20:10 -0800753 auto bag = GetBag(resid, found_resids);
754
755 // Cache style stacks if they are not already cached.
756 auto cached_iter = cached_bag_resid_stacks_.find(resid);
757 if (cached_iter == cached_bag_resid_stacks_.end()) {
758 cached_bag_resid_stacks_[resid] = found_resids;
759 }
760 return bag;
y57cd1952018-04-12 14:26:23 -0700761}
762
763const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800764 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700765
766 auto cached_iter = cached_bags_.find(resid);
767 if (cached_iter != cached_bags_.end()) {
768 return cached_iter->second.get();
769 }
770
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700771 FindEntryResult entry;
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800772 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */,
773 false /* stop_at_first_match */,
774 false /* ignore_configuration */,
775 &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700776 if (cookie == kInvalidCookie) {
777 return nullptr;
778 }
779
780 // Check that the size of the entry header is at least as big as
781 // the desired ResTable_map_entry. Also verify that the entry
782 // was intended to be a map.
783 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
784 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
785 // Not a bag, nothing to do.
786 return nullptr;
787 }
788
789 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
790 const ResTable_map* map_entry =
791 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
792 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
793
y57cd1952018-04-12 14:26:23 -0700794 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
795 // dependencies between bags
796 child_resids.push_back(resid);
797
Adam Lesinskida431a22016-12-29 16:08:16 -0500798 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700799 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
800 != child_resids.end()) {
801 // There is no parent or that a circular dependency exist, meaning there is nothing to
802 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700803 const size_t entry_count = map_entry_end - map_entry;
804 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
805 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
806 ResolvedBag::Entry* new_entry = new_bag->entries;
807 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500808 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800809 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500810 // Attributes, arrays, etc don't have a resource id as the name. They specify
811 // other data, which would be wrong to change via a lookup.
812 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800813 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
814 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500815 return nullptr;
816 }
817 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700818 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500819 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700820 new_entry->key_pool = nullptr;
821 new_entry->type_pool = nullptr;
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800822 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700823 new_entry->value.copyFrom_dtoh(map_entry->value);
824 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
825 if (err != NO_ERROR) {
826 LOG(ERROR) << base::StringPrintf(
827 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
828 new_entry->value.data, new_key);
829 return nullptr;
830 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700831 ++new_entry;
832 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700833 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700834 new_bag->entry_count = static_cast<uint32_t>(entry_count);
835 ResolvedBag* result = new_bag.get();
836 cached_bags_[resid] = std::move(new_bag);
837 return result;
838 }
839
Adam Lesinskida431a22016-12-29 16:08:16 -0500840 // In case the parent is a dynamic reference, resolve it.
841 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
842
Adam Lesinski7ad11102016-10-28 16:39:15 -0700843 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700844 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700845 if (parent_bag == nullptr) {
846 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800847 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
848 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700849 return nullptr;
850 }
851
Adam Lesinski7ad11102016-10-28 16:39:15 -0700852 // Create the max possible entries we can make. Once we construct the bag,
853 // we will realloc to fit to size.
854 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700855 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
856 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700857 ResolvedBag::Entry* new_entry = new_bag->entries;
858
859 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
860 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
861
862 // The keys are expected to be in sorted order. Merge the two bags.
863 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500864 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800865 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500866 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800867 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
868 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500869 return nullptr;
870 }
871 }
872
Adam Lesinski7ad11102016-10-28 16:39:15 -0700873 if (child_key <= parent_entry->key) {
874 // Use the child key if it comes before the parent
875 // or is equal to the parent (overrides).
876 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700877 new_entry->key = child_key;
878 new_entry->key_pool = nullptr;
879 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700880 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800881 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700882 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
883 if (err != NO_ERROR) {
884 LOG(ERROR) << base::StringPrintf(
885 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
886 new_entry->value.data, child_key);
887 return nullptr;
888 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700889 ++map_entry;
890 } else {
891 // Take the parent entry as-is.
892 memcpy(new_entry, parent_entry, sizeof(*new_entry));
893 }
894
895 if (child_key >= parent_entry->key) {
896 // Move to the next parent entry if we used it or it was overridden.
897 ++parent_entry;
898 }
899 // Increment to the next entry to fill.
900 ++new_entry;
901 }
902
903 // Finish the child entries if they exist.
904 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500905 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800906 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500907 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800908 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
909 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500910 return nullptr;
911 }
912 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700913 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500914 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700915 new_entry->key_pool = nullptr;
916 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700917 new_entry->value.copyFrom_dtoh(map_entry->value);
Aurimas Liutikasd42a6702018-11-15 15:48:28 -0800918 new_entry->style = resid;
Adam Lesinski30080e22017-10-16 16:18:09 -0700919 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
920 if (err != NO_ERROR) {
921 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
922 new_entry->value.dataType, new_entry->value.data, new_key);
923 return nullptr;
924 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700925 ++map_entry;
926 ++new_entry;
927 }
928
929 // Finish the parent entries if they exist.
930 if (parent_entry != parent_entry_end) {
931 // Take the rest of the parent entries as-is.
932 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
933 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
934 new_entry += num_entries_to_copy;
935 }
936
937 // Resize the resulting array to fit.
938 const size_t actual_count = new_entry - new_bag->entries;
939 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700940 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
941 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700942 }
943
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700944 // Combine flags from the parent and our own bag.
945 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700946 new_bag->entry_count = static_cast<uint32_t>(actual_count);
947 ResolvedBag* result = new_bag.get();
948 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700949 return result;
950}
951
Adam Lesinski929d6512017-01-16 19:11:19 -0800952static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
953 ssize_t len =
954 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
955 if (len < 0) {
956 return false;
957 }
958 out->resize(static_cast<size_t>(len));
959 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
960 static_cast<size_t>(len + 1));
961 return true;
962}
963
Adam Lesinski0c405242017-01-13 20:47:26 -0800964uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
965 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800966 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800967 StringPiece package_name, type, entry;
968 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
969 return 0u;
970 }
971
972 if (entry.empty()) {
973 return 0u;
974 }
975
976 if (package_name.empty()) {
977 package_name = fallback_package;
978 }
979
980 if (type.empty()) {
981 type = fallback_type;
982 }
983
984 std::u16string type16;
985 if (!Utf8ToUtf16(type, &type16)) {
986 return 0u;
987 }
988
989 std::u16string entry16;
990 if (!Utf8ToUtf16(entry, &entry16)) {
991 return 0u;
992 }
993
994 const StringPiece16 kAttr16 = u"attr";
995 const static std::u16string kAttrPrivate16 = u"^attr-private";
996
997 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800998 for (const ConfiguredPackage& package_impl : package_group.packages_) {
999 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -08001000 if (package_name != package->GetPackageName()) {
1001 // All packages in the same group are expected to have the same package name.
1002 break;
1003 }
1004
1005 uint32_t resid = package->FindEntryByName(type16, entry16);
1006 if (resid == 0u && kAttr16 == type16) {
1007 // Private attributes in libraries (such as the framework) are sometimes encoded
1008 // under the type '^attr-private' in order to leave the ID space of public 'attr'
1009 // free for future additions. Check '^attr-private' for the same name.
1010 resid = package->FindEntryByName(kAttrPrivate16, entry16);
1011 }
1012
1013 if (resid != 0u) {
1014 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
1015 }
1016 }
1017 }
Adam Lesinski0c405242017-01-13 20:47:26 -08001018 return 0u;
1019}
1020
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001021void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001022 for (PackageGroup& group : package_groups_) {
1023 for (ConfiguredPackage& impl : group.packages_) {
1024 // Destroy it.
1025 impl.filtered_configs_.~ByteBucketArray();
1026
1027 // Re-create it.
1028 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
1029
1030 // Create the filters here.
1031 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
1032 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
1033 const auto iter_end = spec->types + spec->type_count;
1034 for (auto iter = spec->types; iter != iter_end; ++iter) {
1035 ResTable_config this_config;
1036 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +02001037 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001038 group.configurations.push_back(this_config);
1039 group.types.push_back(*iter);
1040 }
1041 }
1042 });
1043 }
1044 }
1045}
1046
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047void AssetManager2::InvalidateCaches(uint32_t diff) {
1048 if (diff == 0xffffffffu) {
1049 // Everything must go.
1050 cached_bags_.clear();
1051 return;
1052 }
1053
1054 // Be more conservative with what gets purged. Only if the bag has other possible
1055 // variations with respect to what changed (diff) should we remove it.
1056 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
1057 if (diff & iter->second->type_spec_flags) {
1058 iter = cached_bags_.erase(iter);
1059 } else {
1060 ++iter;
1061 }
1062 }
1063}
1064
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001065uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
1066 for (auto& package_group : package_groups_) {
1067 for (auto& package2 : package_group.packages_) {
1068 if (package2.loaded_package_ == package) {
1069 return package_group.dynamic_ref_table.mAssignedPackageId;
1070 }
1071 }
1072 }
1073 return 0;
1074}
1075
Adam Lesinski30080e22017-10-16 16:18:09 -07001076std::unique_ptr<Theme> AssetManager2::NewTheme() {
1077 return std::unique_ptr<Theme>(new Theme(this));
1078}
1079
1080Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
1081}
1082
1083Theme::~Theme() = default;
1084
1085namespace {
1086
1087struct ThemeEntry {
1088 ApkAssetsCookie cookie;
1089 uint32_t type_spec_flags;
1090 Res_value value;
1091};
1092
1093struct ThemeType {
1094 int entry_count;
1095 ThemeEntry entries[0];
1096};
1097
1098constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
1099
1100} // namespace
1101
1102struct Theme::Package {
1103 // Each element of Type will be a dynamically sized object
1104 // allocated to have the entries stored contiguously with the Type.
1105 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
1106};
Adam Lesinski7ad11102016-10-28 16:39:15 -07001107
1108bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001109 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -07001110
1111 const ResolvedBag* bag = asset_manager_->GetBag(resid);
1112 if (bag == nullptr) {
1113 return false;
1114 }
1115
1116 // Merge the flags from this style.
1117 type_spec_flags_ |= bag->type_spec_flags;
1118
Adam Lesinski30080e22017-10-16 16:18:09 -07001119 int last_type_idx = -1;
1120 int last_package_idx = -1;
1121 Package* last_package = nullptr;
1122 ThemeType* last_type = nullptr;
1123
1124 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
1125 // need to perform one resize per type.
1126 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
1127 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
1128 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001129 const uint32_t attr_resid = bag_iter->key;
1130
Adam Lesinski30080e22017-10-16 16:18:09 -07001131 // If the resource ID passed in is not a style, the key can be some other identifier that is not
1132 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -08001133 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001134 return false;
1135 }
1136
Adam Lesinski30080e22017-10-16 16:18:09 -07001137 // We don't use the 0-based index for the type so that we can avoid doing ID validation
1138 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
1139 // the construction of this type is guarded with a resource ID check, it will never be
1140 // populated, and querying type ID 0 will always fail.
1141 const int package_idx = get_package_id(attr_resid);
1142 const int type_idx = get_type_id(attr_resid);
1143 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001144
Adam Lesinski30080e22017-10-16 16:18:09 -07001145 if (last_package_idx != package_idx) {
1146 std::unique_ptr<Package>& package = packages_[package_idx];
1147 if (package == nullptr) {
1148 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -07001149 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001150 last_package_idx = package_idx;
1151 last_package = package.get();
1152 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001153 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001154
1155 if (last_type_idx != type_idx) {
1156 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
1157 if (type == nullptr) {
1158 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
1159 // a sorted list of attributes, this shouldn't be resized again during this method call.
1160 type.reset(reinterpret_cast<ThemeType*>(
1161 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
1162 type->entry_count = entry_idx + 1;
1163 } else if (entry_idx >= type->entry_count) {
1164 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
1165 // a sorted list of attributes, this shouldn't be resized again during this method call.
1166 const int new_count = entry_idx + 1;
1167 type.reset(reinterpret_cast<ThemeType*>(
1168 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
1169
1170 // Clear out the newly allocated space (which isn't zeroed).
1171 memset(type->entries + type->entry_count, 0,
1172 (new_count - type->entry_count) * sizeof(ThemeEntry));
1173 type->entry_count = new_count;
1174 }
1175 last_type_idx = type_idx;
1176 last_type = type.get();
1177 }
1178
1179 ThemeEntry& entry = last_type->entries[entry_idx];
1180 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
1181 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001182 entry.cookie = bag_iter->cookie;
1183 entry.type_spec_flags |= bag->type_spec_flags;
1184 entry.value = bag_iter->value;
1185 }
1186 }
1187 return true;
1188}
1189
1190ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1191 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001192 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001193
1194 uint32_t type_spec_flags = 0u;
1195
Adam Lesinski30080e22017-10-16 16:18:09 -07001196 do {
1197 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001198 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001199 if (package != nullptr) {
1200 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1201 const int type_idx = get_type_id(resid);
1202 const ThemeType* type = package->types[type_idx].get();
1203 if (type != nullptr) {
1204 const int entry_idx = get_entry_id(resid);
1205 if (entry_idx < type->entry_count) {
1206 const ThemeEntry& entry = type->entries[entry_idx];
1207 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001208
Adam Lesinski30080e22017-10-16 16:18:09 -07001209 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1210 if (cnt > 0) {
1211 cnt--;
1212 resid = entry.value.data;
1213 continue;
1214 }
1215 return kInvalidCookie;
1216 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001217
Adam Lesinski30080e22017-10-16 16:18:09 -07001218 // @null is different than @empty.
1219 if (entry.value.dataType == Res_value::TYPE_NULL &&
1220 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1221 return kInvalidCookie;
1222 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001223
Adam Lesinski30080e22017-10-16 16:18:09 -07001224 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001225 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001226 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001227 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001228 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001229 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001230 break;
1231 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001232 return kInvalidCookie;
1233}
1234
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001235ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1236 ResTable_config* in_out_selected_config,
1237 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001238 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001239 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1240 uint32_t new_flags;
1241 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1242 if (cookie == kInvalidCookie) {
1243 return kInvalidCookie;
1244 }
1245
1246 if (in_out_type_spec_flags != nullptr) {
1247 *in_out_type_spec_flags |= new_flags;
1248 }
1249 }
1250 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1251 in_out_type_spec_flags, out_last_ref);
1252}
1253
Adam Lesinski7ad11102016-10-28 16:39:15 -07001254void Theme::Clear() {
1255 type_spec_flags_ = 0u;
1256 for (std::unique_ptr<Package>& package : packages_) {
1257 package.reset();
1258 }
1259}
1260
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001261void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001262 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001263 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001264 }
1265
Adam Lesinski7ad11102016-10-28 16:39:15 -07001266 type_spec_flags_ = o.type_spec_flags_;
1267
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001268 if (asset_manager_ == o.asset_manager_) {
1269 // The theme comes from the same asset manager so all theme data can be copied exactly
1270 for (size_t p = 0; p < packages_.size(); p++) {
1271 const Package *package = o.packages_[p].get();
1272 if (package == nullptr) {
1273 // The other theme doesn't have this package, clear ours.
1274 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001275 continue;
1276 }
1277
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001278 if (packages_[p] == nullptr) {
1279 // The other theme has this package, but we don't. Make one.
1280 packages_[p].reset(new Package());
1281 }
1282
1283 for (size_t t = 0; t < package->types.size(); t++) {
1284 const ThemeType *type = package->types[t].get();
1285 if (type == nullptr) {
1286 // The other theme doesn't have this type, clear ours.
1287 packages_[p]->types[t].reset();
1288 continue;
1289 }
1290
1291 // Create a new type and update it to theirs.
1292 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1293 void *copied_data = malloc(type_alloc_size);
1294 memcpy(copied_data, type, type_alloc_size);
1295 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1296 }
1297 }
1298 } else {
1299 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1300 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1301 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1302
1303 // Determine which ApkAssets are loaded in both theme AssetManagers
1304 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1305 for (size_t i = 0; i < src_assets.size(); i++) {
1306 const ApkAssets* src_asset = src_assets[i];
1307
1308 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1309 for (size_t j = 0; j < dest_assets.size(); j++) {
1310 const ApkAssets* dest_asset = dest_assets[j];
1311
1312 // Map the runtime package of the source apk asset to the destination apk asset
1313 if (src_asset->GetPath() == dest_asset->GetPath()) {
1314 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1315 src_asset->GetLoadedArsc()->GetPackages();
1316 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1317 dest_asset->GetLoadedArsc()->GetPackages();
1318
1319 SourceToDestinationRuntimePackageMap package_map;
1320
1321 // The source and destination package should have the same number of packages loaded in
1322 // the same order.
1323 const size_t N = src_packages.size();
1324 CHECK(N == dest_packages.size())
1325 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1326 for (size_t p = 0; p < N; p++) {
1327 auto& src_package = src_packages[p];
1328 auto& dest_package = dest_packages[p];
1329 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1330 << " Package " << src_package->GetPackageName() << " differs in load order.";
1331
1332 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1333 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1334 package_map[src_package_id] = dest_package_id;
1335 }
1336
1337 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1338 src_asset_cookie_id_map.insert(
1339 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1340 break;
1341 }
1342 }
1343 }
1344
1345 // Reset the data in the destination theme
1346 for (size_t p = 0; p < packages_.size(); p++) {
1347 if (packages_[p] != nullptr) {
1348 packages_[p].reset();
1349 }
1350 }
1351
1352 for (size_t p = 0; p < packages_.size(); p++) {
1353 const Package *package = o.packages_[p].get();
1354 if (package == nullptr) {
1355 continue;
1356 }
1357
1358 for (size_t t = 0; t < package->types.size(); t++) {
1359 const ThemeType *type = package->types[t].get();
1360 if (type == nullptr) {
1361 continue;
1362 }
1363
1364 for (size_t e = 0; e < type->entry_count; e++) {
1365 const ThemeEntry &entry = type->entries[e];
1366 if (entry.value.dataType == Res_value::TYPE_NULL &&
1367 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1368 continue;
1369 }
1370
Ryan Mitchellb85d9b22018-11-19 12:11:38 -08001371 // If the attribute value represents an attribute or reference, the package id of the
1372 // value needs to be rewritten to the package id of the value in the destination
1373 uint32_t attribue_data = entry.value.data;
1374 if ((entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1375 || entry.value.dataType == Res_value::TYPE_REFERENCE
1376 || entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1377 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE)
1378 && attribue_data != 0x0) {
1379
1380 // Determine the package id of the reference in the destination AssetManager
1381 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1382 if (value_package_map == src_asset_cookie_id_map.end()) {
1383 continue;
1384 }
1385
1386 auto value_dest_package = value_package_map->second.find(
1387 get_package_id(entry.value.data));
1388 if (value_dest_package == value_package_map->second.end()) {
1389 continue;
1390 }
1391
1392 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1393 }
1394
1395 // The package id of the attribute needs to be rewritten to the package id of the
1396 // attribute in the destination
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001397 int attribute_dest_package_id = p;
1398 if (attribute_dest_package_id != 0x01) {
1399 // Find the cookie of the attribute resource id
1400 FindEntryResult attribute_entry_result;
1401 ApkAssetsCookie attribute_cookie =
Ryan Mitchella55dc2e2019-01-24 10:58:23 -08001402 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ ,
1403 true /* stop_at_first_match */,
1404 true /* ignore_configuration */,
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001405 &attribute_entry_result);
1406
1407 // Determine the package id of the attribute in the destination AssetManager
1408 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1409 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1410 continue;
1411 }
1412 auto attribute_dest_package = attribute_package_map->second.find(
1413 attribute_dest_package_id);
1414 if (attribute_dest_package == attribute_package_map->second.end()) {
1415 continue;
1416 }
1417 attribute_dest_package_id = attribute_dest_package->second;
1418 }
1419
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001420 // Lazily instantiate the destination package
1421 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1422 if (dest_package == nullptr) {
1423 dest_package.reset(new Package());
1424 }
1425
1426 // Lazily instantiate and resize the destination type
1427 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1428 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1429 const size_t type_alloc_size = sizeof(ThemeType)
1430 + (type->entry_count * sizeof(ThemeEntry));
1431 void* dest_data = malloc(type_alloc_size);
1432 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1433
1434 // Copy the existing destination type values if the type is resized
1435 if (dest_type != nullptr) {
1436 memcpy(dest_data, type, sizeof(ThemeType)
1437 + (dest_type->entry_count * sizeof(ThemeEntry)));
1438 }
1439
1440 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1441 dest_type->entry_count = type->entry_count;
1442 }
1443
1444 // Find the cookie of the value in the destination
1445 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1446 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1447 continue;
1448 }
1449
1450 dest_type->entries[e].cookie = value_dest_cookie->second;
1451 dest_type->entries[e].value.dataType = entry.value.dataType;
1452 dest_type->entries[e].value.data = attribue_data;
1453 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1454 }
1455 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001456 }
1457 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001458}
1459
1460void Theme::Dump() const {
1461 base::ScopedLogSeverity _log(base::INFO);
1462 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1463
1464 for (int p = 0; p < packages_.size(); p++) {
1465 auto& package = packages_[p];
1466 if (package == nullptr) {
1467 continue;
1468 }
1469
1470 for (int t = 0; t < package->types.size(); t++) {
1471 auto& type = package->types[t];
1472 if (type == nullptr) {
1473 continue;
1474 }
1475
1476 for (int e = 0; e < type->entry_count; e++) {
1477 auto& entry = type->entries[e];
1478 if (entry.value.dataType == Res_value::TYPE_NULL &&
1479 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1480 continue;
1481 }
1482
1483 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1484 make_resid(p, t, e), entry.value.data,
1485 entry.value.dataType, entry.cookie);
1486 }
1487 }
1488 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001489}
1490
1491} // namespace android