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