blob: 9e6948878b1dedf5445697c66fc6b9b4dd760b46 [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>
Adam Lesinski0c405242017-01-13 20:47:26 -080023#include <set>
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -070024#include <map>
Adam Lesinski0c405242017-01-13 20:47:26 -080025
Adam Lesinski7ad11102016-10-28 16:39:15 -070026#include "android-base/logging.h"
27#include "android-base/stringprintf.h"
28#include "utils/ByteOrder.h"
29#include "utils/Trace.h"
30
31#ifdef _WIN32
32#ifdef ERROR
33#undef ERROR
34#endif
35#endif
36
Adam Lesinski929d6512017-01-16 19:11:19 -080037#include "androidfw/ResourceUtils.h"
38
Adam Lesinski7ad11102016-10-28 16:39:15 -070039namespace android {
40
Adam Lesinskibebfcc42018-02-12 14:27:46 -080041struct FindEntryResult {
42 // A pointer to the resource table entry for this resource.
43 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
44 // a ResTable_map_entry and processed as a bag/map.
45 const ResTable_entry* entry;
46
47 // The configuration for which the resulting entry was defined. This is already swapped to host
48 // endianness.
49 ResTable_config config;
50
51 // The bitmask of configuration axis with which the resource value varies.
52 uint32_t type_flags;
53
54 // The dynamic package ID map for the package from which this resource came from.
55 const DynamicRefTable* dynamic_ref_table;
56
57 // The string pool reference to the type's name. This uses a different string pool than
58 // the global string pool, but this is hidden from the caller.
59 StringPoolRef type_string_ref;
60
61 // The string pool reference to the entry's name. This uses a different string pool than
62 // the global string pool, but this is hidden from the caller.
63 StringPoolRef entry_string_ref;
64};
65
Adam Lesinski970bd8d2017-09-25 13:21:55 -070066AssetManager2::AssetManager2() {
67 memset(&configuration_, 0, sizeof(configuration_));
68}
Adam Lesinski7ad11102016-10-28 16:39:15 -070069
70bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020071 bool invalidate_caches, bool filter_incompatible_configs) {
Adam Lesinski7ad11102016-10-28 16:39:15 -070072 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050073 BuildDynamicRefTable();
Mårten Kongstad668ec5b2018-06-11 14:11:33 +020074 RebuildFilterList(filter_incompatible_configs);
Adam Lesinski7ad11102016-10-28 16:39:15 -070075 if (invalidate_caches) {
76 InvalidateCaches(static_cast<uint32_t>(-1));
77 }
78 return true;
79}
80
Adam Lesinskida431a22016-12-29 16:08:16 -050081void AssetManager2::BuildDynamicRefTable() {
82 package_groups_.clear();
83 package_ids_.fill(0xff);
84
85 // 0x01 is reserved for the android package.
86 int next_package_id = 0x02;
87 const size_t apk_assets_count = apk_assets_.size();
88 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070089 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
90
91 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050092 // Get the package ID or assign one if a shared library.
93 int package_id;
94 if (package->IsDynamic()) {
95 package_id = next_package_id++;
96 } else {
97 package_id = package->GetPackageId();
98 }
99
100 // Add the mapping for package ID to index if not present.
101 uint8_t idx = package_ids_[package_id];
102 if (idx == 0xff) {
103 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
104 package_groups_.push_back({});
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800105 DynamicRefTable& ref_table = package_groups_.back().dynamic_ref_table;
106 ref_table.mAssignedPackageId = package_id;
107 ref_table.mAppAsLib = package->IsDynamic() && package->GetPackageId() == 0x7f;
Adam Lesinskida431a22016-12-29 16:08:16 -0500108 }
109 PackageGroup* package_group = &package_groups_[idx];
110
111 // Add the package and to the set of packages with the same ID.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800112 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500113 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
114
115 // Add the package name -> build time ID mappings.
116 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
117 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
118 package_group->dynamic_ref_table.mEntries.replaceValueFor(
119 package_name, static_cast<uint8_t>(entry.package_id));
120 }
121 }
122 }
123
124 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
125 const auto package_groups_end = package_groups_.end();
126 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800127 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500128 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
129 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
130 iter->dynamic_ref_table.mAssignedPackageId);
131 }
132 }
133}
134
135void AssetManager2::DumpToLog() const {
136 base::ScopedLogSeverity _log(base::INFO);
137
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800138 LOG(INFO) << base::StringPrintf("AssetManager2(this=%p)", this);
139
Adam Lesinskida431a22016-12-29 16:08:16 -0500140 std::string list;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800141 for (const auto& apk_assets : apk_assets_) {
142 base::StringAppendF(&list, "%s,", apk_assets->GetPath().c_str());
143 }
144 LOG(INFO) << "ApkAssets: " << list;
145
146 list = "";
Adam Lesinskida431a22016-12-29 16:08:16 -0500147 for (size_t i = 0; i < package_ids_.size(); i++) {
148 if (package_ids_[i] != 0xff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800149 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500150 }
151 }
152 LOG(INFO) << "Package ID map: " << list;
153
Adam Lesinski0dd36992018-01-25 15:38:38 -0800154 for (const auto& package_group: package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800155 list = "";
156 for (const auto& package : package_group.packages_) {
157 const LoadedPackage* loaded_package = package.loaded_package_;
158 base::StringAppendF(&list, "%s(%02x%s), ", loaded_package->GetPackageName().c_str(),
159 loaded_package->GetPackageId(),
160 (loaded_package->IsDynamic() ? " dynamic" : ""));
161 }
162 LOG(INFO) << base::StringPrintf("PG (%02x): ",
163 package_group.dynamic_ref_table.mAssignedPackageId)
164 << list;
Ryan Mitchell5db396d2018-11-05 15:56:15 -0800165
166 for (size_t i = 0; i < 256; i++) {
167 if (package_group.dynamic_ref_table.mLookupTable[i] != 0) {
168 LOG(INFO) << base::StringPrintf(" e[0x%02x] -> 0x%02x", (uint8_t) i,
169 package_group.dynamic_ref_table.mLookupTable[i]);
170 }
171 }
Adam Lesinskida431a22016-12-29 16:08:16 -0500172 }
173}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700174
175const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
176 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
177 return nullptr;
178 }
179 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
180}
181
Adam Lesinskida431a22016-12-29 16:08:16 -0500182const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
183 if (package_id >= package_ids_.size()) {
184 return nullptr;
185 }
186
187 const size_t idx = package_ids_[package_id];
188 if (idx == 0xff) {
189 return nullptr;
190 }
191 return &package_groups_[idx].dynamic_ref_table;
192}
193
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800194const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
195 for (const PackageGroup& package_group : package_groups_) {
196 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
197 if (package_cookie == cookie) {
198 return &package_group.dynamic_ref_table;
199 }
200 }
201 }
202 return nullptr;
203}
204
Adam Lesinski7ad11102016-10-28 16:39:15 -0700205void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
206 const int diff = configuration_.diff(configuration);
207 configuration_ = configuration;
208
209 if (diff) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800210 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700211 InvalidateCaches(static_cast<uint32_t>(diff));
212 }
213}
214
Adam Lesinski0c405242017-01-13 20:47:26 -0800215std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800216 bool exclude_mipmap) const {
217 ATRACE_NAME("AssetManager::GetResourceConfigurations");
Adam Lesinski0c405242017-01-13 20:47:26 -0800218 std::set<ResTable_config> configurations;
219 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800220 for (const ConfiguredPackage& package : package_group.packages_) {
221 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800222 continue;
223 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800224 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800225 }
226 }
227 return configurations;
228}
229
230std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800231 bool merge_equivalent_languages) const {
232 ATRACE_NAME("AssetManager::GetResourceLocales");
Adam Lesinski0c405242017-01-13 20:47:26 -0800233 std::set<std::string> locales;
234 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800235 for (const ConfiguredPackage& package : package_group.packages_) {
236 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800237 continue;
238 }
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800239 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800240 }
241 }
242 return locales;
243}
244
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800245std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
246 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700247 const std::string new_path = "assets/" + filename;
248 return OpenNonAsset(new_path, mode);
249}
250
251std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800252 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700253 const std::string new_path = "assets/" + filename;
254 return OpenNonAsset(new_path, cookie, mode);
255}
256
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800257std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
258 ATRACE_NAME("AssetManager::OpenDir");
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800259
260 std::string full_path = "assets/" + dirname;
261 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
262 util::make_unique<SortedVector<AssetDir::FileInfo>>();
263
264 // Start from the back.
265 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
266 const ApkAssets* apk_assets = *iter;
267
268 auto func = [&](const StringPiece& name, FileType type) {
269 AssetDir::FileInfo info;
270 info.setFileName(String8(name.data(), name.size()));
271 info.setFileType(type);
272 info.setSourceName(String8(apk_assets->GetPath().c_str()));
273 files->add(info);
274 };
275
276 if (!apk_assets->ForEachFile(full_path, func)) {
277 return {};
278 }
279 }
280
281 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
282 asset_dir->setFileList(files.release());
283 return asset_dir;
284}
285
Adam Lesinski7ad11102016-10-28 16:39:15 -0700286// Search in reverse because that's how we used to do it and we need to preserve behaviour.
287// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
288// is inconsistent for split APKs.
289std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
290 Asset::AccessMode mode,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800291 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700292 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
293 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
294 if (asset) {
295 if (out_cookie != nullptr) {
296 *out_cookie = i;
297 }
298 return asset;
299 }
300 }
301
302 if (out_cookie != nullptr) {
303 *out_cookie = kInvalidCookie;
304 }
305 return {};
306}
307
308std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800309 ApkAssetsCookie cookie,
310 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700311 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
312 return {};
313 }
314 return apk_assets_[cookie]->Open(filename, mode);
315}
316
317ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800318 bool /*stop_at_first_match*/,
319 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700320 // Might use this if density_override != 0.
321 ResTable_config density_override_config;
322
323 // Select our configuration or generate a density override configuration.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800324 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700325 if (density_override != 0 && density_override != configuration_.density) {
326 density_override_config = configuration_;
327 density_override_config.density = density_override;
328 desired_config = &density_override_config;
329 }
330
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800331 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500332 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
333 return kInvalidCookie;
334 }
335
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800336 const uint32_t package_id = get_package_id(resid);
337 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800338 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800339
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800340 const uint8_t package_idx = package_ids_[package_id];
341 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500342 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
343 return kInvalidCookie;
344 }
345
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800346 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinskib8b3a262018-02-09 11:01:45 -0800347 const size_t package_count = package_group.packages_.size();
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800348
349 ApkAssetsCookie best_cookie = kInvalidCookie;
350 const LoadedPackage* best_package = nullptr;
351 const ResTable_type* best_type = nullptr;
352 const ResTable_config* best_config = nullptr;
353 ResTable_config best_config_copy;
354 uint32_t best_offset = 0u;
355 uint32_t type_flags = 0u;
356
357 // If desired_config is the same as the set configuration, then we can use our filtered list
358 // and we don't need to match the configurations, since they already matched.
359 const bool use_fast_path = desired_config == &configuration_;
360
361 for (size_t pi = 0; pi < package_count; pi++) {
362 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
363 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
364 ApkAssetsCookie cookie = package_group.cookies_[pi];
365
366 // If the type IDs are offset in this package, we need to take that into account when searching
367 // for a type.
368 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
369 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700370 continue;
371 }
372
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800373 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700374
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800375 // If there is an IDMAP supplied with this package, translate the entry ID.
376 if (type_spec->idmap_entries != nullptr) {
377 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
378 // There is no mapping, so the resource is not meant to be in this overlay package.
379 continue;
380 }
381 }
382
383 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
384
385 // If the package is an overlay, then even configurations that are the same MUST be chosen.
386 const bool package_is_overlay = loaded_package->IsOverlay();
387
388 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
389 if (use_fast_path) {
390 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
391 const size_t type_count = candidate_configs.size();
392 for (uint32_t i = 0; i < type_count; i++) {
393 const ResTable_config& this_config = candidate_configs[i];
394
395 // We can skip calling ResTable_config::match() because we know that all candidate
396 // configurations that do NOT match have been filtered-out.
397 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
398 (package_is_overlay && this_config.compare(*best_config) == 0)) {
399 // The configuration matches and is better than the previous selection.
400 // Find the entry value if it exists for this configuration.
401 const ResTable_type* type_chunk = filtered_group.types[i];
402 const uint32_t offset = LoadedPackage::GetEntryOffset(type_chunk, local_entry_idx);
403 if (offset == ResTable_type::NO_ENTRY) {
404 continue;
405 }
406
407 best_cookie = cookie;
408 best_package = loaded_package;
409 best_type = type_chunk;
410 best_config = &this_config;
411 best_offset = offset;
412 }
413 }
414 } else {
415 // This is the slower path, which doesn't use the filtered list of configurations.
416 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
417 // and fill in any new fields that did not exist when the APK was compiled.
418 // Furthermore when selecting configurations we can't just record the pointer to the
419 // ResTable_config, we must copy it.
420 const auto iter_end = type_spec->types + type_spec->type_count;
421 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
422 ResTable_config this_config;
423 this_config.copyFromDtoH((*iter)->config);
424
425 if (this_config.match(*desired_config)) {
426 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
427 (package_is_overlay && this_config.compare(*best_config) == 0)) {
428 // The configuration matches and is better than the previous selection.
429 // Find the entry value if it exists for this configuration.
430 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
431 if (offset == ResTable_type::NO_ENTRY) {
432 continue;
433 }
434
435 best_cookie = cookie;
436 best_package = loaded_package;
437 best_type = *iter;
438 best_config_copy = this_config;
439 best_config = &best_config_copy;
440 best_offset = offset;
441 }
442 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700443 }
444 }
445 }
446
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800447 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700448 return kInvalidCookie;
449 }
450
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800451 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
452 if (UNLIKELY(best_entry == nullptr)) {
453 return kInvalidCookie;
454 }
455
456 out_entry->entry = best_entry;
457 out_entry->config = *best_config;
458 out_entry->type_flags = type_flags;
459 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
460 out_entry->entry_string_ref =
461 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500462 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinskida431a22016-12-29 16:08:16 -0500463 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700464}
465
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800466bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700467 FindEntryResult entry;
468 ApkAssetsCookie cookie =
469 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700470 if (cookie == kInvalidCookie) {
471 return false;
472 }
473
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800474 const LoadedPackage* package =
475 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Adam Lesinskida431a22016-12-29 16:08:16 -0500476 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700477 return false;
478 }
479
Adam Lesinskida431a22016-12-29 16:08:16 -0500480 out_name->package = package->GetPackageName().data();
481 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700482
483 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
484 out_name->type16 = nullptr;
485 if (out_name->type == nullptr) {
486 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
487 if (out_name->type16 == nullptr) {
488 return false;
489 }
490 }
491
492 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
493 out_name->entry16 = nullptr;
494 if (out_name->entry == nullptr) {
495 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
496 if (out_name->entry16 == nullptr) {
497 return false;
498 }
499 }
500 return true;
501}
502
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800503bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700504 FindEntryResult entry;
505 ApkAssetsCookie cookie =
506 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
507 if (cookie != kInvalidCookie) {
508 *out_flags = entry.type_flags;
509 return cookie;
510 }
511 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700512}
513
514ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
515 uint16_t density_override, Res_value* out_value,
516 ResTable_config* out_selected_config,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800517 uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700518 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700519 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700520 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700521 if (cookie == kInvalidCookie) {
522 return kInvalidCookie;
523 }
524
Adam Lesinski498f6052017-11-29 13:24:29 -0800525 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700526 if (!may_be_bag) {
527 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800528 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700529 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800530
531 // Create a reference since we can't represent this complex type as a Res_value.
532 out_value->dataType = Res_value::TYPE_REFERENCE;
533 out_value->data = resid;
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800534 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700535 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800536 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700537 }
538
539 const Res_value* device_value = reinterpret_cast<const Res_value*>(
540 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
541 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500542
543 // Convert the package ID to the runtime assigned package ID.
544 entry.dynamic_ref_table->lookupResourceValue(out_value);
545
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800546 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700547 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700548 return cookie;
549}
550
Adam Lesinski0c405242017-01-13 20:47:26 -0800551ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
552 ResTable_config* in_out_selected_config,
553 uint32_t* in_out_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800554 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800555 constexpr const int kMaxIterations = 20;
556
Adam Lesinski0c405242017-01-13 20:47:26 -0800557 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
558 in_out_value->data != 0u && iteration < kMaxIterations;
559 iteration++) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800560 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800561 uint32_t new_flags = 0u;
562 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
563 in_out_value, in_out_selected_config, &new_flags);
564 if (cookie == kInvalidCookie) {
565 return kInvalidCookie;
566 }
567 if (in_out_flags != nullptr) {
568 *in_out_flags |= new_flags;
569 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800570 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800571 // This reference can't be resolved, so exit now and let the caller deal with it.
572 return cookie;
573 }
574 }
575 return cookie;
576}
577
Adam Lesinski7ad11102016-10-28 16:39:15 -0700578const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
y57cd1952018-04-12 14:26:23 -0700579 auto found_resids = std::vector<uint32_t>();
580 return GetBag(resid, found_resids);
581}
582
583const ResolvedBag* AssetManager2::GetBag(uint32_t resid, std::vector<uint32_t>& child_resids) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800584 ATRACE_NAME("AssetManager::GetBag");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700585
586 auto cached_iter = cached_bags_.find(resid);
587 if (cached_iter != cached_bags_.end()) {
588 return cached_iter->second.get();
589 }
590
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700591 FindEntryResult entry;
592 ApkAssetsCookie cookie =
593 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700594 if (cookie == kInvalidCookie) {
595 return nullptr;
596 }
597
598 // Check that the size of the entry header is at least as big as
599 // the desired ResTable_map_entry. Also verify that the entry
600 // was intended to be a map.
601 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
602 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
603 // Not a bag, nothing to do.
604 return nullptr;
605 }
606
607 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
608 const ResTable_map* map_entry =
609 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
610 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
611
y57cd1952018-04-12 14:26:23 -0700612 // Keep track of ids that have already been seen to prevent infinite loops caused by circular
613 // dependencies between bags
614 child_resids.push_back(resid);
615
Adam Lesinskida431a22016-12-29 16:08:16 -0500616 uint32_t parent_resid = dtohl(map->parent.ident);
y57cd1952018-04-12 14:26:23 -0700617 if (parent_resid == 0 || std::find(child_resids.begin(), child_resids.end(), parent_resid)
618 != child_resids.end()) {
619 // There is no parent or that a circular dependency exist, meaning there is nothing to
620 // inherit and we can do a simple copy of the entries in the map.
Adam Lesinski7ad11102016-10-28 16:39:15 -0700621 const size_t entry_count = map_entry_end - map_entry;
622 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
623 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
624 ResolvedBag::Entry* new_entry = new_bag->entries;
625 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500626 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800627 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500628 // Attributes, arrays, etc don't have a resource id as the name. They specify
629 // other data, which would be wrong to change via a lookup.
630 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800631 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
632 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500633 return nullptr;
634 }
635 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700636 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500637 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700638 new_entry->key_pool = nullptr;
639 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700640 new_entry->value.copyFrom_dtoh(map_entry->value);
641 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
642 if (err != NO_ERROR) {
643 LOG(ERROR) << base::StringPrintf(
644 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
645 new_entry->value.data, new_key);
646 return nullptr;
647 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700648 ++new_entry;
649 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700650 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700651 new_bag->entry_count = static_cast<uint32_t>(entry_count);
652 ResolvedBag* result = new_bag.get();
653 cached_bags_[resid] = std::move(new_bag);
654 return result;
655 }
656
Adam Lesinskida431a22016-12-29 16:08:16 -0500657 // In case the parent is a dynamic reference, resolve it.
658 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
659
Adam Lesinski7ad11102016-10-28 16:39:15 -0700660 // Get the parent and do a merge of the keys.
y57cd1952018-04-12 14:26:23 -0700661 const ResolvedBag* parent_bag = GetBag(parent_resid, child_resids);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700662 if (parent_bag == nullptr) {
663 // Failed to get the parent that should exist.
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800664 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
665 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700666 return nullptr;
667 }
668
Adam Lesinski7ad11102016-10-28 16:39:15 -0700669 // Create the max possible entries we can make. Once we construct the bag,
670 // we will realloc to fit to size.
671 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700672 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
673 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700674 ResolvedBag::Entry* new_entry = new_bag->entries;
675
676 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
677 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
678
679 // The keys are expected to be in sorted order. Merge the two bags.
680 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500681 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800682 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500683 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800684 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
685 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500686 return nullptr;
687 }
688 }
689
Adam Lesinski7ad11102016-10-28 16:39:15 -0700690 if (child_key <= parent_entry->key) {
691 // Use the child key if it comes before the parent
692 // or is equal to the parent (overrides).
693 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700694 new_entry->key = child_key;
695 new_entry->key_pool = nullptr;
696 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700697 new_entry->value.copyFrom_dtoh(map_entry->value);
698 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
699 if (err != NO_ERROR) {
700 LOG(ERROR) << base::StringPrintf(
701 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
702 new_entry->value.data, child_key);
703 return nullptr;
704 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700705 ++map_entry;
706 } else {
707 // Take the parent entry as-is.
708 memcpy(new_entry, parent_entry, sizeof(*new_entry));
709 }
710
711 if (child_key >= parent_entry->key) {
712 // Move to the next parent entry if we used it or it was overridden.
713 ++parent_entry;
714 }
715 // Increment to the next entry to fill.
716 ++new_entry;
717 }
718
719 // Finish the child entries if they exist.
720 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500721 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800722 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500723 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800724 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
725 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500726 return nullptr;
727 }
728 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700729 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500730 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700731 new_entry->key_pool = nullptr;
732 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700733 new_entry->value.copyFrom_dtoh(map_entry->value);
734 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
735 if (err != NO_ERROR) {
736 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
737 new_entry->value.dataType, new_entry->value.data, new_key);
738 return nullptr;
739 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700740 ++map_entry;
741 ++new_entry;
742 }
743
744 // Finish the parent entries if they exist.
745 if (parent_entry != parent_entry_end) {
746 // Take the rest of the parent entries as-is.
747 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
748 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
749 new_entry += num_entries_to_copy;
750 }
751
752 // Resize the resulting array to fit.
753 const size_t actual_count = new_entry - new_bag->entries;
754 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700755 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
756 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700757 }
758
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700759 // Combine flags from the parent and our own bag.
760 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700761 new_bag->entry_count = static_cast<uint32_t>(actual_count);
762 ResolvedBag* result = new_bag.get();
763 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700764 return result;
765}
766
Adam Lesinski929d6512017-01-16 19:11:19 -0800767static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
768 ssize_t len =
769 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
770 if (len < 0) {
771 return false;
772 }
773 out->resize(static_cast<size_t>(len));
774 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
775 static_cast<size_t>(len + 1));
776 return true;
777}
778
Adam Lesinski0c405242017-01-13 20:47:26 -0800779uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
780 const std::string& fallback_type,
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800781 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800782 StringPiece package_name, type, entry;
783 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
784 return 0u;
785 }
786
787 if (entry.empty()) {
788 return 0u;
789 }
790
791 if (package_name.empty()) {
792 package_name = fallback_package;
793 }
794
795 if (type.empty()) {
796 type = fallback_type;
797 }
798
799 std::u16string type16;
800 if (!Utf8ToUtf16(type, &type16)) {
801 return 0u;
802 }
803
804 std::u16string entry16;
805 if (!Utf8ToUtf16(entry, &entry16)) {
806 return 0u;
807 }
808
809 const StringPiece16 kAttr16 = u"attr";
810 const static std::u16string kAttrPrivate16 = u"^attr-private";
811
812 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800813 for (const ConfiguredPackage& package_impl : package_group.packages_) {
814 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800815 if (package_name != package->GetPackageName()) {
816 // All packages in the same group are expected to have the same package name.
817 break;
818 }
819
820 uint32_t resid = package->FindEntryByName(type16, entry16);
821 if (resid == 0u && kAttr16 == type16) {
822 // Private attributes in libraries (such as the framework) are sometimes encoded
823 // under the type '^attr-private' in order to leave the ID space of public 'attr'
824 // free for future additions. Check '^attr-private' for the same name.
825 resid = package->FindEntryByName(kAttrPrivate16, entry16);
826 }
827
828 if (resid != 0u) {
829 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
830 }
831 }
832 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800833 return 0u;
834}
835
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200836void AssetManager2::RebuildFilterList(bool filter_incompatible_configs) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800837 for (PackageGroup& group : package_groups_) {
838 for (ConfiguredPackage& impl : group.packages_) {
839 // Destroy it.
840 impl.filtered_configs_.~ByteBucketArray();
841
842 // Re-create it.
843 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
844
845 // Create the filters here.
846 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
847 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
848 const auto iter_end = spec->types + spec->type_count;
849 for (auto iter = spec->types; iter != iter_end; ++iter) {
850 ResTable_config this_config;
851 this_config.copyFromDtoH((*iter)->config);
Mårten Kongstad668ec5b2018-06-11 14:11:33 +0200852 if (!filter_incompatible_configs || this_config.match(configuration_)) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800853 group.configurations.push_back(this_config);
854 group.types.push_back(*iter);
855 }
856 }
857 });
858 }
859 }
860}
861
Adam Lesinski7ad11102016-10-28 16:39:15 -0700862void AssetManager2::InvalidateCaches(uint32_t diff) {
863 if (diff == 0xffffffffu) {
864 // Everything must go.
865 cached_bags_.clear();
866 return;
867 }
868
869 // Be more conservative with what gets purged. Only if the bag has other possible
870 // variations with respect to what changed (diff) should we remove it.
871 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
872 if (diff & iter->second->type_spec_flags) {
873 iter = cached_bags_.erase(iter);
874 } else {
875 ++iter;
876 }
877 }
878}
879
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -0700880uint8_t AssetManager2::GetAssignedPackageId(const LoadedPackage* package) {
881 for (auto& package_group : package_groups_) {
882 for (auto& package2 : package_group.packages_) {
883 if (package2.loaded_package_ == package) {
884 return package_group.dynamic_ref_table.mAssignedPackageId;
885 }
886 }
887 }
888 return 0;
889}
890
Adam Lesinski30080e22017-10-16 16:18:09 -0700891std::unique_ptr<Theme> AssetManager2::NewTheme() {
892 return std::unique_ptr<Theme>(new Theme(this));
893}
894
895Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
896}
897
898Theme::~Theme() = default;
899
900namespace {
901
902struct ThemeEntry {
903 ApkAssetsCookie cookie;
904 uint32_t type_spec_flags;
905 Res_value value;
906};
907
908struct ThemeType {
909 int entry_count;
910 ThemeEntry entries[0];
911};
912
913constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
914
915} // namespace
916
917struct Theme::Package {
918 // Each element of Type will be a dynamically sized object
919 // allocated to have the entries stored contiguously with the Type.
920 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
921};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700922
923bool Theme::ApplyStyle(uint32_t resid, bool force) {
Adam Lesinskibebfcc42018-02-12 14:27:46 -0800924 ATRACE_NAME("Theme::ApplyStyle");
Adam Lesinski7ad11102016-10-28 16:39:15 -0700925
926 const ResolvedBag* bag = asset_manager_->GetBag(resid);
927 if (bag == nullptr) {
928 return false;
929 }
930
931 // Merge the flags from this style.
932 type_spec_flags_ |= bag->type_spec_flags;
933
Adam Lesinski30080e22017-10-16 16:18:09 -0700934 int last_type_idx = -1;
935 int last_package_idx = -1;
936 Package* last_package = nullptr;
937 ThemeType* last_type = nullptr;
938
939 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
940 // need to perform one resize per type.
941 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
942 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
943 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700944 const uint32_t attr_resid = bag_iter->key;
945
Adam Lesinski30080e22017-10-16 16:18:09 -0700946 // If the resource ID passed in is not a style, the key can be some other identifier that is not
947 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800948 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700949 return false;
950 }
951
Adam Lesinski30080e22017-10-16 16:18:09 -0700952 // We don't use the 0-based index for the type so that we can avoid doing ID validation
953 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
954 // the construction of this type is guarded with a resource ID check, it will never be
955 // populated, and querying type ID 0 will always fail.
956 const int package_idx = get_package_id(attr_resid);
957 const int type_idx = get_type_id(attr_resid);
958 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700959
Adam Lesinski30080e22017-10-16 16:18:09 -0700960 if (last_package_idx != package_idx) {
961 std::unique_ptr<Package>& package = packages_[package_idx];
962 if (package == nullptr) {
963 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700964 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700965 last_package_idx = package_idx;
966 last_package = package.get();
967 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700968 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700969
970 if (last_type_idx != type_idx) {
971 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
972 if (type == nullptr) {
973 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
974 // a sorted list of attributes, this shouldn't be resized again during this method call.
975 type.reset(reinterpret_cast<ThemeType*>(
976 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
977 type->entry_count = entry_idx + 1;
978 } else if (entry_idx >= type->entry_count) {
979 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
980 // a sorted list of attributes, this shouldn't be resized again during this method call.
981 const int new_count = entry_idx + 1;
982 type.reset(reinterpret_cast<ThemeType*>(
983 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
984
985 // Clear out the newly allocated space (which isn't zeroed).
986 memset(type->entries + type->entry_count, 0,
987 (new_count - type->entry_count) * sizeof(ThemeEntry));
988 type->entry_count = new_count;
989 }
990 last_type_idx = type_idx;
991 last_type = type.get();
992 }
993
994 ThemeEntry& entry = last_type->entries[entry_idx];
995 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
996 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700997 entry.cookie = bag_iter->cookie;
998 entry.type_spec_flags |= bag->type_spec_flags;
999 entry.value = bag_iter->value;
1000 }
1001 }
1002 return true;
1003}
1004
1005ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
1006 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -07001007 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001008
1009 uint32_t type_spec_flags = 0u;
1010
Adam Lesinski30080e22017-10-16 16:18:09 -07001011 do {
1012 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001013 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -07001014 if (package != nullptr) {
1015 // The themes are constructed with a 1-based type ID, so no need to decrement here.
1016 const int type_idx = get_type_id(resid);
1017 const ThemeType* type = package->types[type_idx].get();
1018 if (type != nullptr) {
1019 const int entry_idx = get_entry_id(resid);
1020 if (entry_idx < type->entry_count) {
1021 const ThemeEntry& entry = type->entries[entry_idx];
1022 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001023
Adam Lesinski30080e22017-10-16 16:18:09 -07001024 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
1025 if (cnt > 0) {
1026 cnt--;
1027 resid = entry.value.data;
1028 continue;
1029 }
1030 return kInvalidCookie;
1031 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001032
Adam Lesinski30080e22017-10-16 16:18:09 -07001033 // @null is different than @empty.
1034 if (entry.value.dataType == Res_value::TYPE_NULL &&
1035 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1036 return kInvalidCookie;
1037 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001038
Adam Lesinski30080e22017-10-16 16:18:09 -07001039 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001040 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001041 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001042 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001043 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001044 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001045 break;
1046 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001047 return kInvalidCookie;
1048}
1049
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001050ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1051 ResTable_config* in_out_selected_config,
1052 uint32_t* in_out_type_spec_flags,
Adam Lesinskibebfcc42018-02-12 14:27:46 -08001053 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001054 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1055 uint32_t new_flags;
1056 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1057 if (cookie == kInvalidCookie) {
1058 return kInvalidCookie;
1059 }
1060
1061 if (in_out_type_spec_flags != nullptr) {
1062 *in_out_type_spec_flags |= new_flags;
1063 }
1064 }
1065 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1066 in_out_type_spec_flags, out_last_ref);
1067}
1068
Adam Lesinski7ad11102016-10-28 16:39:15 -07001069void Theme::Clear() {
1070 type_spec_flags_ = 0u;
1071 for (std::unique_ptr<Package>& package : packages_) {
1072 package.reset();
1073 }
1074}
1075
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001076void Theme::SetTo(const Theme& o) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001077 if (this == &o) {
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001078 return;
Adam Lesinski7ad11102016-10-28 16:39:15 -07001079 }
1080
Adam Lesinski7ad11102016-10-28 16:39:15 -07001081 type_spec_flags_ = o.type_spec_flags_;
1082
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001083 if (asset_manager_ == o.asset_manager_) {
1084 // The theme comes from the same asset manager so all theme data can be copied exactly
1085 for (size_t p = 0; p < packages_.size(); p++) {
1086 const Package *package = o.packages_[p].get();
1087 if (package == nullptr) {
1088 // The other theme doesn't have this package, clear ours.
1089 packages_[p].reset();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001090 continue;
1091 }
1092
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001093 if (packages_[p] == nullptr) {
1094 // The other theme has this package, but we don't. Make one.
1095 packages_[p].reset(new Package());
1096 }
1097
1098 for (size_t t = 0; t < package->types.size(); t++) {
1099 const ThemeType *type = package->types[t].get();
1100 if (type == nullptr) {
1101 // The other theme doesn't have this type, clear ours.
1102 packages_[p]->types[t].reset();
1103 continue;
1104 }
1105
1106 // Create a new type and update it to theirs.
1107 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
1108 void *copied_data = malloc(type_alloc_size);
1109 memcpy(copied_data, type, type_alloc_size);
1110 packages_[p]->types[t].reset(reinterpret_cast<ThemeType *>(copied_data));
1111 }
1112 }
1113 } else {
1114 std::map<ApkAssetsCookie, ApkAssetsCookie> src_to_dest_asset_cookies;
1115 typedef std::map<int, int> SourceToDestinationRuntimePackageMap;
1116 std::map<ApkAssetsCookie, SourceToDestinationRuntimePackageMap> src_asset_cookie_id_map;
1117
1118 // Determine which ApkAssets are loaded in both theme AssetManagers
1119 std::vector<const ApkAssets*> src_assets = o.asset_manager_->GetApkAssets();
1120 for (size_t i = 0; i < src_assets.size(); i++) {
1121 const ApkAssets* src_asset = src_assets[i];
1122
1123 std::vector<const ApkAssets*> dest_assets = asset_manager_->GetApkAssets();
1124 for (size_t j = 0; j < dest_assets.size(); j++) {
1125 const ApkAssets* dest_asset = dest_assets[j];
1126
1127 // Map the runtime package of the source apk asset to the destination apk asset
1128 if (src_asset->GetPath() == dest_asset->GetPath()) {
1129 const std::vector<std::unique_ptr<const LoadedPackage>>& src_packages =
1130 src_asset->GetLoadedArsc()->GetPackages();
1131 const std::vector<std::unique_ptr<const LoadedPackage>>& dest_packages =
1132 dest_asset->GetLoadedArsc()->GetPackages();
1133
1134 SourceToDestinationRuntimePackageMap package_map;
1135
1136 // The source and destination package should have the same number of packages loaded in
1137 // the same order.
1138 const size_t N = src_packages.size();
1139 CHECK(N == dest_packages.size())
1140 << " LoadedArsc " << src_asset->GetPath() << " differs number of packages.";
1141 for (size_t p = 0; p < N; p++) {
1142 auto& src_package = src_packages[p];
1143 auto& dest_package = dest_packages[p];
1144 CHECK(src_package->GetPackageName() == dest_package->GetPackageName())
1145 << " Package " << src_package->GetPackageName() << " differs in load order.";
1146
1147 int src_package_id = o.asset_manager_->GetAssignedPackageId(src_package.get());
1148 int dest_package_id = asset_manager_->GetAssignedPackageId(dest_package.get());
1149 package_map[src_package_id] = dest_package_id;
1150 }
1151
1152 src_to_dest_asset_cookies.insert(std::pair<ApkAssetsCookie, ApkAssetsCookie>(i, j));
1153 src_asset_cookie_id_map.insert(
1154 std::pair<ApkAssetsCookie, SourceToDestinationRuntimePackageMap>(i, package_map));
1155 break;
1156 }
1157 }
1158 }
1159
1160 // Reset the data in the destination theme
1161 for (size_t p = 0; p < packages_.size(); p++) {
1162 if (packages_[p] != nullptr) {
1163 packages_[p].reset();
1164 }
1165 }
1166
1167 for (size_t p = 0; p < packages_.size(); p++) {
1168 const Package *package = o.packages_[p].get();
1169 if (package == nullptr) {
1170 continue;
1171 }
1172
1173 for (size_t t = 0; t < package->types.size(); t++) {
1174 const ThemeType *type = package->types[t].get();
1175 if (type == nullptr) {
1176 continue;
1177 }
1178
1179 for (size_t e = 0; e < type->entry_count; e++) {
1180 const ThemeEntry &entry = type->entries[e];
1181 if (entry.value.dataType == Res_value::TYPE_NULL &&
1182 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1183 continue;
1184 }
1185
1186 // The package id of the attribute needs to be rewritten to the package id of the value in
1187 // the destination
1188 int attribute_dest_package_id = p;
1189 if (attribute_dest_package_id != 0x01) {
1190 // Find the cookie of the attribute resource id
1191 FindEntryResult attribute_entry_result;
1192 ApkAssetsCookie attribute_cookie =
1193 o.asset_manager_->FindEntry(make_resid(p, t, e), 0 /* density_override */ , false,
1194 &attribute_entry_result);
1195
1196 // Determine the package id of the attribute in the destination AssetManager
1197 auto attribute_package_map = src_asset_cookie_id_map.find(attribute_cookie);
1198 if (attribute_package_map == src_asset_cookie_id_map.end()) {
1199 continue;
1200 }
1201 auto attribute_dest_package = attribute_package_map->second.find(
1202 attribute_dest_package_id);
1203 if (attribute_dest_package == attribute_package_map->second.end()) {
1204 continue;
1205 }
1206 attribute_dest_package_id = attribute_dest_package->second;
1207 }
1208
1209 // If the attribute value represents an attribute or reference, the package id of the
1210 // value needs to be rewritten to the package id of the value in the destination
1211 uint32_t attribue_data = entry.value.data;
1212 if (entry.value.dataType == Res_value::TYPE_DYNAMIC_ATTRIBUTE
1213 || entry.value.dataType == Res_value::TYPE_DYNAMIC_REFERENCE
1214 || entry.value.dataType == Res_value::TYPE_ATTRIBUTE
1215 || entry.value.dataType == Res_value::TYPE_REFERENCE) {
1216
1217 // Determine the package id of the reference in the destination AssetManager
1218 auto value_package_map = src_asset_cookie_id_map.find(entry.cookie);
1219 if (value_package_map == src_asset_cookie_id_map.end()) {
1220 continue;
1221 }
1222
1223 auto value_dest_package = value_package_map->second.find(
1224 get_package_id(entry.value.data));
1225 if (value_dest_package == value_package_map->second.end()) {
1226 continue;
1227 }
1228
1229 attribue_data = fix_package_id(entry.value.data, value_dest_package->second);
1230 }
1231
1232 // Lazily instantiate the destination package
1233 std::unique_ptr<Package>& dest_package = packages_[attribute_dest_package_id];
1234 if (dest_package == nullptr) {
1235 dest_package.reset(new Package());
1236 }
1237
1238 // Lazily instantiate and resize the destination type
1239 util::unique_cptr<ThemeType>& dest_type = dest_package->types[t];
1240 if (dest_type == nullptr || dest_type->entry_count < type->entry_count) {
1241 const size_t type_alloc_size = sizeof(ThemeType)
1242 + (type->entry_count * sizeof(ThemeEntry));
1243 void* dest_data = malloc(type_alloc_size);
1244 memset(dest_data, 0, type->entry_count * sizeof(ThemeEntry));
1245
1246 // Copy the existing destination type values if the type is resized
1247 if (dest_type != nullptr) {
1248 memcpy(dest_data, type, sizeof(ThemeType)
1249 + (dest_type->entry_count * sizeof(ThemeEntry)));
1250 }
1251
1252 dest_type.reset(reinterpret_cast<ThemeType *>(dest_data));
1253 dest_type->entry_count = type->entry_count;
1254 }
1255
1256 // Find the cookie of the value in the destination
1257 auto value_dest_cookie = src_to_dest_asset_cookies.find(entry.cookie);
1258 if (value_dest_cookie == src_to_dest_asset_cookies.end()) {
1259 continue;
1260 }
1261
1262 dest_type->entries[e].cookie = value_dest_cookie->second;
1263 dest_type->entries[e].value.dataType = entry.value.dataType;
1264 dest_type->entries[e].value.data = attribue_data;
1265 dest_type->entries[e].type_spec_flags = entry.type_spec_flags;
1266 }
1267 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001268 }
1269 }
Ryan Mitchellb3ae42e2018-10-16 12:48:38 -07001270}
1271
1272void Theme::Dump() const {
1273 base::ScopedLogSeverity _log(base::INFO);
1274 LOG(INFO) << base::StringPrintf("Theme(this=%p, AssetManager2=%p)", this, asset_manager_);
1275
1276 for (int p = 0; p < packages_.size(); p++) {
1277 auto& package = packages_[p];
1278 if (package == nullptr) {
1279 continue;
1280 }
1281
1282 for (int t = 0; t < package->types.size(); t++) {
1283 auto& type = package->types[t];
1284 if (type == nullptr) {
1285 continue;
1286 }
1287
1288 for (int e = 0; e < type->entry_count; e++) {
1289 auto& entry = type->entries[e];
1290 if (entry.value.dataType == Res_value::TYPE_NULL &&
1291 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1292 continue;
1293 }
1294
1295 LOG(INFO) << base::StringPrintf(" entry(0x%08x)=(0x%08x) type=(0x%02x), cookie(%d)",
1296 make_resid(p, t, e), entry.value.data,
1297 entry.value.dataType, entry.cookie);
1298 }
1299 }
1300 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001301}
1302
1303} // namespace android