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