1 /* 2 * Copyright (C) 2015 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 #include "flatten/TableFlattener.h" 18 19 #include <algorithm> 20 #include <numeric> 21 #include <sstream> 22 #include <type_traits> 23 24 #include "android-base/logging.h" 25 #include "android-base/macros.h" 26 27 #include "ResourceTable.h" 28 #include "ResourceValues.h" 29 #include "SdkConstants.h" 30 #include "ValueVisitor.h" 31 #include "flatten/ChunkWriter.h" 32 #include "flatten/ResourceTypeExtensions.h" 33 #include "util/BigBuffer.h" 34 35 using namespace android; 36 37 namespace aapt { 38 39 namespace { 40 41 template <typename T> 42 static bool cmp_ids(const T* a, const T* b) { 43 return a->id.value() < b->id.value(); 44 } 45 46 static void strcpy16_htod(uint16_t* dst, size_t len, const StringPiece16& src) { 47 if (len == 0) { 48 return; 49 } 50 51 size_t i; 52 const char16_t* src_data = src.data(); 53 for (i = 0; i < len - 1 && i < src.size(); i++) { 54 dst[i] = util::HostToDevice16((uint16_t)src_data[i]); 55 } 56 dst[i] = 0; 57 } 58 59 static bool cmp_style_entries(const Style::Entry& a, const Style::Entry& b) { 60 if (a.key.id) { 61 if (b.key.id) { 62 return a.key.id.value() < b.key.id.value(); 63 } 64 return true; 65 } else if (!b.key.id) { 66 return a.key.name.value() < b.key.name.value(); 67 } 68 return false; 69 } 70 71 struct FlatEntry { 72 ResourceEntry* entry; 73 Value* value; 74 75 // The entry string pool index to the entry's name. 76 uint32_t entry_key; 77 }; 78 79 class MapFlattenVisitor : public RawValueVisitor { 80 public: 81 using RawValueVisitor::Visit; 82 83 MapFlattenVisitor(ResTable_entry_ext* out_entry, BigBuffer* buffer) 84 : out_entry_(out_entry), buffer_(buffer) {} 85 86 void Visit(Attribute* attr) override { 87 { 88 Reference key = Reference(ResourceId(ResTable_map::ATTR_TYPE)); 89 BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->type_mask); 90 FlattenEntry(&key, &val); 91 } 92 93 if (attr->min_int != std::numeric_limits<int32_t>::min()) { 94 Reference key = Reference(ResourceId(ResTable_map::ATTR_MIN)); 95 BinaryPrimitive val(Res_value::TYPE_INT_DEC, 96 static_cast<uint32_t>(attr->min_int)); 97 FlattenEntry(&key, &val); 98 } 99 100 if (attr->max_int != std::numeric_limits<int32_t>::max()) { 101 Reference key = Reference(ResourceId(ResTable_map::ATTR_MAX)); 102 BinaryPrimitive val(Res_value::TYPE_INT_DEC, 103 static_cast<uint32_t>(attr->max_int)); 104 FlattenEntry(&key, &val); 105 } 106 107 for (Attribute::Symbol& s : attr->symbols) { 108 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value); 109 FlattenEntry(&s.symbol, &val); 110 } 111 } 112 113 void Visit(Style* style) override { 114 if (style->parent) { 115 const Reference& parent_ref = style->parent.value(); 116 CHECK(bool(parent_ref.id)) << "parent has no ID"; 117 out_entry_->parent.ident = util::HostToDevice32(parent_ref.id.value().id); 118 } 119 120 // Sort the style. 121 std::sort(style->entries.begin(), style->entries.end(), cmp_style_entries); 122 123 for (Style::Entry& entry : style->entries) { 124 FlattenEntry(&entry.key, entry.value.get()); 125 } 126 } 127 128 void Visit(Styleable* styleable) override { 129 for (auto& attr_ref : styleable->entries) { 130 BinaryPrimitive val(Res_value{}); 131 FlattenEntry(&attr_ref, &val); 132 } 133 } 134 135 void Visit(Array* array) override { 136 for (auto& item : array->elements) { 137 ResTable_map* out_entry = buffer_->NextBlock<ResTable_map>(); 138 FlattenValue(item.get(), out_entry); 139 out_entry->value.size = util::HostToDevice16(sizeof(out_entry->value)); 140 entry_count_++; 141 } 142 } 143 144 void Visit(Plural* plural) override { 145 const size_t count = plural->values.size(); 146 for (size_t i = 0; i < count; i++) { 147 if (!plural->values[i]) { 148 continue; 149 } 150 151 ResourceId q; 152 switch (i) { 153 case Plural::Zero: 154 q.id = android::ResTable_map::ATTR_ZERO; 155 break; 156 157 case Plural::One: 158 q.id = android::ResTable_map::ATTR_ONE; 159 break; 160 161 case Plural::Two: 162 q.id = android::ResTable_map::ATTR_TWO; 163 break; 164 165 case Plural::Few: 166 q.id = android::ResTable_map::ATTR_FEW; 167 break; 168 169 case Plural::Many: 170 q.id = android::ResTable_map::ATTR_MANY; 171 break; 172 173 case Plural::Other: 174 q.id = android::ResTable_map::ATTR_OTHER; 175 break; 176 177 default: 178 LOG(FATAL) << "unhandled plural type"; 179 break; 180 } 181 182 Reference key(q); 183 FlattenEntry(&key, plural->values[i].get()); 184 } 185 } 186 187 /** 188 * Call this after visiting a Value. This will finish any work that 189 * needs to be done to prepare the entry. 190 */ 191 void Finish() { out_entry_->count = util::HostToDevice32(entry_count_); } 192 193 private: 194 DISALLOW_COPY_AND_ASSIGN(MapFlattenVisitor); 195 196 void FlattenKey(Reference* key, ResTable_map* out_entry) { 197 CHECK(bool(key->id)) << "key has no ID"; 198 out_entry->name.ident = util::HostToDevice32(key->id.value().id); 199 } 200 201 void FlattenValue(Item* value, ResTable_map* out_entry) { 202 CHECK(value->Flatten(&out_entry->value)) << "flatten failed"; 203 } 204 205 void FlattenEntry(Reference* key, Item* value) { 206 ResTable_map* out_entry = buffer_->NextBlock<ResTable_map>(); 207 FlattenKey(key, out_entry); 208 FlattenValue(value, out_entry); 209 out_entry->value.size = util::HostToDevice16(sizeof(out_entry->value)); 210 entry_count_++; 211 } 212 213 ResTable_entry_ext* out_entry_; 214 BigBuffer* buffer_; 215 size_t entry_count_ = 0; 216 }; 217 218 class PackageFlattener { 219 public: 220 PackageFlattener(IAaptContext* context, ResourceTablePackage* package, 221 const std::map<size_t, std::string>* shared_libs, bool use_sparse_entries) 222 : context_(context), 223 diag_(context->GetDiagnostics()), 224 package_(package), 225 shared_libs_(shared_libs), 226 use_sparse_entries_(use_sparse_entries) {} 227 228 bool FlattenPackage(BigBuffer* buffer) { 229 ChunkWriter pkg_writer(buffer); 230 ResTable_package* pkg_header = pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE); 231 pkg_header->id = util::HostToDevice32(package_->id.value()); 232 233 // AAPT truncated the package name, so do the same. 234 // Shared libraries require full package names, so don't truncate theirs. 235 if (context_->GetPackageType() != PackageType::kApp && 236 package_->name.size() >= arraysize(pkg_header->name)) { 237 diag_->Error(DiagMessage() << "package name '" << package_->name 238 << "' is too long. " 239 "Shared libraries cannot have truncated package names"); 240 return false; 241 } 242 243 // Copy the package name in device endianness. 244 strcpy16_htod(pkg_header->name, arraysize(pkg_header->name), util::Utf8ToUtf16(package_->name)); 245 246 // Serialize the types. We do this now so that our type and key strings 247 // are populated. We write those first. 248 BigBuffer type_buffer(1024); 249 FlattenTypes(&type_buffer); 250 251 pkg_header->typeStrings = util::HostToDevice32(pkg_writer.size()); 252 StringPool::FlattenUtf16(pkg_writer.buffer(), type_pool_); 253 254 pkg_header->keyStrings = util::HostToDevice32(pkg_writer.size()); 255 StringPool::FlattenUtf8(pkg_writer.buffer(), key_pool_); 256 257 // Append the types. 258 buffer->AppendBuffer(std::move(type_buffer)); 259 260 // If there are libraries (or if the package ID is 0x00), encode a library chunk. 261 if (package_->id.value() == 0x00 || !shared_libs_->empty()) { 262 FlattenLibrarySpec(buffer); 263 } 264 265 pkg_writer.Finish(); 266 return true; 267 } 268 269 private: 270 DISALLOW_COPY_AND_ASSIGN(PackageFlattener); 271 272 template <typename T, bool IsItem> 273 T* WriteEntry(FlatEntry* entry, BigBuffer* buffer) { 274 static_assert(std::is_same<ResTable_entry, T>::value || 275 std::is_same<ResTable_entry_ext, T>::value, 276 "T must be ResTable_entry or ResTable_entry_ext"); 277 278 T* result = buffer->NextBlock<T>(); 279 ResTable_entry* out_entry = (ResTable_entry*)result; 280 if (entry->entry->symbol_status.state == SymbolState::kPublic) { 281 out_entry->flags |= ResTable_entry::FLAG_PUBLIC; 282 } 283 284 if (entry->value->IsWeak()) { 285 out_entry->flags |= ResTable_entry::FLAG_WEAK; 286 } 287 288 if (!IsItem) { 289 out_entry->flags |= ResTable_entry::FLAG_COMPLEX; 290 } 291 292 out_entry->flags = util::HostToDevice16(out_entry->flags); 293 out_entry->key.index = util::HostToDevice32(entry->entry_key); 294 out_entry->size = util::HostToDevice16(sizeof(T)); 295 return result; 296 } 297 298 bool FlattenValue(FlatEntry* entry, BigBuffer* buffer) { 299 if (Item* item = ValueCast<Item>(entry->value)) { 300 WriteEntry<ResTable_entry, true>(entry, buffer); 301 Res_value* outValue = buffer->NextBlock<Res_value>(); 302 CHECK(item->Flatten(outValue)) << "flatten failed"; 303 outValue->size = util::HostToDevice16(sizeof(*outValue)); 304 } else { 305 ResTable_entry_ext* out_entry = 306 WriteEntry<ResTable_entry_ext, false>(entry, buffer); 307 MapFlattenVisitor visitor(out_entry, buffer); 308 entry->value->Accept(&visitor); 309 visitor.Finish(); 310 } 311 return true; 312 } 313 314 bool FlattenConfig(const ResourceTableType* type, const ConfigDescription& config, 315 const size_t num_total_entries, std::vector<FlatEntry>* entries, 316 BigBuffer* buffer) { 317 CHECK(num_total_entries != 0); 318 CHECK(num_total_entries <= std::numeric_limits<uint16_t>::max()); 319 320 ChunkWriter type_writer(buffer); 321 ResTable_type* type_header = 322 type_writer.StartChunk<ResTable_type>(RES_TABLE_TYPE_TYPE); 323 type_header->id = type->id.value(); 324 type_header->config = config; 325 type_header->config.swapHtoD(); 326 327 std::vector<uint32_t> offsets; 328 offsets.resize(num_total_entries, 0xffffffffu); 329 330 BigBuffer values_buffer(512); 331 for (FlatEntry& flat_entry : *entries) { 332 CHECK(static_cast<size_t>(flat_entry.entry->id.value()) < num_total_entries); 333 offsets[flat_entry.entry->id.value()] = values_buffer.size(); 334 if (!FlattenValue(&flat_entry, &values_buffer)) { 335 diag_->Error(DiagMessage() 336 << "failed to flatten resource '" 337 << ResourceNameRef(package_->name, type->type, flat_entry.entry->name) 338 << "' for configuration '" << config << "'"); 339 return false; 340 } 341 } 342 343 bool sparse_encode = use_sparse_entries_; 344 345 // Only sparse encode if the entries will be read on platforms O+. 346 sparse_encode = 347 sparse_encode && (context_->GetMinSdkVersion() >= SDK_O || config.sdkVersion >= SDK_O); 348 349 // Only sparse encode if the offsets are representable in 2 bytes. 350 sparse_encode = 351 sparse_encode && (values_buffer.size() / 4u) <= std::numeric_limits<uint16_t>::max(); 352 353 // Only sparse encode if the ratio of populated entries to total entries is below some 354 // threshold. 355 sparse_encode = 356 sparse_encode && ((100 * entries->size()) / num_total_entries) < kSparseEncodingThreshold; 357 358 if (sparse_encode) { 359 type_header->entryCount = util::HostToDevice32(entries->size()); 360 type_header->flags |= ResTable_type::FLAG_SPARSE; 361 ResTable_sparseTypeEntry* indices = 362 type_writer.NextBlock<ResTable_sparseTypeEntry>(entries->size()); 363 for (size_t i = 0; i < num_total_entries; i++) { 364 if (offsets[i] != ResTable_type::NO_ENTRY) { 365 CHECK((offsets[i] & 0x03) == 0); 366 indices->idx = util::HostToDevice16(i); 367 indices->offset = util::HostToDevice16(offsets[i] / 4u); 368 indices++; 369 } 370 } 371 } else { 372 type_header->entryCount = util::HostToDevice32(num_total_entries); 373 uint32_t* indices = type_writer.NextBlock<uint32_t>(num_total_entries); 374 for (size_t i = 0; i < num_total_entries; i++) { 375 indices[i] = util::HostToDevice32(offsets[i]); 376 } 377 } 378 379 type_header->entriesStart = util::HostToDevice32(type_writer.size()); 380 type_writer.buffer()->AppendBuffer(std::move(values_buffer)); 381 type_writer.Finish(); 382 return true; 383 } 384 385 std::vector<ResourceTableType*> CollectAndSortTypes() { 386 std::vector<ResourceTableType*> sorted_types; 387 for (auto& type : package_->types) { 388 if (type->type == ResourceType::kStyleable) { 389 // Styleables aren't real Resource Types, they are represented in the 390 // R.java file. 391 continue; 392 } 393 394 CHECK(bool(type->id)) << "type must have an ID set"; 395 396 sorted_types.push_back(type.get()); 397 } 398 std::sort(sorted_types.begin(), sorted_types.end(), 399 cmp_ids<ResourceTableType>); 400 return sorted_types; 401 } 402 403 std::vector<ResourceEntry*> CollectAndSortEntries(ResourceTableType* type) { 404 // Sort the entries by entry ID. 405 std::vector<ResourceEntry*> sorted_entries; 406 for (auto& entry : type->entries) { 407 CHECK(bool(entry->id)) << "entry must have an ID set"; 408 sorted_entries.push_back(entry.get()); 409 } 410 std::sort(sorted_entries.begin(), sorted_entries.end(), cmp_ids<ResourceEntry>); 411 return sorted_entries; 412 } 413 414 bool FlattenTypeSpec(ResourceTableType* type, 415 std::vector<ResourceEntry*>* sorted_entries, 416 BigBuffer* buffer) { 417 ChunkWriter type_spec_writer(buffer); 418 ResTable_typeSpec* spec_header = 419 type_spec_writer.StartChunk<ResTable_typeSpec>( 420 RES_TABLE_TYPE_SPEC_TYPE); 421 spec_header->id = type->id.value(); 422 423 if (sorted_entries->empty()) { 424 type_spec_writer.Finish(); 425 return true; 426 } 427 428 // We can't just take the size of the vector. There may be holes in the 429 // entry ID space. 430 // Since the entries are sorted by ID, the last one will be the biggest. 431 const size_t num_entries = sorted_entries->back()->id.value() + 1; 432 433 spec_header->entryCount = util::HostToDevice32(num_entries); 434 435 // Reserve space for the masks of each resource in this type. These 436 // show for which configuration axis the resource changes. 437 uint32_t* config_masks = type_spec_writer.NextBlock<uint32_t>(num_entries); 438 439 const size_t actual_num_entries = sorted_entries->size(); 440 for (size_t entryIndex = 0; entryIndex < actual_num_entries; entryIndex++) { 441 ResourceEntry* entry = sorted_entries->at(entryIndex); 442 443 // Populate the config masks for this entry. 444 445 if (entry->symbol_status.state == SymbolState::kPublic) { 446 config_masks[entry->id.value()] |= 447 util::HostToDevice32(ResTable_typeSpec::SPEC_PUBLIC); 448 } 449 450 const size_t config_count = entry->values.size(); 451 for (size_t i = 0; i < config_count; i++) { 452 const ConfigDescription& config = entry->values[i]->config; 453 for (size_t j = i + 1; j < config_count; j++) { 454 config_masks[entry->id.value()] |= 455 util::HostToDevice32(config.diff(entry->values[j]->config)); 456 } 457 } 458 } 459 type_spec_writer.Finish(); 460 return true; 461 } 462 463 bool FlattenTypes(BigBuffer* buffer) { 464 // Sort the types by their IDs. They will be inserted into the StringPool in 465 // this order. 466 std::vector<ResourceTableType*> sorted_types = CollectAndSortTypes(); 467 468 size_t expected_type_id = 1; 469 for (ResourceTableType* type : sorted_types) { 470 // If there is a gap in the type IDs, fill in the StringPool 471 // with empty values until we reach the ID we expect. 472 while (type->id.value() > expected_type_id) { 473 std::stringstream type_name; 474 type_name << "?" << expected_type_id; 475 type_pool_.MakeRef(type_name.str()); 476 expected_type_id++; 477 } 478 expected_type_id++; 479 type_pool_.MakeRef(ToString(type->type)); 480 481 std::vector<ResourceEntry*> sorted_entries = CollectAndSortEntries(type); 482 if (sorted_entries.empty()) { 483 continue; 484 } 485 486 if (!FlattenTypeSpec(type, &sorted_entries, buffer)) { 487 return false; 488 } 489 490 // Since the entries are sorted by ID, the last ID will be the largest. 491 const size_t num_entries = sorted_entries.back()->id.value() + 1; 492 493 // The binary resource table lists resource entries for each 494 // configuration. 495 // We store them inverted, where a resource entry lists the values for 496 // each 497 // configuration available. Here we reverse this to match the binary 498 // table. 499 std::map<ConfigDescription, std::vector<FlatEntry>> config_to_entry_list_map; 500 for (ResourceEntry* entry : sorted_entries) { 501 const uint32_t key_index = (uint32_t)key_pool_.MakeRef(entry->name).index(); 502 503 // Group values by configuration. 504 for (auto& config_value : entry->values) { 505 config_to_entry_list_map[config_value->config].push_back( 506 FlatEntry{entry, config_value->value.get(), key_index}); 507 } 508 } 509 510 // Flatten a configuration value. 511 for (auto& entry : config_to_entry_list_map) { 512 if (!FlattenConfig(type, entry.first, num_entries, &entry.second, buffer)) { 513 return false; 514 } 515 } 516 } 517 return true; 518 } 519 520 void FlattenLibrarySpec(BigBuffer* buffer) { 521 ChunkWriter lib_writer(buffer); 522 ResTable_lib_header* lib_header = 523 lib_writer.StartChunk<ResTable_lib_header>(RES_TABLE_LIBRARY_TYPE); 524 525 const size_t num_entries = (package_->id.value() == 0x00 ? 1 : 0) + shared_libs_->size(); 526 CHECK(num_entries > 0); 527 528 lib_header->count = util::HostToDevice32(num_entries); 529 530 ResTable_lib_entry* lib_entry = buffer->NextBlock<ResTable_lib_entry>(num_entries); 531 if (package_->id.value() == 0x00) { 532 // Add this package 533 lib_entry->packageId = util::HostToDevice32(0x00); 534 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName), 535 util::Utf8ToUtf16(package_->name)); 536 ++lib_entry; 537 } 538 539 for (auto& map_entry : *shared_libs_) { 540 lib_entry->packageId = util::HostToDevice32(map_entry.first); 541 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName), 542 util::Utf8ToUtf16(map_entry.second)); 543 ++lib_entry; 544 } 545 lib_writer.Finish(); 546 } 547 548 IAaptContext* context_; 549 IDiagnostics* diag_; 550 ResourceTablePackage* package_; 551 const std::map<size_t, std::string>* shared_libs_; 552 bool use_sparse_entries_; 553 StringPool type_pool_; 554 StringPool key_pool_; 555 }; 556 557 } // namespace 558 559 bool TableFlattener::Consume(IAaptContext* context, ResourceTable* table) { 560 // We must do this before writing the resources, since the string pool IDs may change. 561 table->string_pool.Prune(); 562 table->string_pool.Sort([](const StringPool::Context& a, const StringPool::Context& b) -> int { 563 int diff = util::compare(a.priority, b.priority); 564 if (diff == 0) { 565 diff = a.config.compare(b.config); 566 } 567 return diff; 568 }); 569 570 // Write the ResTable header. 571 ChunkWriter table_writer(buffer_); 572 ResTable_header* table_header = table_writer.StartChunk<ResTable_header>(RES_TABLE_TYPE); 573 table_header->packageCount = util::HostToDevice32(table->packages.size()); 574 575 // Write a self mapping entry for this package if the ID is non-standard (0x7f). 576 if (context->GetPackageType() == PackageType::kApp) { 577 const uint8_t package_id = context->GetPackageId(); 578 if (package_id != kFrameworkPackageId && package_id != kAppPackageId) { 579 table->included_packages_[package_id] = context->GetCompilationPackage(); 580 } 581 } 582 583 // Flatten the values string pool. 584 StringPool::FlattenUtf8(table_writer.buffer(), table->string_pool); 585 586 BigBuffer package_buffer(1024); 587 588 // Flatten each package. 589 for (auto& package : table->packages) { 590 PackageFlattener flattener(context, package.get(), &table->included_packages_, 591 options_.use_sparse_entries); 592 if (!flattener.FlattenPackage(&package_buffer)) { 593 return false; 594 } 595 } 596 597 // Finally merge all the packages into the main buffer. 598 table_writer.buffer()->AppendBuffer(std::move(package_buffer)); 599 table_writer.Finish(); 600 return true; 601 } 602 603 } // namespace aapt 604