blob: a558ff7ccfc129658008f84b1e14d1fa7c55bf53 [file] [log] [blame]
Adam Lesinski7ad11102016-10-28 16:39:15 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/AssetManager2.h"
20
Adam Lesinski30080e22017-10-16 16:18:09 -070021#include <iterator>
Adam Lesinski0c405242017-01-13 20:47:26 -080022#include <set>
23
Adam Lesinski7ad11102016-10-28 16:39:15 -070024#include "android-base/logging.h"
25#include "android-base/stringprintf.h"
26#include "utils/ByteOrder.h"
27#include "utils/Trace.h"
28
29#ifdef _WIN32
30#ifdef ERROR
31#undef ERROR
32#endif
33#endif
34
Adam Lesinski929d6512017-01-16 19:11:19 -080035#include "androidfw/ResourceUtils.h"
36
Adam Lesinski7ad11102016-10-28 16:39:15 -070037namespace android {
38
Adam Lesinski64ee69d2018-01-08 17:38:30 -080039struct FindEntryResult {
40 // A pointer to the resource table entry for this resource.
41 // If the size of the entry is > sizeof(ResTable_entry), it can be cast to
42 // a ResTable_map_entry and processed as a bag/map.
43 const ResTable_entry* entry;
44
45 // The configuration for which the resulting entry was defined. This is already swapped to host
46 // endianness.
47 ResTable_config config;
48
49 // The bitmask of configuration axis with which the resource value varies.
50 uint32_t type_flags;
51
52 // The dynamic package ID map for the package from which this resource came from.
53 const DynamicRefTable* dynamic_ref_table;
54
55 // The string pool reference to the type's name. This uses a different string pool than
56 // the global string pool, but this is hidden from the caller.
57 StringPoolRef type_string_ref;
58
59 // The string pool reference to the entry's name. This uses a different string pool than
60 // the global string pool, but this is hidden from the caller.
61 StringPoolRef entry_string_ref;
62};
63
Adam Lesinski970bd8d2017-09-25 13:21:55 -070064AssetManager2::AssetManager2() {
65 memset(&configuration_, 0, sizeof(configuration_));
66}
Adam Lesinski7ad11102016-10-28 16:39:15 -070067
68bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets,
69 bool invalidate_caches) {
70 apk_assets_ = apk_assets;
Adam Lesinskida431a22016-12-29 16:08:16 -050071 BuildDynamicRefTable();
Adam Lesinski64ee69d2018-01-08 17:38:30 -080072 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -070073 if (invalidate_caches) {
74 InvalidateCaches(static_cast<uint32_t>(-1));
75 }
76 return true;
77}
78
Adam Lesinskida431a22016-12-29 16:08:16 -050079void AssetManager2::BuildDynamicRefTable() {
80 package_groups_.clear();
81 package_ids_.fill(0xff);
82
83 // 0x01 is reserved for the android package.
84 int next_package_id = 0x02;
85 const size_t apk_assets_count = apk_assets_.size();
86 for (size_t i = 0; i < apk_assets_count; i++) {
Adam Lesinski970bd8d2017-09-25 13:21:55 -070087 const LoadedArsc* loaded_arsc = apk_assets_[i]->GetLoadedArsc();
88
89 for (const std::unique_ptr<const LoadedPackage>& package : loaded_arsc->GetPackages()) {
Adam Lesinskida431a22016-12-29 16:08:16 -050090 // Get the package ID or assign one if a shared library.
91 int package_id;
92 if (package->IsDynamic()) {
93 package_id = next_package_id++;
94 } else {
95 package_id = package->GetPackageId();
96 }
97
98 // Add the mapping for package ID to index if not present.
99 uint8_t idx = package_ids_[package_id];
100 if (idx == 0xff) {
101 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size());
102 package_groups_.push_back({});
103 package_groups_.back().dynamic_ref_table.mAssignedPackageId = package_id;
104 }
105 PackageGroup* package_group = &package_groups_[idx];
106
107 // Add the package and to the set of packages with the same ID.
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800108 package_group->packages_.push_back(ConfiguredPackage{package.get(), {}});
Adam Lesinskida431a22016-12-29 16:08:16 -0500109 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i));
110
111 // Add the package name -> build time ID mappings.
112 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) {
113 String16 package_name(entry.package_name.c_str(), entry.package_name.size());
114 package_group->dynamic_ref_table.mEntries.replaceValueFor(
115 package_name, static_cast<uint8_t>(entry.package_id));
116 }
117 }
118 }
119
120 // Now assign the runtime IDs so that we have a build-time to runtime ID map.
121 const auto package_groups_end = package_groups_.end();
122 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800123 const std::string& package_name = iter->packages_[0].loaded_package_->GetPackageName();
Adam Lesinskida431a22016-12-29 16:08:16 -0500124 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) {
125 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()),
126 iter->dynamic_ref_table.mAssignedPackageId);
127 }
128 }
129}
130
131void AssetManager2::DumpToLog() const {
132 base::ScopedLogSeverity _log(base::INFO);
133
134 std::string list;
135 for (size_t i = 0; i < package_ids_.size(); i++) {
136 if (package_ids_[i] != 0xff) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800137 base::StringAppendF(&list, "%02x -> %d, ", (int)i, package_ids_[i]);
Adam Lesinskida431a22016-12-29 16:08:16 -0500138 }
139 }
140 LOG(INFO) << "Package ID map: " << list;
141
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800142 for (const auto& package_group : package_groups_) {
143 list = "";
144 for (const auto& package : package_group.packages_) {
145 base::StringAppendF(&list, "%s(%02x), ", package.loaded_package_->GetPackageName().c_str(),
146 package.loaded_package_->GetPackageId());
147 }
148 LOG(INFO) << base::StringPrintf("PG (%02x): ",
149 package_group.dynamic_ref_table.mAssignedPackageId)
150 << list;
Adam Lesinskida431a22016-12-29 16:08:16 -0500151 }
152}
Adam Lesinski7ad11102016-10-28 16:39:15 -0700153
154const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const {
155 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
156 return nullptr;
157 }
158 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool();
159}
160
Adam Lesinskida431a22016-12-29 16:08:16 -0500161const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const {
162 if (package_id >= package_ids_.size()) {
163 return nullptr;
164 }
165
166 const size_t idx = package_ids_[package_id];
167 if (idx == 0xff) {
168 return nullptr;
169 }
170 return &package_groups_[idx].dynamic_ref_table;
171}
172
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800173const DynamicRefTable* AssetManager2::GetDynamicRefTableForCookie(ApkAssetsCookie cookie) const {
174 for (const PackageGroup& package_group : package_groups_) {
175 for (const ApkAssetsCookie& package_cookie : package_group.cookies_) {
176 if (package_cookie == cookie) {
177 return &package_group.dynamic_ref_table;
178 }
179 }
180 }
181 return nullptr;
182}
183
Adam Lesinski7ad11102016-10-28 16:39:15 -0700184void AssetManager2::SetConfiguration(const ResTable_config& configuration) {
185 const int diff = configuration_.diff(configuration);
186 configuration_ = configuration;
187
188 if (diff) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800189 RebuildFilterList();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700190 InvalidateCaches(static_cast<uint32_t>(diff));
191 }
192}
193
Adam Lesinski0c405242017-01-13 20:47:26 -0800194std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800195 bool exclude_mipmap) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800196 ATRACE_CALL();
197 std::set<ResTable_config> configurations;
198 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800199 for (const ConfiguredPackage& package : package_group.packages_) {
200 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800201 continue;
202 }
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800203 package.loaded_package_->CollectConfigurations(exclude_mipmap, &configurations);
Adam Lesinski0c405242017-01-13 20:47:26 -0800204 }
205 }
206 return configurations;
207}
208
209std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800210 bool merge_equivalent_languages) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800211 ATRACE_CALL();
212 std::set<std::string> locales;
213 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800214 for (const ConfiguredPackage& package : package_group.packages_) {
215 if (exclude_system && package.loaded_package_->IsSystem()) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800216 continue;
217 }
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800218 package.loaded_package_->CollectLocales(merge_equivalent_languages, &locales);
Adam Lesinski0c405242017-01-13 20:47:26 -0800219 }
220 }
221 return locales;
222}
223
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800224std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename,
225 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700226 const std::string new_path = "assets/" + filename;
227 return OpenNonAsset(new_path, mode);
228}
229
230std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800231 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700232 const std::string new_path = "assets/" + filename;
233 return OpenNonAsset(new_path, cookie, mode);
234}
235
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800236std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800237 ATRACE_CALL();
238
239 std::string full_path = "assets/" + dirname;
240 std::unique_ptr<SortedVector<AssetDir::FileInfo>> files =
241 util::make_unique<SortedVector<AssetDir::FileInfo>>();
242
243 // Start from the back.
244 for (auto iter = apk_assets_.rbegin(); iter != apk_assets_.rend(); ++iter) {
245 const ApkAssets* apk_assets = *iter;
246
247 auto func = [&](const StringPiece& name, FileType type) {
248 AssetDir::FileInfo info;
249 info.setFileName(String8(name.data(), name.size()));
250 info.setFileType(type);
251 info.setSourceName(String8(apk_assets->GetPath().c_str()));
252 files->add(info);
253 };
254
255 if (!apk_assets->ForEachFile(full_path, func)) {
256 return {};
257 }
258 }
259
260 std::unique_ptr<AssetDir> asset_dir = util::make_unique<AssetDir>();
261 asset_dir->setFileList(files.release());
262 return asset_dir;
263}
264
Adam Lesinski7ad11102016-10-28 16:39:15 -0700265// Search in reverse because that's how we used to do it and we need to preserve behaviour.
266// This is unfortunate, because ClassLoaders delegate to the parent first, so the order
267// is inconsistent for split APKs.
268std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
269 Asset::AccessMode mode,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800270 ApkAssetsCookie* out_cookie) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700271 ATRACE_CALL();
272 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) {
273 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode);
274 if (asset) {
275 if (out_cookie != nullptr) {
276 *out_cookie = i;
277 }
278 return asset;
279 }
280 }
281
282 if (out_cookie != nullptr) {
283 *out_cookie = kInvalidCookie;
284 }
285 return {};
286}
287
288std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800289 ApkAssetsCookie cookie,
290 Asset::AccessMode mode) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700291 ATRACE_CALL();
292 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) {
293 return {};
294 }
295 return apk_assets_[cookie]->Open(filename, mode);
296}
297
298ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800299 bool /*stop_at_first_match*/,
300 FindEntryResult* out_entry) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700301 // Might use this if density_override != 0.
302 ResTable_config density_override_config;
303
304 // Select our configuration or generate a density override configuration.
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800305 const ResTable_config* desired_config = &configuration_;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700306 if (density_override != 0 && density_override != configuration_.density) {
307 density_override_config = configuration_;
308 density_override_config.density = density_override;
309 desired_config = &density_override_config;
310 }
311
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800312 if (!is_valid_resid(resid)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500313 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid);
314 return kInvalidCookie;
315 }
316
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800317 const uint32_t package_id = get_package_id(resid);
318 const uint8_t type_idx = get_type_id(resid) - 1;
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800319 const uint16_t entry_idx = get_entry_id(resid);
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800320
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800321 const uint8_t package_idx = package_ids_[package_id];
322 if (package_idx == 0xff) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500323 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid);
324 return kInvalidCookie;
325 }
326
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800327 const PackageGroup& package_group = package_groups_[package_idx];
Adam Lesinski50706b62018-01-23 03:16:16 -0800328 const size_t package_count = package_group.packages_.size();
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800329
330 ApkAssetsCookie best_cookie = kInvalidCookie;
331 const LoadedPackage* best_package = nullptr;
332 const ResTable_type* best_type = nullptr;
333 const ResTable_config* best_config = nullptr;
334 ResTable_config best_config_copy;
335 uint32_t best_offset = 0u;
336 uint32_t type_flags = 0u;
337
338 // If desired_config is the same as the set configuration, then we can use our filtered list
339 // and we don't need to match the configurations, since they already matched.
340 const bool use_fast_path = desired_config == &configuration_;
341
342 for (size_t pi = 0; pi < package_count; pi++) {
343 const ConfiguredPackage& loaded_package_impl = package_group.packages_[pi];
344 const LoadedPackage* loaded_package = loaded_package_impl.loaded_package_;
345 ApkAssetsCookie cookie = package_group.cookies_[pi];
346
347 // If the type IDs are offset in this package, we need to take that into account when searching
348 // for a type.
349 const TypeSpec* type_spec = loaded_package->GetTypeSpecByTypeIndex(type_idx);
350 if (UNLIKELY(type_spec == nullptr)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700351 continue;
352 }
353
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800354 uint16_t local_entry_idx = entry_idx;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700355
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800356 // If there is an IDMAP supplied with this package, translate the entry ID.
357 if (type_spec->idmap_entries != nullptr) {
358 if (!LoadedIdmap::Lookup(type_spec->idmap_entries, local_entry_idx, &local_entry_idx)) {
359 // There is no mapping, so the resource is not meant to be in this overlay package.
360 continue;
361 }
362 }
363
364 type_flags |= type_spec->GetFlagsForEntryIndex(local_entry_idx);
365
366 // If the package is an overlay, then even configurations that are the same MUST be chosen.
367 const bool package_is_overlay = loaded_package->IsOverlay();
368
369 const FilteredConfigGroup& filtered_group = loaded_package_impl.filtered_configs_[type_idx];
370 if (use_fast_path) {
371 const std::vector<ResTable_config>& candidate_configs = filtered_group.configurations;
372 const size_t type_count = candidate_configs.size();
373 for (uint32_t i = 0; i < type_count; i++) {
374 const ResTable_config& this_config = candidate_configs[i];
375
376 // We can skip calling ResTable_config::match() because we know that all candidate
377 // configurations that do NOT match have been filtered-out.
378 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
379 (package_is_overlay && this_config.compare(*best_config) == 0)) {
380 // The configuration matches and is better than the previous selection.
381 // Find the entry value if it exists for this configuration.
382 const ResTable_type* type_chunk = filtered_group.types[i];
383 const uint32_t offset = LoadedPackage::GetEntryOffset(type_chunk, local_entry_idx);
384 if (offset == ResTable_type::NO_ENTRY) {
385 continue;
386 }
387
388 best_cookie = cookie;
389 best_package = loaded_package;
390 best_type = type_chunk;
391 best_config = &this_config;
392 best_offset = offset;
393 }
394 }
395 } else {
396 // This is the slower path, which doesn't use the filtered list of configurations.
397 // Here we must read the ResTable_config from the mmapped APK, convert it to host endianness
398 // and fill in any new fields that did not exist when the APK was compiled.
399 // Furthermore when selecting configurations we can't just record the pointer to the
400 // ResTable_config, we must copy it.
401 const auto iter_end = type_spec->types + type_spec->type_count;
402 for (auto iter = type_spec->types; iter != iter_end; ++iter) {
403 ResTable_config this_config;
404 this_config.copyFromDtoH((*iter)->config);
405
406 if (this_config.match(*desired_config)) {
407 if ((best_config == nullptr || this_config.isBetterThan(*best_config, desired_config)) ||
408 (package_is_overlay && this_config.compare(*best_config) == 0)) {
409 // The configuration matches and is better than the previous selection.
410 // Find the entry value if it exists for this configuration.
411 const uint32_t offset = LoadedPackage::GetEntryOffset(*iter, local_entry_idx);
412 if (offset == ResTable_type::NO_ENTRY) {
413 continue;
414 }
415
416 best_cookie = cookie;
417 best_package = loaded_package;
418 best_type = *iter;
419 best_config_copy = this_config;
420 best_config = &best_config_copy;
421 best_offset = offset;
422 }
423 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700424 }
425 }
426 }
427
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800428 if (UNLIKELY(best_cookie == kInvalidCookie)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700429 return kInvalidCookie;
430 }
431
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800432 const ResTable_entry* best_entry = LoadedPackage::GetEntryFromOffset(best_type, best_offset);
433 if (UNLIKELY(best_entry == nullptr)) {
434 return kInvalidCookie;
435 }
436
437 out_entry->entry = best_entry;
438 out_entry->config = *best_config;
439 out_entry->type_flags = type_flags;
440 out_entry->type_string_ref = StringPoolRef(best_package->GetTypeStringPool(), best_type->id - 1);
441 out_entry->entry_string_ref =
442 StringPoolRef(best_package->GetKeyStringPool(), best_entry->key.index);
Adam Lesinskida431a22016-12-29 16:08:16 -0500443 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table;
Adam Lesinskida431a22016-12-29 16:08:16 -0500444 return best_cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700445}
446
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800447bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700448 ATRACE_CALL();
449
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700450 FindEntryResult entry;
451 ApkAssetsCookie cookie =
452 FindEntry(resid, 0u /* density_override */, true /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700453 if (cookie == kInvalidCookie) {
454 return false;
455 }
456
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800457 const LoadedPackage* package =
458 apk_assets_[cookie]->GetLoadedArsc()->GetPackageById(get_package_id(resid));
Adam Lesinskida431a22016-12-29 16:08:16 -0500459 if (package == nullptr) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700460 return false;
461 }
462
Adam Lesinskida431a22016-12-29 16:08:16 -0500463 out_name->package = package->GetPackageName().data();
464 out_name->package_len = package->GetPackageName().size();
Adam Lesinski7ad11102016-10-28 16:39:15 -0700465
466 out_name->type = entry.type_string_ref.string8(&out_name->type_len);
467 out_name->type16 = nullptr;
468 if (out_name->type == nullptr) {
469 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len);
470 if (out_name->type16 == nullptr) {
471 return false;
472 }
473 }
474
475 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len);
476 out_name->entry16 = nullptr;
477 if (out_name->entry == nullptr) {
478 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len);
479 if (out_name->entry16 == nullptr) {
480 return false;
481 }
482 }
483 return true;
484}
485
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800486bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) const {
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700487 FindEntryResult entry;
488 ApkAssetsCookie cookie =
489 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
490 if (cookie != kInvalidCookie) {
491 *out_flags = entry.type_flags;
492 return cookie;
493 }
494 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700495}
496
497ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag,
498 uint16_t density_override, Res_value* out_value,
499 ResTable_config* out_selected_config,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800500 uint32_t* out_flags) const {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700501 ATRACE_CALL();
502
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700503 FindEntryResult entry;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700504 ApkAssetsCookie cookie =
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700505 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700506 if (cookie == kInvalidCookie) {
507 return kInvalidCookie;
508 }
509
Adam Lesinski498f6052017-11-29 13:24:29 -0800510 if (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700511 if (!may_be_bag) {
512 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid);
Adam Lesinski0c405242017-01-13 20:47:26 -0800513 return kInvalidCookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700514 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800515
516 // Create a reference since we can't represent this complex type as a Res_value.
517 out_value->dataType = Res_value::TYPE_REFERENCE;
518 out_value->data = resid;
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800519 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700520 *out_flags = entry.type_flags;
Adam Lesinski0c405242017-01-13 20:47:26 -0800521 return cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700522 }
523
524 const Res_value* device_value = reinterpret_cast<const Res_value*>(
525 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size));
526 out_value->copyFrom_dtoh(*device_value);
Adam Lesinskida431a22016-12-29 16:08:16 -0500527
528 // Convert the package ID to the runtime assigned package ID.
529 entry.dynamic_ref_table->lookupResourceValue(out_value);
530
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800531 *out_selected_config = entry.config;
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700532 *out_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700533 return cookie;
534}
535
Adam Lesinski0c405242017-01-13 20:47:26 -0800536ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value,
537 ResTable_config* in_out_selected_config,
538 uint32_t* in_out_flags,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800539 uint32_t* out_last_reference) const {
Adam Lesinski0c405242017-01-13 20:47:26 -0800540 ATRACE_CALL();
541 constexpr const int kMaxIterations = 20;
542
Adam Lesinski0c405242017-01-13 20:47:26 -0800543 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE &&
544 in_out_value->data != 0u && iteration < kMaxIterations;
545 iteration++) {
Adam Lesinskidcb3c652017-01-23 12:58:11 -0800546 *out_last_reference = in_out_value->data;
Adam Lesinski0c405242017-01-13 20:47:26 -0800547 uint32_t new_flags = 0u;
548 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/,
549 in_out_value, in_out_selected_config, &new_flags);
550 if (cookie == kInvalidCookie) {
551 return kInvalidCookie;
552 }
553 if (in_out_flags != nullptr) {
554 *in_out_flags |= new_flags;
555 }
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -0800556 if (*out_last_reference == in_out_value->data) {
Adam Lesinski0c405242017-01-13 20:47:26 -0800557 // This reference can't be resolved, so exit now and let the caller deal with it.
558 return cookie;
559 }
560 }
561 return cookie;
562}
563
Adam Lesinski7ad11102016-10-28 16:39:15 -0700564const ResolvedBag* AssetManager2::GetBag(uint32_t resid) {
565 ATRACE_CALL();
566
567 auto cached_iter = cached_bags_.find(resid);
568 if (cached_iter != cached_bags_.end()) {
569 return cached_iter->second.get();
570 }
571
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700572 FindEntryResult entry;
573 ApkAssetsCookie cookie =
574 FindEntry(resid, 0u /* density_override */, false /* stop_at_first_match */, &entry);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700575 if (cookie == kInvalidCookie) {
576 return nullptr;
577 }
578
579 // Check that the size of the entry header is at least as big as
580 // the desired ResTable_map_entry. Also verify that the entry
581 // was intended to be a map.
582 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) ||
583 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) {
584 // Not a bag, nothing to do.
585 return nullptr;
586 }
587
588 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry);
589 const ResTable_map* map_entry =
590 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size);
591 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count);
592
Adam Lesinskida431a22016-12-29 16:08:16 -0500593 uint32_t parent_resid = dtohl(map->parent.ident);
594 if (parent_resid == 0) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700595 // There is no parent, meaning there is nothing to inherit and we can do a simple
596 // copy of the entries in the map.
597 const size_t entry_count = map_entry_end - map_entry;
598 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
599 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))};
600 ResolvedBag::Entry* new_entry = new_bag->entries;
601 for (; map_entry != map_entry_end; ++map_entry) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500602 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800603 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500604 // Attributes, arrays, etc don't have a resource id as the name. They specify
605 // other data, which would be wrong to change via a lookup.
606 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800607 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
608 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500609 return nullptr;
610 }
611 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700612 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500613 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700614 new_entry->key_pool = nullptr;
615 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700616 new_entry->value.copyFrom_dtoh(map_entry->value);
617 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
618 if (err != NO_ERROR) {
619 LOG(ERROR) << base::StringPrintf(
620 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
621 new_entry->value.data, new_key);
622 return nullptr;
623 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700624 ++new_entry;
625 }
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700626 new_bag->type_spec_flags = entry.type_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700627 new_bag->entry_count = static_cast<uint32_t>(entry_count);
628 ResolvedBag* result = new_bag.get();
629 cached_bags_[resid] = std::move(new_bag);
630 return result;
631 }
632
Adam Lesinskida431a22016-12-29 16:08:16 -0500633 // In case the parent is a dynamic reference, resolve it.
634 entry.dynamic_ref_table->lookupResourceId(&parent_resid);
635
Adam Lesinski7ad11102016-10-28 16:39:15 -0700636 // Get the parent and do a merge of the keys.
Adam Lesinskida431a22016-12-29 16:08:16 -0500637 const ResolvedBag* parent_bag = GetBag(parent_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700638 if (parent_bag == nullptr) {
639 // Failed to get the parent that should exist.
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800640 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid,
641 resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700642 return nullptr;
643 }
644
Adam Lesinski7ad11102016-10-28 16:39:15 -0700645 // Create the max possible entries we can make. Once we construct the bag,
646 // we will realloc to fit to size.
647 const size_t max_count = parent_bag->entry_count + dtohl(map->count);
George Burgess IV09b119f2017-07-25 15:00:04 -0700648 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>(
649 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry))))};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700650 ResolvedBag::Entry* new_entry = new_bag->entries;
651
652 const ResolvedBag::Entry* parent_entry = parent_bag->entries;
653 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count;
654
655 // The keys are expected to be in sorted order. Merge the two bags.
656 while (map_entry != map_entry_end && parent_entry != parent_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500657 uint32_t child_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800658 if (!is_internal_resid(child_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500659 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800660 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key,
661 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500662 return nullptr;
663 }
664 }
665
Adam Lesinski7ad11102016-10-28 16:39:15 -0700666 if (child_key <= parent_entry->key) {
667 // Use the child key if it comes before the parent
668 // or is equal to the parent (overrides).
669 new_entry->cookie = cookie;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700670 new_entry->key = child_key;
671 new_entry->key_pool = nullptr;
672 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700673 new_entry->value.copyFrom_dtoh(map_entry->value);
674 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
675 if (err != NO_ERROR) {
676 LOG(ERROR) << base::StringPrintf(
677 "Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.", new_entry->value.dataType,
678 new_entry->value.data, child_key);
679 return nullptr;
680 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700681 ++map_entry;
682 } else {
683 // Take the parent entry as-is.
684 memcpy(new_entry, parent_entry, sizeof(*new_entry));
685 }
686
687 if (child_key >= parent_entry->key) {
688 // Move to the next parent entry if we used it or it was overridden.
689 ++parent_entry;
690 }
691 // Increment to the next entry to fill.
692 ++new_entry;
693 }
694
695 // Finish the child entries if they exist.
696 while (map_entry != map_entry_end) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500697 uint32_t new_key = dtohl(map_entry->name.ident);
Adam Lesinski929d6512017-01-16 19:11:19 -0800698 if (!is_internal_resid(new_key)) {
Adam Lesinskida431a22016-12-29 16:08:16 -0500699 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800700 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key,
701 resid);
Adam Lesinskida431a22016-12-29 16:08:16 -0500702 return nullptr;
703 }
704 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700705 new_entry->cookie = cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -0500706 new_entry->key = new_key;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700707 new_entry->key_pool = nullptr;
708 new_entry->type_pool = nullptr;
Adam Lesinski30080e22017-10-16 16:18:09 -0700709 new_entry->value.copyFrom_dtoh(map_entry->value);
710 status_t err = entry.dynamic_ref_table->lookupResourceValue(&new_entry->value);
711 if (err != NO_ERROR) {
712 LOG(ERROR) << base::StringPrintf("Failed to resolve value t=0x%02x d=0x%08x for key 0x%08x.",
713 new_entry->value.dataType, new_entry->value.data, new_key);
714 return nullptr;
715 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700716 ++map_entry;
717 ++new_entry;
718 }
719
720 // Finish the parent entries if they exist.
721 if (parent_entry != parent_entry_end) {
722 // Take the rest of the parent entries as-is.
723 const size_t num_entries_to_copy = parent_entry_end - parent_entry;
724 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry));
725 new_entry += num_entries_to_copy;
726 }
727
728 // Resize the resulting array to fit.
729 const size_t actual_count = new_entry - new_bag->entries;
730 if (actual_count != max_count) {
George Burgess IV09b119f2017-07-25 15:00:04 -0700731 new_bag.reset(reinterpret_cast<ResolvedBag*>(realloc(
732 new_bag.release(), sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))));
Adam Lesinski7ad11102016-10-28 16:39:15 -0700733 }
734
Adam Lesinski1a1e9c22017-10-13 15:45:34 -0700735 // Combine flags from the parent and our own bag.
736 new_bag->type_spec_flags = entry.type_flags | parent_bag->type_spec_flags;
George Burgess IV09b119f2017-07-25 15:00:04 -0700737 new_bag->entry_count = static_cast<uint32_t>(actual_count);
738 ResolvedBag* result = new_bag.get();
739 cached_bags_[resid] = std::move(new_bag);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700740 return result;
741}
742
Adam Lesinski929d6512017-01-16 19:11:19 -0800743static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) {
744 ssize_t len =
745 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false);
746 if (len < 0) {
747 return false;
748 }
749 out->resize(static_cast<size_t>(len));
750 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(),
751 static_cast<size_t>(len + 1));
752 return true;
753}
754
Adam Lesinski0c405242017-01-13 20:47:26 -0800755uint32_t AssetManager2::GetResourceId(const std::string& resource_name,
756 const std::string& fallback_type,
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800757 const std::string& fallback_package) const {
Adam Lesinski929d6512017-01-16 19:11:19 -0800758 StringPiece package_name, type, entry;
759 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) {
760 return 0u;
761 }
762
763 if (entry.empty()) {
764 return 0u;
765 }
766
767 if (package_name.empty()) {
768 package_name = fallback_package;
769 }
770
771 if (type.empty()) {
772 type = fallback_type;
773 }
774
775 std::u16string type16;
776 if (!Utf8ToUtf16(type, &type16)) {
777 return 0u;
778 }
779
780 std::u16string entry16;
781 if (!Utf8ToUtf16(entry, &entry16)) {
782 return 0u;
783 }
784
785 const StringPiece16 kAttr16 = u"attr";
786 const static std::u16string kAttrPrivate16 = u"^attr-private";
787
788 for (const PackageGroup& package_group : package_groups_) {
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800789 for (const ConfiguredPackage& package_impl : package_group.packages_) {
790 const LoadedPackage* package = package_impl.loaded_package_;
Adam Lesinski929d6512017-01-16 19:11:19 -0800791 if (package_name != package->GetPackageName()) {
792 // All packages in the same group are expected to have the same package name.
793 break;
794 }
795
796 uint32_t resid = package->FindEntryByName(type16, entry16);
797 if (resid == 0u && kAttr16 == type16) {
798 // Private attributes in libraries (such as the framework) are sometimes encoded
799 // under the type '^attr-private' in order to leave the ID space of public 'attr'
800 // free for future additions. Check '^attr-private' for the same name.
801 resid = package->FindEntryByName(kAttrPrivate16, entry16);
802 }
803
804 if (resid != 0u) {
805 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId);
806 }
807 }
808 }
Adam Lesinski0c405242017-01-13 20:47:26 -0800809 return 0u;
810}
811
Adam Lesinski64ee69d2018-01-08 17:38:30 -0800812void AssetManager2::RebuildFilterList() {
813 for (PackageGroup& group : package_groups_) {
814 for (ConfiguredPackage& impl : group.packages_) {
815 // Destroy it.
816 impl.filtered_configs_.~ByteBucketArray();
817
818 // Re-create it.
819 new (&impl.filtered_configs_) ByteBucketArray<FilteredConfigGroup>();
820
821 // Create the filters here.
822 impl.loaded_package_->ForEachTypeSpec([&](const TypeSpec* spec, uint8_t type_index) {
823 FilteredConfigGroup& group = impl.filtered_configs_.editItemAt(type_index);
824 const auto iter_end = spec->types + spec->type_count;
825 for (auto iter = spec->types; iter != iter_end; ++iter) {
826 ResTable_config this_config;
827 this_config.copyFromDtoH((*iter)->config);
828 if (this_config.match(configuration_)) {
829 group.configurations.push_back(this_config);
830 group.types.push_back(*iter);
831 }
832 }
833 });
834 }
835 }
836}
837
Adam Lesinski7ad11102016-10-28 16:39:15 -0700838void AssetManager2::InvalidateCaches(uint32_t diff) {
839 if (diff == 0xffffffffu) {
840 // Everything must go.
841 cached_bags_.clear();
842 return;
843 }
844
845 // Be more conservative with what gets purged. Only if the bag has other possible
846 // variations with respect to what changed (diff) should we remove it.
847 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) {
848 if (diff & iter->second->type_spec_flags) {
849 iter = cached_bags_.erase(iter);
850 } else {
851 ++iter;
852 }
853 }
854}
855
Adam Lesinski30080e22017-10-16 16:18:09 -0700856std::unique_ptr<Theme> AssetManager2::NewTheme() {
857 return std::unique_ptr<Theme>(new Theme(this));
858}
859
860Theme::Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {
861}
862
863Theme::~Theme() = default;
864
865namespace {
866
867struct ThemeEntry {
868 ApkAssetsCookie cookie;
869 uint32_t type_spec_flags;
870 Res_value value;
871};
872
873struct ThemeType {
874 int entry_count;
875 ThemeEntry entries[0];
876};
877
878constexpr size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1;
879
880} // namespace
881
882struct Theme::Package {
883 // Each element of Type will be a dynamically sized object
884 // allocated to have the entries stored contiguously with the Type.
885 std::array<util::unique_cptr<ThemeType>, kTypeCount> types;
886};
Adam Lesinski7ad11102016-10-28 16:39:15 -0700887
888bool Theme::ApplyStyle(uint32_t resid, bool force) {
889 ATRACE_CALL();
890
891 const ResolvedBag* bag = asset_manager_->GetBag(resid);
892 if (bag == nullptr) {
893 return false;
894 }
895
896 // Merge the flags from this style.
897 type_spec_flags_ |= bag->type_spec_flags;
898
Adam Lesinski30080e22017-10-16 16:18:09 -0700899 int last_type_idx = -1;
900 int last_package_idx = -1;
901 Package* last_package = nullptr;
902 ThemeType* last_type = nullptr;
903
904 // Iterate backwards, because each bag is sorted in ascending key ID order, meaning we will only
905 // need to perform one resize per type.
906 using reverse_bag_iterator = std::reverse_iterator<const ResolvedBag::Entry*>;
907 const auto bag_iter_end = reverse_bag_iterator(begin(bag));
908 for (auto bag_iter = reverse_bag_iterator(end(bag)); bag_iter != bag_iter_end; ++bag_iter) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700909 const uint32_t attr_resid = bag_iter->key;
910
Adam Lesinski30080e22017-10-16 16:18:09 -0700911 // If the resource ID passed in is not a style, the key can be some other identifier that is not
912 // a resource ID. We should fail fast instead of operating with strange resource IDs.
Adam Lesinski929d6512017-01-16 19:11:19 -0800913 if (!is_valid_resid(attr_resid)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700914 return false;
915 }
916
Adam Lesinski30080e22017-10-16 16:18:09 -0700917 // We don't use the 0-based index for the type so that we can avoid doing ID validation
918 // upon lookup. Instead, we keep space for the type ID 0 in our data structures. Since
919 // the construction of this type is guarded with a resource ID check, it will never be
920 // populated, and querying type ID 0 will always fail.
921 const int package_idx = get_package_id(attr_resid);
922 const int type_idx = get_type_id(attr_resid);
923 const int entry_idx = get_entry_id(attr_resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700924
Adam Lesinski30080e22017-10-16 16:18:09 -0700925 if (last_package_idx != package_idx) {
926 std::unique_ptr<Package>& package = packages_[package_idx];
927 if (package == nullptr) {
928 package.reset(new Package());
Adam Lesinski7ad11102016-10-28 16:39:15 -0700929 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700930 last_package_idx = package_idx;
931 last_package = package.get();
932 last_type_idx = -1;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700933 }
Adam Lesinski30080e22017-10-16 16:18:09 -0700934
935 if (last_type_idx != type_idx) {
936 util::unique_cptr<ThemeType>& type = last_package->types[type_idx];
937 if (type == nullptr) {
938 // Allocate enough memory to contain this entry_idx. Since we're iterating in reverse over
939 // a sorted list of attributes, this shouldn't be resized again during this method call.
940 type.reset(reinterpret_cast<ThemeType*>(
941 calloc(sizeof(ThemeType) + (entry_idx + 1) * sizeof(ThemeEntry), 1)));
942 type->entry_count = entry_idx + 1;
943 } else if (entry_idx >= type->entry_count) {
944 // Reallocate the memory to contain this entry_idx. Since we're iterating in reverse over
945 // a sorted list of attributes, this shouldn't be resized again during this method call.
946 const int new_count = entry_idx + 1;
947 type.reset(reinterpret_cast<ThemeType*>(
948 realloc(type.release(), sizeof(ThemeType) + (new_count * sizeof(ThemeEntry)))));
949
950 // Clear out the newly allocated space (which isn't zeroed).
951 memset(type->entries + type->entry_count, 0,
952 (new_count - type->entry_count) * sizeof(ThemeEntry));
953 type->entry_count = new_count;
954 }
955 last_type_idx = type_idx;
956 last_type = type.get();
957 }
958
959 ThemeEntry& entry = last_type->entries[entry_idx];
960 if (force || (entry.value.dataType == Res_value::TYPE_NULL &&
961 entry.value.data != Res_value::DATA_NULL_EMPTY)) {
Adam Lesinski7ad11102016-10-28 16:39:15 -0700962 entry.cookie = bag_iter->cookie;
963 entry.type_spec_flags |= bag->type_spec_flags;
964 entry.value = bag_iter->value;
965 }
966 }
967 return true;
968}
969
970ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value,
971 uint32_t* out_flags) const {
Adam Lesinski30080e22017-10-16 16:18:09 -0700972 int cnt = 20;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700973
974 uint32_t type_spec_flags = 0u;
975
Adam Lesinski30080e22017-10-16 16:18:09 -0700976 do {
977 const int package_idx = get_package_id(resid);
Adam Lesinski7ad11102016-10-28 16:39:15 -0700978 const Package* package = packages_[package_idx].get();
Adam Lesinski30080e22017-10-16 16:18:09 -0700979 if (package != nullptr) {
980 // The themes are constructed with a 1-based type ID, so no need to decrement here.
981 const int type_idx = get_type_id(resid);
982 const ThemeType* type = package->types[type_idx].get();
983 if (type != nullptr) {
984 const int entry_idx = get_entry_id(resid);
985 if (entry_idx < type->entry_count) {
986 const ThemeEntry& entry = type->entries[entry_idx];
987 type_spec_flags |= entry.type_spec_flags;
Adam Lesinski7ad11102016-10-28 16:39:15 -0700988
Adam Lesinski30080e22017-10-16 16:18:09 -0700989 if (entry.value.dataType == Res_value::TYPE_ATTRIBUTE) {
990 if (cnt > 0) {
991 cnt--;
992 resid = entry.value.data;
993 continue;
994 }
995 return kInvalidCookie;
996 }
Adam Lesinski7ad11102016-10-28 16:39:15 -0700997
Adam Lesinski30080e22017-10-16 16:18:09 -0700998 // @null is different than @empty.
999 if (entry.value.dataType == Res_value::TYPE_NULL &&
1000 entry.value.data != Res_value::DATA_NULL_EMPTY) {
1001 return kInvalidCookie;
1002 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001003
Adam Lesinski30080e22017-10-16 16:18:09 -07001004 *out_value = entry.value;
Adam Lesinskida431a22016-12-29 16:08:16 -05001005 *out_flags = type_spec_flags;
Adam Lesinski30080e22017-10-16 16:18:09 -07001006 return entry.cookie;
Adam Lesinskida431a22016-12-29 16:08:16 -05001007 }
Adam Lesinskida431a22016-12-29 16:08:16 -05001008 }
Adam Lesinski7ad11102016-10-28 16:39:15 -07001009 }
Adam Lesinski30080e22017-10-16 16:18:09 -07001010 break;
1011 } while (true);
Adam Lesinski7ad11102016-10-28 16:39:15 -07001012 return kInvalidCookie;
1013}
1014
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001015ApkAssetsCookie Theme::ResolveAttributeReference(ApkAssetsCookie cookie, Res_value* in_out_value,
1016 ResTable_config* in_out_selected_config,
1017 uint32_t* in_out_type_spec_flags,
Adam Lesinski64ee69d2018-01-08 17:38:30 -08001018 uint32_t* out_last_ref) const {
Adam Lesinskid1ecd7a2017-01-23 12:58:11 -08001019 if (in_out_value->dataType == Res_value::TYPE_ATTRIBUTE) {
1020 uint32_t new_flags;
1021 cookie = GetAttribute(in_out_value->data, in_out_value, &new_flags);
1022 if (cookie == kInvalidCookie) {
1023 return kInvalidCookie;
1024 }
1025
1026 if (in_out_type_spec_flags != nullptr) {
1027 *in_out_type_spec_flags |= new_flags;
1028 }
1029 }
1030 return asset_manager_->ResolveReference(cookie, in_out_value, in_out_selected_config,
1031 in_out_type_spec_flags, out_last_ref);
1032}
1033
Adam Lesinski7ad11102016-10-28 16:39:15 -07001034void Theme::Clear() {
1035 type_spec_flags_ = 0u;
1036 for (std::unique_ptr<Package>& package : packages_) {
1037 package.reset();
1038 }
1039}
1040
1041bool Theme::SetTo(const Theme& o) {
1042 if (this == &o) {
1043 return true;
1044 }
1045
Adam Lesinski7ad11102016-10-28 16:39:15 -07001046 type_spec_flags_ = o.type_spec_flags_;
1047
Adam Lesinski03ebac82017-09-25 13:10:14 -07001048 const bool copy_only_system = asset_manager_ != o.asset_manager_;
1049
Adam Lesinskida431a22016-12-29 16:08:16 -05001050 for (size_t p = 0; p < packages_.size(); p++) {
Adam Lesinski7ad11102016-10-28 16:39:15 -07001051 const Package* package = o.packages_[p].get();
Adam Lesinski03ebac82017-09-25 13:10:14 -07001052 if (package == nullptr || (copy_only_system && p != 0x01)) {
1053 // The other theme doesn't have this package, clear ours.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001054 packages_[p].reset();
1055 continue;
1056 }
1057
Adam Lesinski03ebac82017-09-25 13:10:14 -07001058 if (packages_[p] == nullptr) {
1059 // The other theme has this package, but we don't. Make one.
1060 packages_[p].reset(new Package());
1061 }
1062
Adam Lesinskida431a22016-12-29 16:08:16 -05001063 for (size_t t = 0; t < package->types.size(); t++) {
Adam Lesinski30080e22017-10-16 16:18:09 -07001064 const ThemeType* type = package->types[t].get();
Adam Lesinski7ad11102016-10-28 16:39:15 -07001065 if (type == nullptr) {
Adam Lesinski03ebac82017-09-25 13:10:14 -07001066 // The other theme doesn't have this type, clear ours.
Adam Lesinski7ad11102016-10-28 16:39:15 -07001067 packages_[p]->types[t].reset();
1068 continue;
1069 }
1070
Adam Lesinski03ebac82017-09-25 13:10:14 -07001071 // Create a new type and update it to theirs.
Adam Lesinski30080e22017-10-16 16:18:09 -07001072 const size_t type_alloc_size = sizeof(ThemeType) + (type->entry_count * sizeof(ThemeEntry));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001073 void* copied_data = malloc(type_alloc_size);
1074 memcpy(copied_data, type, type_alloc_size);
Adam Lesinski30080e22017-10-16 16:18:09 -07001075 packages_[p]->types[t].reset(reinterpret_cast<ThemeType*>(copied_data));
Adam Lesinski7ad11102016-10-28 16:39:15 -07001076 }
1077 }
1078 return true;
1079}
1080
1081} // namespace android