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 "format/binary/TableFlattener.h"
18
19 #include <limits>
20 #include <sstream>
21 #include <type_traits>
22 #include <variant>
23
24 #include "ResourceTable.h"
25 #include "ResourceValues.h"
26 #include "SdkConstants.h"
27 #include "android-base/logging.h"
28 #include "android-base/macros.h"
29 #include "android-base/stringprintf.h"
30 #include "androidfw/BigBuffer.h"
31 #include "androidfw/ResourceUtils.h"
32 #include "format/binary/ChunkWriter.h"
33 #include "format/binary/ResEntryWriter.h"
34 #include "format/binary/ResourceTypeExtensions.h"
35 #include "optimize/Obfuscator.h"
36 #include "trace/TraceBuffer.h"
37
38 using namespace android;
39
40 namespace aapt {
41
42 namespace {
43
44 template <typename T>
cmp_ids(const T * a,const T * b)45 static bool cmp_ids(const T* a, const T* b) {
46 return a->id.value() < b->id.value();
47 }
48
strcpy16_htod(uint16_t * dst,size_t len,const StringPiece16 & src)49 static void strcpy16_htod(uint16_t* dst, size_t len, const StringPiece16& src) {
50 if (len == 0) {
51 return;
52 }
53
54 size_t i;
55 const char16_t* src_data = src.data();
56 for (i = 0; i < len - 1 && i < src.size(); i++) {
57 dst[i] = android::util::HostToDevice16((uint16_t)src_data[i]);
58 }
59 dst[i] = 0;
60 }
61
62 struct OverlayableChunk {
63 std::string actor;
64 android::Source source;
65 std::map<PolicyFlags, std::set<ResourceId>> policy_ids;
66 };
67
68 class PackageFlattener {
69 public:
PackageFlattener(IAaptContext * context,const ResourceTablePackageView & package,const ResourceTable::ReferencedPackages * shared_libs,SparseEntriesMode sparse_entries,bool compact_entries,bool collapse_key_stringpool,const std::set<ResourceName> & name_collapse_exemptions,bool deduplicate_entry_values)70 PackageFlattener(IAaptContext* context, const ResourceTablePackageView& package,
71 const ResourceTable::ReferencedPackages* shared_libs,
72 SparseEntriesMode sparse_entries, bool compact_entries,
73 bool collapse_key_stringpool,
74 const std::set<ResourceName>& name_collapse_exemptions,
75 bool deduplicate_entry_values)
76 : context_(context),
77 diag_(context->GetDiagnostics()),
78 package_(package),
79 shared_libs_(shared_libs),
80 sparse_entries_(sparse_entries),
81 compact_entries_(compact_entries),
82 collapse_key_stringpool_(collapse_key_stringpool),
83 name_collapse_exemptions_(name_collapse_exemptions),
84 deduplicate_entry_values_(deduplicate_entry_values) {
85 }
86
FlattenPackage(BigBuffer * buffer)87 bool FlattenPackage(BigBuffer* buffer) {
88 TRACE_CALL();
89 ChunkWriter pkg_writer(buffer);
90 ResTable_package* pkg_header = pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
91 pkg_header->id = android::util::HostToDevice32(package_.id.value());
92
93 // AAPT truncated the package name, so do the same.
94 // Shared libraries require full package names, so don't truncate theirs.
95 if (context_->GetPackageType() != PackageType::kApp &&
96 package_.name.size() >= arraysize(pkg_header->name)) {
97 diag_->Error(android::DiagMessage()
98 << "package name '" << package_.name
99 << "' is too long. "
100 "Shared libraries cannot have truncated package names");
101 return false;
102 }
103
104 // Copy the package name in device endianness.
105 strcpy16_htod(pkg_header->name, arraysize(pkg_header->name),
106 android::util::Utf8ToUtf16(package_.name));
107
108 // Serialize the types. We do this now so that our type and key strings
109 // are populated. We write those first.
110 android::BigBuffer type_buffer(1024);
111 FlattenTypes(&type_buffer);
112
113 pkg_header->typeStrings = android::util::HostToDevice32(pkg_writer.size());
114 android::StringPool::FlattenUtf16(pkg_writer.buffer(), type_pool_, diag_);
115
116 pkg_header->keyStrings = android::util::HostToDevice32(pkg_writer.size());
117 android::StringPool::FlattenUtf8(pkg_writer.buffer(), key_pool_, diag_);
118
119 // Append the types.
120 buffer->AppendBuffer(std::move(type_buffer));
121
122 // If there are libraries (or if the package ID is 0x00), encode a library chunk.
123 if (package_.id.value() == 0x00 || !shared_libs_->empty()) {
124 FlattenLibrarySpec(buffer);
125 }
126
127 if (!FlattenOverlayable(buffer)) {
128 return false;
129 }
130
131 if (!FlattenAliases(buffer)) {
132 return false;
133 }
134
135 pkg_writer.Finish();
136 return true;
137 }
138
139 private:
140 DISALLOW_COPY_AND_ASSIGN(PackageFlattener);
141
142 // Use compact entries only if
143 // 1) it is enabled, and that
144 // 2) the entries will be accessed on platforms U+, and
145 // 3) all entry keys can be encoded in 16 bits
UseCompactEntries(const ConfigDescription & config,std::vector<FlatEntry> * entries) const146 bool UseCompactEntries(const ConfigDescription& config, std::vector<FlatEntry>* entries) const {
147 return compact_entries_ && context_->GetMinSdkVersion() > SDK_TIRAMISU &&
148 std::none_of(entries->cbegin(), entries->cend(),
149 [](const auto& e) { return e.entry_key >= std::numeric_limits<uint16_t>::max(); });
150 }
151
GetResEntryWriter(bool dedup,bool compact,BigBuffer * buffer)152 std::unique_ptr<ResEntryWriter> GetResEntryWriter(bool dedup, bool compact, BigBuffer* buffer) {
153 if (dedup) {
154 if (compact) {
155 return std::make_unique<DeduplicateItemsResEntryWriter<true>>(buffer);
156 } else {
157 return std::make_unique<DeduplicateItemsResEntryWriter<false>>(buffer);
158 }
159 } else {
160 if (compact) {
161 return std::make_unique<SequentialResEntryWriter<true>>(buffer);
162 } else {
163 return std::make_unique<SequentialResEntryWriter<false>>(buffer);
164 }
165 }
166 }
167
FlattenConfig(const ResourceTableTypeView & type,const ConfigDescription & config,const size_t num_total_entries,std::vector<FlatEntry> * entries,BigBuffer * buffer)168 bool FlattenConfig(const ResourceTableTypeView& type, const ConfigDescription& config,
169 const size_t num_total_entries, std::vector<FlatEntry>* entries,
170 BigBuffer* buffer) {
171 CHECK(num_total_entries != 0);
172 CHECK(num_total_entries <= std::numeric_limits<uint16_t>::max());
173
174 ChunkWriter type_writer(buffer);
175 ResTable_type* type_header = type_writer.StartChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
176 type_header->id = type.id.value();
177 type_header->config = config;
178 type_header->config.swapHtoD();
179
180 std::vector<uint32_t> offsets;
181 offsets.resize(num_total_entries, 0xffffffffu);
182
183 bool compact_entry = UseCompactEntries(config, entries);
184
185 android::BigBuffer values_buffer(512);
186 auto res_entry_writer = GetResEntryWriter(deduplicate_entry_values_,
187 compact_entry, &values_buffer);
188
189 for (FlatEntry& flat_entry : *entries) {
190 CHECK(static_cast<size_t>(flat_entry.entry->id.value()) < num_total_entries);
191 offsets[flat_entry.entry->id.value()] = res_entry_writer->Write(&flat_entry);
192 }
193
194 // whether the offsets can be represented in 2 bytes
195 bool short_offsets = (values_buffer.size() / 4u) < std::numeric_limits<uint16_t>::max();
196
197 bool sparse_encode = sparse_entries_ == SparseEntriesMode::Enabled ||
198 sparse_entries_ == SparseEntriesMode::Forced;
199
200 if (sparse_entries_ == SparseEntriesMode::Forced ||
201 (context_->GetMinSdkVersion() == 0 && config.sdkVersion == 0)) {
202 // Sparse encode if forced or sdk version is not set in context and config.
203 } else {
204 // Otherwise, only sparse encode if the entries will be read on platforms S_V2+.
205 sparse_encode = sparse_encode && (context_->GetMinSdkVersion() >= SDK_S_V2);
206 }
207
208 // Only sparse encode if the offsets are representable in 2 bytes.
209 sparse_encode = sparse_encode && short_offsets;
210
211 // Only sparse encode if the ratio of populated entries to total entries is below some
212 // threshold.
213 sparse_encode =
214 sparse_encode && ((100 * entries->size()) / num_total_entries) < kSparseEncodingThreshold;
215
216 if (sparse_encode) {
217 type_header->entryCount = android::util::HostToDevice32(entries->size());
218 type_header->flags |= ResTable_type::FLAG_SPARSE;
219 ResTable_sparseTypeEntry* indices =
220 type_writer.NextBlock<ResTable_sparseTypeEntry>(entries->size());
221 for (size_t i = 0; i < num_total_entries; i++) {
222 if (offsets[i] != ResTable_type::NO_ENTRY) {
223 CHECK((offsets[i] & 0x03) == 0);
224 indices->idx = android::util::HostToDevice16(i);
225 indices->offset = android::util::HostToDevice16(offsets[i] / 4u);
226 indices++;
227 }
228 }
229 } else {
230 type_header->entryCount = android::util::HostToDevice32(num_total_entries);
231 if (compact_entry && short_offsets) {
232 // use 16-bit offset only when compact_entry is true
233 type_header->flags |= ResTable_type::FLAG_OFFSET16;
234 uint16_t* indices = type_writer.NextBlock<uint16_t>(num_total_entries);
235 for (size_t i = 0; i < num_total_entries; i++) {
236 indices[i] = android::util::HostToDevice16(offsets[i] / 4u);
237 }
238 } else {
239 uint32_t* indices = type_writer.NextBlock<uint32_t>(num_total_entries);
240 for (size_t i = 0; i < num_total_entries; i++) {
241 indices[i] = android::util::HostToDevice32(offsets[i]);
242 }
243 }
244 }
245
246 type_writer.buffer()->Align4();
247 type_header->entriesStart = android::util::HostToDevice32(type_writer.size());
248 type_writer.buffer()->AppendBuffer(std::move(values_buffer));
249 type_writer.Finish();
250 return true;
251 }
252
FlattenAliases(BigBuffer * buffer)253 bool FlattenAliases(BigBuffer* buffer) {
254 if (aliases_.empty()) {
255 return true;
256 }
257
258 ChunkWriter alias_writer(buffer);
259 auto header =
260 alias_writer.StartChunk<ResTable_staged_alias_header>(RES_TABLE_STAGED_ALIAS_TYPE);
261 header->count = android::util::HostToDevice32(aliases_.size());
262
263 auto mapping = alias_writer.NextBlock<ResTable_staged_alias_entry>(aliases_.size());
264 for (auto& p : aliases_) {
265 mapping->stagedResId = android::util::HostToDevice32(p.first);
266 mapping->finalizedResId = android::util::HostToDevice32(p.second);
267 ++mapping;
268 }
269 alias_writer.Finish();
270 return true;
271 }
272
FlattenOverlayable(BigBuffer * buffer)273 bool FlattenOverlayable(BigBuffer* buffer) {
274 std::set<ResourceId> seen_ids;
275 std::map<std::string, OverlayableChunk> overlayable_chunks;
276
277 CHECK(bool(package_.id)) << "package must have an ID set when flattening <overlayable>";
278 for (auto& type : package_.types) {
279 CHECK(bool(type.id)) << "type must have an ID set when flattening <overlayable>";
280 for (auto& entry : type.entries) {
281 CHECK(bool(type.id)) << "entry must have an ID set when flattening <overlayable>";
282 if (!entry.overlayable_item) {
283 continue;
284 }
285
286 const OverlayableItem& item = entry.overlayable_item.value();
287
288 // Resource ids should only appear once in the resource table
289 ResourceId id = android::make_resid(package_.id.value(), type.id.value(), entry.id.value());
290 CHECK(seen_ids.find(id) == seen_ids.end())
291 << "multiple overlayable definitions found for resource "
292 << ResourceName(package_.name, type.named_type, entry.name).to_string();
293 seen_ids.insert(id);
294
295 // Find the overlayable chunk with the specified name
296 OverlayableChunk* overlayable_chunk = nullptr;
297 auto iter = overlayable_chunks.find(item.overlayable->name);
298 if (iter == overlayable_chunks.end()) {
299 OverlayableChunk chunk{item.overlayable->actor, item.overlayable->source};
300 overlayable_chunk =
301 &overlayable_chunks.insert({item.overlayable->name, chunk}).first->second;
302 } else {
303 OverlayableChunk& chunk = iter->second;
304 if (!(chunk.source == item.overlayable->source)) {
305 // The name of an overlayable set of resources must be unique
306 context_->GetDiagnostics()->Error(android::DiagMessage(item.overlayable->source)
307 << "duplicate overlayable name"
308 << item.overlayable->name << "'");
309 context_->GetDiagnostics()->Error(android::DiagMessage(chunk.source)
310 << "previous declaration here");
311 return false;
312 }
313
314 CHECK(chunk.actor == item.overlayable->actor);
315 overlayable_chunk = &chunk;
316 }
317
318 if (item.policies == 0) {
319 context_->GetDiagnostics()->Error(android::DiagMessage(item.overlayable->source)
320 << "overlayable " << entry.name
321 << " does not specify policy");
322 return false;
323 }
324
325 auto policy = overlayable_chunk->policy_ids.find(item.policies);
326 if (policy != overlayable_chunk->policy_ids.end()) {
327 policy->second.insert(id);
328 } else {
329 overlayable_chunk->policy_ids.insert(
330 std::make_pair(item.policies, std::set<ResourceId>{id}));
331 }
332 }
333 }
334
335 for (auto& overlayable_pair : overlayable_chunks) {
336 std::string name = overlayable_pair.first;
337 OverlayableChunk& overlayable = overlayable_pair.second;
338
339 // Write the header of the overlayable chunk
340 ChunkWriter overlayable_writer(buffer);
341 auto* overlayable_type =
342 overlayable_writer.StartChunk<ResTable_overlayable_header>(RES_TABLE_OVERLAYABLE_TYPE);
343 if (name.size() >= arraysize(overlayable_type->name)) {
344 diag_->Error(android::DiagMessage()
345 << "overlayable name '" << name << "' exceeds maximum length ("
346 << arraysize(overlayable_type->name) << " utf16 characters)");
347 return false;
348 }
349 strcpy16_htod(overlayable_type->name, arraysize(overlayable_type->name),
350 android::util::Utf8ToUtf16(name));
351
352 if (overlayable.actor.size() >= arraysize(overlayable_type->actor)) {
353 diag_->Error(android::DiagMessage()
354 << "overlayable name '" << overlayable.actor << "' exceeds maximum length ("
355 << arraysize(overlayable_type->actor) << " utf16 characters)");
356 return false;
357 }
358 strcpy16_htod(overlayable_type->actor, arraysize(overlayable_type->actor),
359 android::util::Utf8ToUtf16(overlayable.actor));
360
361 // Write each policy block for the overlayable
362 for (auto& policy_ids : overlayable.policy_ids) {
363 ChunkWriter policy_writer(buffer);
364 auto* policy_type = policy_writer.StartChunk<ResTable_overlayable_policy_header>(
365 RES_TABLE_OVERLAYABLE_POLICY_TYPE);
366 policy_type->policy_flags = static_cast<PolicyFlags>(
367 android::util::HostToDevice32(static_cast<uint32_t>(policy_ids.first)));
368 policy_type->entry_count =
369 android::util::HostToDevice32(static_cast<uint32_t>(policy_ids.second.size()));
370 // Write the ids after the policy header
371 auto* id_block = policy_writer.NextBlock<ResTable_ref>(policy_ids.second.size());
372 for (const ResourceId& id : policy_ids.second) {
373 id_block->ident = android::util::HostToDevice32(id.id);
374 id_block++;
375 }
376 policy_writer.Finish();
377 }
378 overlayable_writer.Finish();
379 }
380
381 return true;
382 }
383
FlattenTypeSpec(const ResourceTableTypeView & type,const std::vector<ResourceTableEntryView> & sorted_entries,BigBuffer * buffer)384 ResTable_typeSpec* FlattenTypeSpec(const ResourceTableTypeView& type,
385 const std::vector<ResourceTableEntryView>& sorted_entries,
386 BigBuffer* buffer) {
387 ChunkWriter type_spec_writer(buffer);
388 ResTable_typeSpec* spec_header =
389 type_spec_writer.StartChunk<ResTable_typeSpec>(RES_TABLE_TYPE_SPEC_TYPE);
390 spec_header->id = type.id.value();
391
392 if (sorted_entries.empty()) {
393 type_spec_writer.Finish();
394 return spec_header;
395 }
396
397 // We can't just take the size of the vector. There may be holes in the
398 // entry ID space.
399 // Since the entries are sorted by ID, the last one will be the biggest.
400 const size_t num_entries = sorted_entries.back().id.value() + 1;
401
402 spec_header->entryCount = android::util::HostToDevice32(num_entries);
403
404 // Reserve space for the masks of each resource in this type. These
405 // show for which configuration axis the resource changes.
406 uint32_t* config_masks = type_spec_writer.NextBlock<uint32_t>(num_entries);
407
408 for (const ResourceTableEntryView& entry : sorted_entries) {
409 const uint16_t entry_id = entry.id.value();
410
411 // Populate the config masks for this entry.
412 uint32_t& entry_config_masks = config_masks[entry_id];
413 if (entry.visibility.level == Visibility::Level::kPublic) {
414 entry_config_masks |= android::util::HostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
415 }
416 if (entry.visibility.staged_api) {
417 entry_config_masks |= android::util::HostToDevice32(ResTable_typeSpec::SPEC_STAGED_API);
418 }
419
420 const size_t config_count = entry.values.size();
421 for (size_t i = 0; i < config_count; i++) {
422 const ConfigDescription& config = entry.values[i]->config;
423 for (size_t j = i + 1; j < config_count; j++) {
424 config_masks[entry_id] |=
425 android::util::HostToDevice32(config.diff(entry.values[j]->config));
426 }
427 }
428 }
429 type_spec_writer.Finish();
430 return spec_header;
431 }
432
FlattenTypes(BigBuffer * buffer)433 bool FlattenTypes(BigBuffer* buffer) {
434 size_t expected_type_id = 1;
435 for (const ResourceTableTypeView& type : package_.types) {
436 if (type.named_type.type == ResourceType::kStyleable ||
437 type.named_type.type == ResourceType::kMacro) {
438 // Styleables and macros are not real resource types.
439 continue;
440 }
441
442 // If there is a gap in the type IDs, fill in the StringPool
443 // with empty values until we reach the ID we expect.
444 while (type.id.value() > expected_type_id) {
445 std::stringstream type_name;
446 type_name << "?" << expected_type_id;
447 type_pool_.MakeRef(type_name.str());
448 expected_type_id++;
449 }
450 expected_type_id++;
451 type_pool_.MakeRef(type.named_type.to_string());
452
453 const auto type_spec_header = FlattenTypeSpec(type, type.entries, buffer);
454 if (!type_spec_header) {
455 return false;
456 }
457
458 // Since the entries are sorted by ID, the last ID will be the largest.
459 const size_t num_entries = type.entries.back().id.value() + 1;
460
461 // The binary resource table lists resource entries for each
462 // configuration.
463 // We store them inverted, where a resource entry lists the values for
464 // each
465 // configuration available. Here we reverse this to match the binary
466 // table.
467 std::map<ConfigDescription, std::vector<FlatEntry>> config_to_entry_list_map;
468
469 for (const ResourceTableEntryView& entry : type.entries) {
470 if (entry.staged_id) {
471 aliases_.insert(std::make_pair(
472 entry.staged_id.value().id.id,
473 ResourceId(package_.id.value(), type.id.value(), entry.id.value()).id));
474 }
475
476 uint32_t local_key_index;
477 auto onObfuscate = [this, &local_key_index, &entry](Obfuscator::Result obfuscatedResult,
478 const ResourceName& resource_name) {
479 if (obfuscatedResult == Obfuscator::Result::Keep_ExemptionList) {
480 local_key_index = (uint32_t)key_pool_.MakeRef(entry.name).index();
481 } else if (obfuscatedResult == Obfuscator::Result::Keep_Overlayable) {
482 // if the resource name of the specific entry is obfuscated and this
483 // entry is in the overlayable list, the overlay can't work on this
484 // overlayable at runtime because the name has been obfuscated in
485 // resources.arsc during flatten operation.
486 const OverlayableItem& item = entry.overlayable_item.value();
487 context_->GetDiagnostics()->Warn(android::DiagMessage(item.overlayable->source)
488 << "The resource name of overlayable entry '"
489 << resource_name.to_string()
490 << "' shouldn't be obfuscated in resources.arsc");
491
492 local_key_index = (uint32_t)key_pool_.MakeRef(entry.name).index();
493 } else {
494 local_key_index =
495 (uint32_t)key_pool_.MakeRef(Obfuscator::kObfuscatedResourceName).index();
496 }
497 };
498
499 Obfuscator::ObfuscateResourceName(collapse_key_stringpool_, name_collapse_exemptions_,
500 type.named_type, entry, onObfuscate);
501
502 // Group values by configuration.
503 for (auto& config_value : entry.values) {
504 config_to_entry_list_map[config_value->config].push_back(
505 FlatEntry{&entry, config_value->value.get(), local_key_index});
506 }
507 }
508
509 // Flatten a configuration value.
510 for (auto& entry : config_to_entry_list_map) {
511 if (!FlattenConfig(type, entry.first, num_entries, &entry.second, buffer)) {
512 return false;
513 }
514 }
515
516 // And now we can update the type entries count in the typeSpec header.
517 type_spec_header->typesCount = android::util::HostToDevice16(uint16_t(std::min<uint32_t>(
518 config_to_entry_list_map.size(), std::numeric_limits<uint16_t>::max())));
519 }
520 return true;
521 }
522
FlattenLibrarySpec(BigBuffer * buffer)523 void FlattenLibrarySpec(BigBuffer* buffer) {
524 ChunkWriter lib_writer(buffer);
525 ResTable_lib_header* lib_header =
526 lib_writer.StartChunk<ResTable_lib_header>(RES_TABLE_LIBRARY_TYPE);
527
528 const size_t num_entries = (package_.id.value() == 0x00 ? 1 : 0) + shared_libs_->size();
529 CHECK(num_entries > 0);
530
531 lib_header->count = android::util::HostToDevice32(num_entries);
532
533 ResTable_lib_entry* lib_entry = buffer->NextBlock<ResTable_lib_entry>(num_entries);
534 if (package_.id.value() == 0x00) {
535 // Add this package
536 lib_entry->packageId = android::util::HostToDevice32(0x00);
537 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
538 android::util::Utf8ToUtf16(package_.name));
539 ++lib_entry;
540 }
541
542 for (auto& map_entry : *shared_libs_) {
543 lib_entry->packageId = android::util::HostToDevice32(map_entry.first);
544 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
545 android::util::Utf8ToUtf16(map_entry.second));
546 ++lib_entry;
547 }
548 lib_writer.Finish();
549 }
550
551 IAaptContext* context_;
552 android::IDiagnostics* diag_;
553 const ResourceTablePackageView package_;
554 const ResourceTable::ReferencedPackages* shared_libs_;
555 SparseEntriesMode sparse_entries_;
556 bool compact_entries_;
557 android::StringPool type_pool_;
558 android::StringPool key_pool_;
559 bool collapse_key_stringpool_;
560 const std::set<ResourceName>& name_collapse_exemptions_;
561 std::map<uint32_t, uint32_t> aliases_;
562 bool deduplicate_entry_values_;
563 };
564
565 } // namespace
566
Consume(IAaptContext * context,ResourceTable * table)567 bool TableFlattener::Consume(IAaptContext* context, ResourceTable* table) {
568 TRACE_CALL();
569 // We must do this before writing the resources, since the string pool IDs may change.
570 table->string_pool.Prune();
571 table->string_pool.Sort(
572 [](const android::StringPool::Context& a, const android::StringPool::Context& b) -> int {
573 int diff = util::compare(a.priority, b.priority);
574 if (diff == 0) {
575 diff = a.config.compare(b.config);
576 }
577 return diff;
578 });
579
580 // Write the ResTable header.
581 const auto& table_view =
582 table->GetPartitionedView(ResourceTableViewOptions{.create_alias_entries = true});
583 ChunkWriter table_writer(buffer_);
584 ResTable_header* table_header = table_writer.StartChunk<ResTable_header>(RES_TABLE_TYPE);
585 table_header->packageCount = android::util::HostToDevice32(table_view.packages.size());
586
587 // Flatten the values string pool.
588 android::StringPool::FlattenUtf8(table_writer.buffer(), table->string_pool,
589 context->GetDiagnostics());
590
591 android::BigBuffer package_buffer(1024);
592
593 // Flatten each package.
594 for (auto& package : table_view.packages) {
595 if (context->GetPackageType() == PackageType::kApp) {
596 // Write a self mapping entry for this package if the ID is non-standard (0x7f).
597 CHECK((bool)package.id) << "Resource ids have not been assigned before flattening the table";
598 const uint8_t package_id = package.id.value();
599 if (package_id != kFrameworkPackageId && package_id != kAppPackageId) {
600 auto result = table->included_packages_.insert({package_id, package.name});
601 if (!result.second && result.first->second != package.name) {
602 // A mapping for this package ID already exists, and is a different package. Error!
603 context->GetDiagnostics()->Error(
604 android::DiagMessage() << android::base::StringPrintf(
605 "can't map package ID %02x to '%s'. Already mapped to '%s'", package_id,
606 package.name.c_str(), result.first->second.c_str()));
607 return false;
608 }
609 }
610 }
611
612 PackageFlattener flattener(context, package, &table->included_packages_,
613 options_.sparse_entries,
614 options_.use_compact_entries,
615 options_.collapse_key_stringpool,
616 options_.name_collapse_exemptions,
617 options_.deduplicate_entry_values);
618 if (!flattener.FlattenPackage(&package_buffer)) {
619 return false;
620 }
621 }
622
623 // Finally merge all the packages into the main buffer.
624 table_writer.buffer()->AppendBuffer(std::move(package_buffer));
625 table_writer.Finish();
626 return true;
627 }
628
629 } // namespace aapt
630