AssetManager2.cpp revision 929d6517dfd338f0d481dbe6587643d5aef27ec6
1/* 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 21#include <set> 22 23#include "android-base/logging.h" 24#include "android-base/stringprintf.h" 25#include "utils/ByteOrder.h" 26#include "utils/Trace.h" 27 28#ifdef _WIN32 29#ifdef ERROR 30#undef ERROR 31#endif 32#endif 33 34#include "androidfw/ResourceUtils.h" 35 36namespace android { 37 38AssetManager2::AssetManager2() { memset(&configuration_, 0, sizeof(configuration_)); } 39 40bool AssetManager2::SetApkAssets(const std::vector<const ApkAssets*>& apk_assets, 41 bool invalidate_caches) { 42 apk_assets_ = apk_assets; 43 BuildDynamicRefTable(); 44 if (invalidate_caches) { 45 InvalidateCaches(static_cast<uint32_t>(-1)); 46 } 47 return true; 48} 49 50void AssetManager2::BuildDynamicRefTable() { 51 package_groups_.clear(); 52 package_ids_.fill(0xff); 53 54 // 0x01 is reserved for the android package. 55 int next_package_id = 0x02; 56 const size_t apk_assets_count = apk_assets_.size(); 57 for (size_t i = 0; i < apk_assets_count; i++) { 58 const ApkAssets* apk_asset = apk_assets_[i]; 59 for (const std::unique_ptr<const LoadedPackage>& package : 60 apk_asset->GetLoadedArsc()->GetPackages()) { 61 // Get the package ID or assign one if a shared library. 62 int package_id; 63 if (package->IsDynamic()) { 64 package_id = next_package_id++; 65 } else { 66 package_id = package->GetPackageId(); 67 } 68 69 // Add the mapping for package ID to index if not present. 70 uint8_t idx = package_ids_[package_id]; 71 if (idx == 0xff) { 72 package_ids_[package_id] = idx = static_cast<uint8_t>(package_groups_.size()); 73 package_groups_.push_back({}); 74 package_groups_.back().dynamic_ref_table.mAssignedPackageId = package_id; 75 } 76 PackageGroup* package_group = &package_groups_[idx]; 77 78 // Add the package and to the set of packages with the same ID. 79 package_group->packages_.push_back(package.get()); 80 package_group->cookies_.push_back(static_cast<ApkAssetsCookie>(i)); 81 82 // Add the package name -> build time ID mappings. 83 for (const DynamicPackageEntry& entry : package->GetDynamicPackageMap()) { 84 String16 package_name(entry.package_name.c_str(), entry.package_name.size()); 85 package_group->dynamic_ref_table.mEntries.replaceValueFor( 86 package_name, static_cast<uint8_t>(entry.package_id)); 87 } 88 } 89 } 90 91 // Now assign the runtime IDs so that we have a build-time to runtime ID map. 92 const auto package_groups_end = package_groups_.end(); 93 for (auto iter = package_groups_.begin(); iter != package_groups_end; ++iter) { 94 const std::string& package_name = iter->packages_[0]->GetPackageName(); 95 for (auto iter2 = package_groups_.begin(); iter2 != package_groups_end; ++iter2) { 96 iter2->dynamic_ref_table.addMapping(String16(package_name.c_str(), package_name.size()), 97 iter->dynamic_ref_table.mAssignedPackageId); 98 } 99 } 100} 101 102void AssetManager2::DumpToLog() const { 103 base::ScopedLogSeverity _log(base::INFO); 104 105 std::string list; 106 for (size_t i = 0; i < package_ids_.size(); i++) { 107 if (package_ids_[i] != 0xff) { 108 base::StringAppendF(&list, "%02x -> %d, ", (int) i, package_ids_[i]); 109 } 110 } 111 LOG(INFO) << "Package ID map: " << list; 112 113 for (const auto& package_group: package_groups_) { 114 list = ""; 115 for (const auto& package : package_group.packages_) { 116 base::StringAppendF(&list, "%s(%02x), ", package->GetPackageName().c_str(), package->GetPackageId()); 117 } 118 LOG(INFO) << base::StringPrintf("PG (%02x): ", package_group.dynamic_ref_table.mAssignedPackageId) << list; 119 } 120} 121 122const ResStringPool* AssetManager2::GetStringPoolForCookie(ApkAssetsCookie cookie) const { 123 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) { 124 return nullptr; 125 } 126 return apk_assets_[cookie]->GetLoadedArsc()->GetStringPool(); 127} 128 129const DynamicRefTable* AssetManager2::GetDynamicRefTableForPackage(uint32_t package_id) const { 130 if (package_id >= package_ids_.size()) { 131 return nullptr; 132 } 133 134 const size_t idx = package_ids_[package_id]; 135 if (idx == 0xff) { 136 return nullptr; 137 } 138 return &package_groups_[idx].dynamic_ref_table; 139} 140 141void AssetManager2::SetConfiguration(const ResTable_config& configuration) { 142 const int diff = configuration_.diff(configuration); 143 configuration_ = configuration; 144 145 if (diff) { 146 InvalidateCaches(static_cast<uint32_t>(diff)); 147 } 148} 149 150std::set<ResTable_config> AssetManager2::GetResourceConfigurations(bool exclude_system, 151 bool exclude_mipmap) { 152 ATRACE_CALL(); 153 std::set<ResTable_config> configurations; 154 for (const PackageGroup& package_group : package_groups_) { 155 for (const LoadedPackage* package : package_group.packages_) { 156 if (exclude_system && package->IsSystem()) { 157 continue; 158 } 159 package->CollectConfigurations(exclude_mipmap, &configurations); 160 } 161 } 162 return configurations; 163} 164 165std::set<std::string> AssetManager2::GetResourceLocales(bool exclude_system, 166 bool merge_equivalent_languages) { 167 ATRACE_CALL(); 168 std::set<std::string> locales; 169 for (const PackageGroup& package_group : package_groups_) { 170 for (const LoadedPackage* package : package_group.packages_) { 171 if (exclude_system && package->IsSystem()) { 172 continue; 173 } 174 package->CollectLocales(merge_equivalent_languages, &locales); 175 } 176 } 177 return locales; 178} 179 180std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, Asset::AccessMode mode) { 181 const std::string new_path = "assets/" + filename; 182 return OpenNonAsset(new_path, mode); 183} 184 185std::unique_ptr<Asset> AssetManager2::Open(const std::string& filename, ApkAssetsCookie cookie, 186 Asset::AccessMode mode) { 187 const std::string new_path = "assets/" + filename; 188 return OpenNonAsset(new_path, cookie, mode); 189} 190 191// Search in reverse because that's how we used to do it and we need to preserve behaviour. 192// This is unfortunate, because ClassLoaders delegate to the parent first, so the order 193// is inconsistent for split APKs. 194std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename, 195 Asset::AccessMode mode, 196 ApkAssetsCookie* out_cookie) { 197 ATRACE_CALL(); 198 for (int32_t i = apk_assets_.size() - 1; i >= 0; i--) { 199 std::unique_ptr<Asset> asset = apk_assets_[i]->Open(filename, mode); 200 if (asset) { 201 if (out_cookie != nullptr) { 202 *out_cookie = i; 203 } 204 return asset; 205 } 206 } 207 208 if (out_cookie != nullptr) { 209 *out_cookie = kInvalidCookie; 210 } 211 return {}; 212} 213 214std::unique_ptr<Asset> AssetManager2::OpenNonAsset(const std::string& filename, 215 ApkAssetsCookie cookie, Asset::AccessMode mode) { 216 ATRACE_CALL(); 217 if (cookie < 0 || static_cast<size_t>(cookie) >= apk_assets_.size()) { 218 return {}; 219 } 220 return apk_assets_[cookie]->Open(filename, mode); 221} 222 223ApkAssetsCookie AssetManager2::FindEntry(uint32_t resid, uint16_t density_override, 224 bool stop_at_first_match, LoadedArscEntry* out_entry, 225 ResTable_config* out_selected_config, 226 uint32_t* out_flags) { 227 ATRACE_CALL(); 228 229 // Might use this if density_override != 0. 230 ResTable_config density_override_config; 231 232 // Select our configuration or generate a density override configuration. 233 ResTable_config* desired_config = &configuration_; 234 if (density_override != 0 && density_override != configuration_.density) { 235 density_override_config = configuration_; 236 density_override_config.density = density_override; 237 desired_config = &density_override_config; 238 } 239 240 const uint32_t package_id = get_package_id(resid); 241 const uint8_t type_id = get_type_id(resid); 242 const uint16_t entry_id = get_entry_id(resid); 243 244 if (type_id == 0) { 245 LOG(ERROR) << base::StringPrintf("Invalid ID 0x%08x.", resid); 246 return kInvalidCookie; 247 } 248 249 const uint8_t idx = package_ids_[package_id]; 250 if (idx == 0xff) { 251 LOG(ERROR) << base::StringPrintf("No package ID %02x found for ID 0x%08x.", package_id, resid); 252 return kInvalidCookie; 253 } 254 255 LoadedArscEntry best_entry; 256 ResTable_config best_config; 257 ApkAssetsCookie best_cookie = kInvalidCookie; 258 uint32_t cumulated_flags = 0u; 259 260 const PackageGroup& package_group = package_groups_[idx]; 261 const size_t package_count = package_group.packages_.size(); 262 for (size_t i = 0; i < package_count; i++) { 263 LoadedArscEntry current_entry; 264 ResTable_config current_config; 265 uint32_t current_flags = 0; 266 267 const LoadedPackage* loaded_package = package_group.packages_[i]; 268 if (!loaded_package->FindEntry(type_id - 1, entry_id, *desired_config, ¤t_entry, 269 ¤t_config, ¤t_flags)) { 270 continue; 271 } 272 273 cumulated_flags |= current_flags; 274 275 if (best_cookie == kInvalidCookie || current_config.isBetterThan(best_config, desired_config)) { 276 best_entry = current_entry; 277 best_config = current_config; 278 best_cookie = package_group.cookies_[i]; 279 if (stop_at_first_match) { 280 break; 281 } 282 } 283 } 284 285 if (best_cookie == kInvalidCookie) { 286 return kInvalidCookie; 287 } 288 289 *out_entry = best_entry; 290 out_entry->dynamic_ref_table = &package_group.dynamic_ref_table; 291 *out_selected_config = best_config; 292 *out_flags = cumulated_flags; 293 return best_cookie; 294} 295 296bool AssetManager2::GetResourceName(uint32_t resid, ResourceName* out_name) { 297 ATRACE_CALL(); 298 299 LoadedArscEntry entry; 300 ResTable_config config; 301 uint32_t flags = 0u; 302 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */, 303 true /* stop_at_first_match */, &entry, &config, &flags); 304 if (cookie == kInvalidCookie) { 305 return false; 306 } 307 308 const LoadedPackage* package = apk_assets_[cookie]->GetLoadedArsc()->GetPackageForId(resid); 309 if (package == nullptr) { 310 return false; 311 } 312 313 out_name->package = package->GetPackageName().data(); 314 out_name->package_len = package->GetPackageName().size(); 315 316 out_name->type = entry.type_string_ref.string8(&out_name->type_len); 317 out_name->type16 = nullptr; 318 if (out_name->type == nullptr) { 319 out_name->type16 = entry.type_string_ref.string16(&out_name->type_len); 320 if (out_name->type16 == nullptr) { 321 return false; 322 } 323 } 324 325 out_name->entry = entry.entry_string_ref.string8(&out_name->entry_len); 326 out_name->entry16 = nullptr; 327 if (out_name->entry == nullptr) { 328 out_name->entry16 = entry.entry_string_ref.string16(&out_name->entry_len); 329 if (out_name->entry16 == nullptr) { 330 return false; 331 } 332 } 333 return true; 334} 335 336bool AssetManager2::GetResourceFlags(uint32_t resid, uint32_t* out_flags) { 337 LoadedArscEntry entry; 338 ResTable_config config; 339 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */, 340 false /* stop_at_first_match */, &entry, &config, out_flags); 341 return cookie != kInvalidCookie; 342} 343 344ApkAssetsCookie AssetManager2::GetResource(uint32_t resid, bool may_be_bag, 345 uint16_t density_override, Res_value* out_value, 346 ResTable_config* out_selected_config, 347 uint32_t* out_flags) { 348 ATRACE_CALL(); 349 350 LoadedArscEntry entry; 351 ResTable_config config; 352 uint32_t flags = 0u; 353 ApkAssetsCookie cookie = 354 FindEntry(resid, density_override, false /* stop_at_first_match */, &entry, &config, &flags); 355 if (cookie == kInvalidCookie) { 356 return kInvalidCookie; 357 } 358 359 if (dtohl(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) { 360 if (!may_be_bag) { 361 LOG(ERROR) << base::StringPrintf("Resource %08x is a complex map type.", resid); 362 return kInvalidCookie; 363 } 364 365 // Create a reference since we can't represent this complex type as a Res_value. 366 out_value->dataType = Res_value::TYPE_REFERENCE; 367 out_value->data = resid; 368 *out_selected_config = config; 369 *out_flags = flags; 370 return cookie; 371 } 372 373 const Res_value* device_value = reinterpret_cast<const Res_value*>( 374 reinterpret_cast<const uint8_t*>(entry.entry) + dtohs(entry.entry->size)); 375 out_value->copyFrom_dtoh(*device_value); 376 377 // Convert the package ID to the runtime assigned package ID. 378 entry.dynamic_ref_table->lookupResourceValue(out_value); 379 380 *out_selected_config = config; 381 *out_flags = flags; 382 return cookie; 383} 384 385ApkAssetsCookie AssetManager2::ResolveReference(ApkAssetsCookie cookie, Res_value* in_out_value, 386 ResTable_config* in_out_selected_config, 387 uint32_t* in_out_flags, 388 ResTable_ref* out_last_reference) { 389 ATRACE_CALL(); 390 constexpr const int kMaxIterations = 20; 391 392 out_last_reference->ident = 0u; 393 for (size_t iteration = 0u; in_out_value->dataType == Res_value::TYPE_REFERENCE && 394 in_out_value->data != 0u && iteration < kMaxIterations; 395 iteration++) { 396 if (out_last_reference != nullptr) { 397 out_last_reference->ident = in_out_value->data; 398 } 399 uint32_t new_flags = 0u; 400 cookie = GetResource(in_out_value->data, true /*may_be_bag*/, 0u /*density_override*/, 401 in_out_value, in_out_selected_config, &new_flags); 402 if (cookie == kInvalidCookie) { 403 return kInvalidCookie; 404 } 405 if (in_out_flags != nullptr) { 406 *in_out_flags |= new_flags; 407 } 408 if (out_last_reference->ident == in_out_value->data) { 409 // This reference can't be resolved, so exit now and let the caller deal with it. 410 return cookie; 411 } 412 } 413 return cookie; 414} 415 416const ResolvedBag* AssetManager2::GetBag(uint32_t resid) { 417 ATRACE_CALL(); 418 419 auto cached_iter = cached_bags_.find(resid); 420 if (cached_iter != cached_bags_.end()) { 421 return cached_iter->second.get(); 422 } 423 424 LoadedArscEntry entry; 425 ResTable_config config; 426 uint32_t flags = 0u; 427 ApkAssetsCookie cookie = FindEntry(resid, 0u /* density_override */, 428 false /* stop_at_first_match */, &entry, &config, &flags); 429 if (cookie == kInvalidCookie) { 430 return nullptr; 431 } 432 433 // Check that the size of the entry header is at least as big as 434 // the desired ResTable_map_entry. Also verify that the entry 435 // was intended to be a map. 436 if (dtohs(entry.entry->size) < sizeof(ResTable_map_entry) || 437 (dtohs(entry.entry->flags) & ResTable_entry::FLAG_COMPLEX) == 0) { 438 // Not a bag, nothing to do. 439 return nullptr; 440 } 441 442 const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry.entry); 443 const ResTable_map* map_entry = 444 reinterpret_cast<const ResTable_map*>(reinterpret_cast<const uint8_t*>(map) + map->size); 445 const ResTable_map* const map_entry_end = map_entry + dtohl(map->count); 446 447 uint32_t parent_resid = dtohl(map->parent.ident); 448 if (parent_resid == 0) { 449 // There is no parent, meaning there is nothing to inherit and we can do a simple 450 // copy of the entries in the map. 451 const size_t entry_count = map_entry_end - map_entry; 452 util::unique_cptr<ResolvedBag> new_bag{reinterpret_cast<ResolvedBag*>( 453 malloc(sizeof(ResolvedBag) + (entry_count * sizeof(ResolvedBag::Entry))))}; 454 ResolvedBag::Entry* new_entry = new_bag->entries; 455 for (; map_entry != map_entry_end; ++map_entry) { 456 uint32_t new_key = dtohl(map_entry->name.ident); 457 if (!is_internal_resid(new_key)) { 458 // Attributes, arrays, etc don't have a resource id as the name. They specify 459 // other data, which would be wrong to change via a lookup. 460 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) { 461 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key, resid); 462 return nullptr; 463 } 464 } 465 new_entry->cookie = cookie; 466 new_entry->value.copyFrom_dtoh(map_entry->value); 467 new_entry->key = new_key; 468 new_entry->key_pool = nullptr; 469 new_entry->type_pool = nullptr; 470 ++new_entry; 471 } 472 new_bag->type_spec_flags = flags; 473 new_bag->entry_count = static_cast<uint32_t>(entry_count); 474 ResolvedBag* result = new_bag.get(); 475 cached_bags_[resid] = std::move(new_bag); 476 return result; 477 } 478 479 // In case the parent is a dynamic reference, resolve it. 480 entry.dynamic_ref_table->lookupResourceId(&parent_resid); 481 482 // Get the parent and do a merge of the keys. 483 const ResolvedBag* parent_bag = GetBag(parent_resid); 484 if (parent_bag == nullptr) { 485 // Failed to get the parent that should exist. 486 LOG(ERROR) << base::StringPrintf("Failed to find parent 0x%08x of bag 0x%08x.", parent_resid, resid); 487 return nullptr; 488 } 489 490 // Combine flags from the parent and our own bag. 491 flags |= parent_bag->type_spec_flags; 492 493 // Create the max possible entries we can make. Once we construct the bag, 494 // we will realloc to fit to size. 495 const size_t max_count = parent_bag->entry_count + dtohl(map->count); 496 ResolvedBag* new_bag = reinterpret_cast<ResolvedBag*>( 497 malloc(sizeof(ResolvedBag) + (max_count * sizeof(ResolvedBag::Entry)))); 498 ResolvedBag::Entry* new_entry = new_bag->entries; 499 500 const ResolvedBag::Entry* parent_entry = parent_bag->entries; 501 const ResolvedBag::Entry* const parent_entry_end = parent_entry + parent_bag->entry_count; 502 503 // The keys are expected to be in sorted order. Merge the two bags. 504 while (map_entry != map_entry_end && parent_entry != parent_entry_end) { 505 uint32_t child_key = dtohl(map_entry->name.ident); 506 if (!is_internal_resid(child_key)) { 507 if (entry.dynamic_ref_table->lookupResourceId(&child_key) != NO_ERROR) { 508 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", child_key, resid); 509 return nullptr; 510 } 511 } 512 513 if (child_key <= parent_entry->key) { 514 // Use the child key if it comes before the parent 515 // or is equal to the parent (overrides). 516 new_entry->cookie = cookie; 517 new_entry->value.copyFrom_dtoh(map_entry->value); 518 new_entry->key = child_key; 519 new_entry->key_pool = nullptr; 520 new_entry->type_pool = nullptr; 521 ++map_entry; 522 } else { 523 // Take the parent entry as-is. 524 memcpy(new_entry, parent_entry, sizeof(*new_entry)); 525 } 526 527 if (child_key >= parent_entry->key) { 528 // Move to the next parent entry if we used it or it was overridden. 529 ++parent_entry; 530 } 531 // Increment to the next entry to fill. 532 ++new_entry; 533 } 534 535 // Finish the child entries if they exist. 536 while (map_entry != map_entry_end) { 537 uint32_t new_key = dtohl(map_entry->name.ident); 538 if (!is_internal_resid(new_key)) { 539 if (entry.dynamic_ref_table->lookupResourceId(&new_key) != NO_ERROR) { 540 LOG(ERROR) << base::StringPrintf("Failed to resolve key 0x%08x in bag 0x%08x.", new_key, resid); 541 return nullptr; 542 } 543 } 544 new_entry->cookie = cookie; 545 new_entry->value.copyFrom_dtoh(map_entry->value); 546 new_entry->key = new_key; 547 new_entry->key_pool = nullptr; 548 new_entry->type_pool = nullptr; 549 ++map_entry; 550 ++new_entry; 551 } 552 553 // Finish the parent entries if they exist. 554 if (parent_entry != parent_entry_end) { 555 // Take the rest of the parent entries as-is. 556 const size_t num_entries_to_copy = parent_entry_end - parent_entry; 557 memcpy(new_entry, parent_entry, num_entries_to_copy * sizeof(*new_entry)); 558 new_entry += num_entries_to_copy; 559 } 560 561 // Resize the resulting array to fit. 562 const size_t actual_count = new_entry - new_bag->entries; 563 if (actual_count != max_count) { 564 new_bag = reinterpret_cast<ResolvedBag*>( 565 realloc(new_bag, sizeof(ResolvedBag) + (actual_count * sizeof(ResolvedBag::Entry)))); 566 } 567 568 util::unique_cptr<ResolvedBag> final_bag{new_bag}; 569 final_bag->type_spec_flags = flags; 570 final_bag->entry_count = static_cast<uint32_t>(actual_count); 571 ResolvedBag* result = final_bag.get(); 572 cached_bags_[resid] = std::move(final_bag); 573 return result; 574} 575 576static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) { 577 ssize_t len = 578 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false); 579 if (len < 0) { 580 return false; 581 } 582 out->resize(static_cast<size_t>(len)); 583 utf8_to_utf16(reinterpret_cast<const uint8_t*>(str.data()), str.size(), &*out->begin(), 584 static_cast<size_t>(len + 1)); 585 return true; 586} 587 588uint32_t AssetManager2::GetResourceId(const std::string& resource_name, 589 const std::string& fallback_type, 590 const std::string& fallback_package) { 591 StringPiece package_name, type, entry; 592 if (!ExtractResourceName(resource_name, &package_name, &type, &entry)) { 593 return 0u; 594 } 595 596 if (entry.empty()) { 597 return 0u; 598 } 599 600 if (package_name.empty()) { 601 package_name = fallback_package; 602 } 603 604 if (type.empty()) { 605 type = fallback_type; 606 } 607 608 std::u16string type16; 609 if (!Utf8ToUtf16(type, &type16)) { 610 return 0u; 611 } 612 613 std::u16string entry16; 614 if (!Utf8ToUtf16(entry, &entry16)) { 615 return 0u; 616 } 617 618 const StringPiece16 kAttr16 = u"attr"; 619 const static std::u16string kAttrPrivate16 = u"^attr-private"; 620 621 for (const PackageGroup& package_group : package_groups_) { 622 for (const LoadedPackage* package : package_group.packages_) { 623 if (package_name != package->GetPackageName()) { 624 // All packages in the same group are expected to have the same package name. 625 break; 626 } 627 628 uint32_t resid = package->FindEntryByName(type16, entry16); 629 if (resid == 0u && kAttr16 == type16) { 630 // Private attributes in libraries (such as the framework) are sometimes encoded 631 // under the type '^attr-private' in order to leave the ID space of public 'attr' 632 // free for future additions. Check '^attr-private' for the same name. 633 resid = package->FindEntryByName(kAttrPrivate16, entry16); 634 } 635 636 if (resid != 0u) { 637 return fix_package_id(resid, package_group.dynamic_ref_table.mAssignedPackageId); 638 } 639 } 640 } 641 return 0u; 642} 643 644void AssetManager2::InvalidateCaches(uint32_t diff) { 645 if (diff == 0xffffffffu) { 646 // Everything must go. 647 cached_bags_.clear(); 648 return; 649 } 650 651 // Be more conservative with what gets purged. Only if the bag has other possible 652 // variations with respect to what changed (diff) should we remove it. 653 for (auto iter = cached_bags_.cbegin(); iter != cached_bags_.cend();) { 654 if (diff & iter->second->type_spec_flags) { 655 iter = cached_bags_.erase(iter); 656 } else { 657 ++iter; 658 } 659 } 660} 661 662std::unique_ptr<Theme> AssetManager2::NewTheme() { return std::unique_ptr<Theme>(new Theme(this)); } 663 664bool Theme::ApplyStyle(uint32_t resid, bool force) { 665 ATRACE_CALL(); 666 667 const ResolvedBag* bag = asset_manager_->GetBag(resid); 668 if (bag == nullptr) { 669 return false; 670 } 671 672 // Merge the flags from this style. 673 type_spec_flags_ |= bag->type_spec_flags; 674 675 // On the first iteration, verify the attribute IDs and 676 // update the entry count in each type. 677 const auto bag_iter_end = end(bag); 678 for (auto bag_iter = begin(bag); bag_iter != bag_iter_end; ++bag_iter) { 679 const uint32_t attr_resid = bag_iter->key; 680 681 // If the resource ID passed in is not a style, the key can be 682 // some other identifier that is not a resource ID. 683 if (!is_valid_resid(attr_resid)) { 684 return false; 685 } 686 687 const uint32_t package_idx = get_package_id(attr_resid); 688 689 // The type ID is 1-based, so subtract 1 to get an index. 690 const uint32_t type_idx = get_type_id(attr_resid) - 1; 691 const uint32_t entry_idx = get_entry_id(attr_resid); 692 693 std::unique_ptr<Package>& package = packages_[package_idx]; 694 if (package == nullptr) { 695 package.reset(new Package()); 696 } 697 698 util::unique_cptr<Type>& type = package->types[type_idx]; 699 if (type == nullptr) { 700 // Set the initial capacity to take up a total amount of 1024 bytes. 701 constexpr uint32_t kInitialCapacity = (1024u - sizeof(Type)) / sizeof(Entry); 702 const uint32_t initial_capacity = std::max(entry_idx, kInitialCapacity); 703 type.reset( 704 reinterpret_cast<Type*>(calloc(sizeof(Type) + (initial_capacity * sizeof(Entry)), 1))); 705 type->entry_capacity = initial_capacity; 706 } 707 708 // Set the entry_count to include this entry. We will populate 709 // and resize the array as necessary in the next pass. 710 if (entry_idx + 1 > type->entry_count) { 711 // Increase the entry count to include this. 712 type->entry_count = entry_idx + 1; 713 } 714 } 715 716 // On the second pass, we will realloc to fit the entry counts 717 // and populate the structures. 718 for (auto bag_iter = begin(bag); bag_iter != bag_iter_end; ++bag_iter) { 719 const uint32_t attr_resid = bag_iter->key; 720 const uint32_t package_idx = get_package_id(attr_resid); 721 const uint32_t type_idx = get_type_id(attr_resid) - 1; 722 const uint32_t entry_idx = get_entry_id(attr_resid); 723 Package* package = packages_[package_idx].get(); 724 util::unique_cptr<Type>& type = package->types[type_idx]; 725 if (type->entry_count != type->entry_capacity) { 726 // Resize to fit the actual entries that will be included. 727 Type* type_ptr = type.release(); 728 type.reset(reinterpret_cast<Type*>( 729 realloc(type_ptr, sizeof(Type) + (type_ptr->entry_count * sizeof(Entry))))); 730 if (type->entry_capacity < type->entry_count) { 731 // Clear the newly allocated memory (which does not get zero initialized). 732 // We need to do this because we |= type_spec_flags. 733 memset(type->entries + type->entry_capacity, 0, 734 sizeof(Entry) * (type->entry_count - type->entry_capacity)); 735 } 736 type->entry_capacity = type->entry_count; 737 } 738 Entry& entry = type->entries[entry_idx]; 739 if (force || entry.value.dataType == Res_value::TYPE_NULL) { 740 entry.cookie = bag_iter->cookie; 741 entry.type_spec_flags |= bag->type_spec_flags; 742 entry.value = bag_iter->value; 743 } 744 } 745 return true; 746} 747 748ApkAssetsCookie Theme::GetAttribute(uint32_t resid, Res_value* out_value, 749 uint32_t* out_flags) const { 750 constexpr const int kMaxIterations = 20; 751 752 uint32_t type_spec_flags = 0u; 753 754 for (int iterations_left = kMaxIterations; iterations_left > 0; iterations_left--) { 755 if (!is_valid_resid(resid)) { 756 return kInvalidCookie; 757 } 758 759 const uint32_t package_idx = get_package_id(resid); 760 761 // Type ID is 1-based, subtract 1 to get the index. 762 const uint32_t type_idx = get_type_id(resid) - 1; 763 const uint32_t entry_idx = get_entry_id(resid); 764 765 const Package* package = packages_[package_idx].get(); 766 if (package == nullptr) { 767 return kInvalidCookie; 768 } 769 770 const Type* type = package->types[type_idx].get(); 771 if (type == nullptr) { 772 return kInvalidCookie; 773 } 774 775 if (entry_idx >= type->entry_count) { 776 return kInvalidCookie; 777 } 778 779 const Entry& entry = type->entries[entry_idx]; 780 type_spec_flags |= entry.type_spec_flags; 781 782 switch (entry.value.dataType) { 783 case Res_value::TYPE_NULL: 784 return kInvalidCookie; 785 786 case Res_value::TYPE_ATTRIBUTE: 787 resid = entry.value.data; 788 break; 789 790 case Res_value::TYPE_DYNAMIC_ATTRIBUTE: { 791 // Resolve the dynamic attribute to a normal attribute 792 // (with the right package ID). 793 resid = entry.value.data; 794 const DynamicRefTable* ref_table = 795 asset_manager_->GetDynamicRefTableForPackage(package_idx); 796 if (ref_table == nullptr || ref_table->lookupResourceId(&resid) != NO_ERROR) { 797 LOG(ERROR) << base::StringPrintf("Failed to resolve dynamic attribute 0x%08x", resid); 798 return kInvalidCookie; 799 } 800 } break; 801 802 case Res_value::TYPE_DYNAMIC_REFERENCE: { 803 // Resolve the dynamic reference to a normal reference 804 // (with the right package ID). 805 out_value->dataType = Res_value::TYPE_REFERENCE; 806 out_value->data = entry.value.data; 807 const DynamicRefTable* ref_table = 808 asset_manager_->GetDynamicRefTableForPackage(package_idx); 809 if (ref_table == nullptr || ref_table->lookupResourceId(&out_value->data) != NO_ERROR) { 810 LOG(ERROR) << base::StringPrintf("Failed to resolve dynamic reference 0x%08x", 811 out_value->data); 812 return kInvalidCookie; 813 } 814 815 if (out_flags != nullptr) { 816 *out_flags = type_spec_flags; 817 } 818 return entry.cookie; 819 } 820 821 default: 822 *out_value = entry.value; 823 if (out_flags != nullptr) { 824 *out_flags = type_spec_flags; 825 } 826 return entry.cookie; 827 } 828 } 829 830 LOG(WARNING) << base::StringPrintf("Too many (%d) attribute references, stopped at: 0x%08x", 831 kMaxIterations, resid); 832 return kInvalidCookie; 833} 834 835void Theme::Clear() { 836 type_spec_flags_ = 0u; 837 for (std::unique_ptr<Package>& package : packages_) { 838 package.reset(); 839 } 840} 841 842bool Theme::SetTo(const Theme& o) { 843 if (this == &o) { 844 return true; 845 } 846 847 if (asset_manager_ != o.asset_manager_) { 848 return false; 849 } 850 851 type_spec_flags_ = o.type_spec_flags_; 852 853 for (size_t p = 0; p < packages_.size(); p++) { 854 const Package* package = o.packages_[p].get(); 855 if (package == nullptr) { 856 packages_[p].reset(); 857 continue; 858 } 859 860 for (size_t t = 0; t < package->types.size(); t++) { 861 const Type* type = package->types[t].get(); 862 if (type == nullptr) { 863 packages_[p]->types[t].reset(); 864 continue; 865 } 866 867 const size_t type_alloc_size = sizeof(Type) + (type->entry_capacity * sizeof(Entry)); 868 void* copied_data = malloc(type_alloc_size); 869 memcpy(copied_data, type, type_alloc_size); 870 packages_[p]->types[t].reset(reinterpret_cast<Type*>(copied_data)); 871 } 872 } 873 return true; 874} 875 876} // namespace android 877