blob: 8641a7c93d194f609d435a32798edb3b6cade399 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
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
Adam Lesinski46708052017-09-29 14:49:15 -070017#include "format/binary/TableFlattener.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070018
Adam Lesinski803c7c82016-04-06 16:09:43 -070019#include <algorithm>
Adam Lesinskicacb28f2016-10-19 12:18:14 -070020#include <numeric>
Adam Lesinskid0f116b2016-07-08 15:00:32 -070021#include <sstream>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070022#include <type_traits>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070023
Adam Lesinskice5e56e22016-10-21 17:56:45 -070024#include "android-base/logging.h"
25#include "android-base/macros.h"
Adam Lesinski490595a2017-11-07 17:08:07 -080026#include "android-base/stringprintf.h"
Adam Lesinskice5e56e22016-10-21 17:56:45 -070027
28#include "ResourceTable.h"
29#include "ResourceValues.h"
Adam Lesinskic8f71aa2017-02-08 07:03:50 -080030#include "SdkConstants.h"
Adam Lesinskice5e56e22016-10-21 17:56:45 -070031#include "ValueVisitor.h"
Adam Lesinski46708052017-09-29 14:49:15 -070032#include "format/binary/ChunkWriter.h"
33#include "format/binary/ResourceTypeExtensions.h"
Adam Lesinskice5e56e22016-10-21 17:56:45 -070034#include "util/BigBuffer.h"
35
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036using namespace android;
37
38namespace aapt {
39
40namespace {
41
42template <typename T>
Adam Lesinskice5e56e22016-10-21 17:56:45 -070043static bool cmp_ids(const T* a, const T* b) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070044 return a->id.value() < b->id.value();
Adam Lesinski1ab598f2015-08-14 14:26:04 -070045}
46
47static void strcpy16_htod(uint16_t* dst, size_t len, const StringPiece16& src) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070048 if (len == 0) {
49 return;
50 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070051
Adam Lesinskicacb28f2016-10-19 12:18:14 -070052 size_t i;
Adam Lesinskice5e56e22016-10-21 17:56:45 -070053 const char16_t* src_data = src.data();
Adam Lesinskicacb28f2016-10-19 12:18:14 -070054 for (i = 0; i < len - 1 && i < src.size(); i++) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -070055 dst[i] = util::HostToDevice16((uint16_t)src_data[i]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -070056 }
57 dst[i] = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058}
59
Adam Lesinskice5e56e22016-10-21 17:56:45 -070060static bool cmp_style_entries(const Style::Entry& a, const Style::Entry& b) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070061 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;
Adam Lesinski59e04c62016-02-04 15:59:23 -080070}
71
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072struct FlatEntry {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070073 ResourceEntry* entry;
74 Value* value;
Adam Lesinski3b4cd942015-10-30 16:31:42 -070075
Adam Lesinskicacb28f2016-10-19 12:18:14 -070076 // The entry string pool index to the entry's name.
Adam Lesinskice5e56e22016-10-21 17:56:45 -070077 uint32_t entry_key;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070078};
79
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070080class MapFlattenVisitor : public ValueVisitor {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070081 public:
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070082 using ValueVisitor::Visit;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070083
Adam Lesinskice5e56e22016-10-21 17:56:45 -070084 MapFlattenVisitor(ResTable_entry_ext* out_entry, BigBuffer* buffer)
Adam Lesinski46708052017-09-29 14:49:15 -070085 : out_entry_(out_entry), buffer_(buffer) {
86 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -070087
Adam Lesinskice5e56e22016-10-21 17:56:45 -070088 void Visit(Attribute* attr) override {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070089 {
90 Reference key = Reference(ResourceId(ResTable_map::ATTR_TYPE));
Adam Lesinskice5e56e22016-10-21 17:56:45 -070091 BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->type_mask);
92 FlattenEntry(&key, &val);
Adam Lesinski28cacf02015-11-23 14:22:47 -080093 }
94
Adam Lesinskice5e56e22016-10-21 17:56:45 -070095 if (attr->min_int != std::numeric_limits<int32_t>::min()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070096 Reference key = Reference(ResourceId(ResTable_map::ATTR_MIN));
Adam Lesinski46708052017-09-29 14:49:15 -070097 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->min_int));
Adam Lesinskice5e56e22016-10-21 17:56:45 -070098 FlattenEntry(&key, &val);
Adam Lesinski1ab598f2015-08-14 14:26:04 -070099 }
100
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700101 if (attr->max_int != std::numeric_limits<int32_t>::max()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700102 Reference key = Reference(ResourceId(ResTable_map::ATTR_MAX));
Adam Lesinski46708052017-09-29 14:49:15 -0700103 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->max_int));
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700104 FlattenEntry(&key, &val);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700105 }
106
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 for (Attribute::Symbol& s : attr->symbols) {
108 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700109 FlattenEntry(&s.symbol, &val);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700110 }
111 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800112
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700113 void Visit(Style* style) override {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700114 if (style->parent) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700115 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);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700118 }
119
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700120 // Sort the style.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700121 std::sort(style->entries.begin(), style->entries.end(), cmp_style_entries);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700122
123 for (Style::Entry& entry : style->entries) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700124 FlattenEntry(&entry.key, entry.value.get());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700125 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700127
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700128 void Visit(Styleable* styleable) override {
129 for (auto& attr_ref : styleable->entries) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700130 BinaryPrimitive val(Res_value{});
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700131 FlattenEntry(&attr_ref, &val);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700132 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700133 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800134
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700135 void Visit(Array* array) override {
Ryan Mitchell0f7da5e2018-08-16 16:10:00 -0700136 const size_t count = array->elements.size();
137 for (size_t i = 0; i < count; i++) {
138 Reference key(android::ResTable_map::ATTR_MIN + i);
139 FlattenEntry(&key, array->elements[i].get());
Adam Lesinski59e04c62016-02-04 15:59:23 -0800140 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700141 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800142
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700143 void Visit(Plural* plural) override {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700144 const size_t count = plural->values.size();
145 for (size_t i = 0; i < count; i++) {
146 if (!plural->values[i]) {
147 continue;
148 }
149
150 ResourceId q;
151 switch (i) {
152 case Plural::Zero:
153 q.id = android::ResTable_map::ATTR_ZERO;
154 break;
155
156 case Plural::One:
157 q.id = android::ResTable_map::ATTR_ONE;
158 break;
159
160 case Plural::Two:
161 q.id = android::ResTable_map::ATTR_TWO;
162 break;
163
164 case Plural::Few:
165 q.id = android::ResTable_map::ATTR_FEW;
166 break;
167
168 case Plural::Many:
169 q.id = android::ResTable_map::ATTR_MANY;
170 break;
171
172 case Plural::Other:
173 q.id = android::ResTable_map::ATTR_OTHER;
174 break;
175
176 default:
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700177 LOG(FATAL) << "unhandled plural type";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700178 break;
179 }
180
181 Reference key(q);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700182 FlattenEntry(&key, plural->values[i].get());
Adam Lesinski59e04c62016-02-04 15:59:23 -0800183 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700184 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800185
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700186 /**
187 * Call this after visiting a Value. This will finish any work that
188 * needs to be done to prepare the entry.
189 */
Adam Lesinski46708052017-09-29 14:49:15 -0700190 void Finish() {
191 out_entry_->count = util::HostToDevice32(entry_count_);
192 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800193
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700194 private:
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700195 DISALLOW_COPY_AND_ASSIGN(MapFlattenVisitor);
196
197 void FlattenKey(Reference* key, ResTable_map* out_entry) {
198 CHECK(bool(key->id)) << "key has no ID";
199 out_entry->name.ident = util::HostToDevice32(key->id.value().id);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700200 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800201
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700202 void FlattenValue(Item* value, ResTable_map* out_entry) {
203 CHECK(value->Flatten(&out_entry->value)) << "flatten failed";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700204 }
205
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700206 void FlattenEntry(Reference* key, Item* value) {
207 ResTable_map* out_entry = buffer_->NextBlock<ResTable_map>();
208 FlattenKey(key, out_entry);
209 FlattenValue(value, out_entry);
210 out_entry->value.size = util::HostToDevice16(sizeof(out_entry->value));
211 entry_count_++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700212 }
213
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700214 ResTable_entry_ext* out_entry_;
215 BigBuffer* buffer_;
216 size_t entry_count_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700217};
218
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700219class PackageFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700220 public:
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800221 PackageFlattener(IAaptContext* context, ResourceTablePackage* package,
Luke Nicholsonb0643302017-12-01 15:29:03 -0800222 const std::map<size_t, std::string>* shared_libs, bool use_sparse_entries,
223 bool collapse_key_stringpool, const std::set<std::string>& whitelisted_resources)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800224 : context_(context),
225 diag_(context->GetDiagnostics()),
226 package_(package),
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800227 shared_libs_(shared_libs),
Luke Nicholsonb0643302017-12-01 15:29:03 -0800228 use_sparse_entries_(use_sparse_entries),
229 collapse_key_stringpool_(collapse_key_stringpool),
230 whitelisted_resources_(whitelisted_resources) {
Adam Lesinski46708052017-09-29 14:49:15 -0700231 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700232
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700233 bool FlattenPackage(BigBuffer* buffer) {
234 ChunkWriter pkg_writer(buffer);
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800235 ResTable_package* pkg_header = pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700236 pkg_header->id = util::HostToDevice32(package_->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700237
Adam Lesinskib522f042017-04-21 16:57:59 -0700238 // AAPT truncated the package name, so do the same.
239 // Shared libraries require full package names, so don't truncate theirs.
240 if (context_->GetPackageType() != PackageType::kApp &&
241 package_->name.size() >= arraysize(pkg_header->name)) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700242 diag_->Error(DiagMessage() << "package name '" << package_->name
Adam Lesinskib522f042017-04-21 16:57:59 -0700243 << "' is too long. "
244 "Shared libraries cannot have truncated package names");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700245 return false;
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700246 }
247
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700248 // Copy the package name in device endianness.
Adam Lesinskib522f042017-04-21 16:57:59 -0700249 strcpy16_htod(pkg_header->name, arraysize(pkg_header->name), util::Utf8ToUtf16(package_->name));
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700250
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700251 // Serialize the types. We do this now so that our type and key strings
252 // are populated. We write those first.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700253 BigBuffer type_buffer(1024);
254 FlattenTypes(&type_buffer);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700255
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700256 pkg_header->typeStrings = util::HostToDevice32(pkg_writer.size());
Ryan Mitchella15c2a82018-03-26 11:05:31 -0700257 StringPool::FlattenUtf16(pkg_writer.buffer(), type_pool_, diag_);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700258
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700259 pkg_header->keyStrings = util::HostToDevice32(pkg_writer.size());
Ryan Mitchella15c2a82018-03-26 11:05:31 -0700260 StringPool::FlattenUtf8(pkg_writer.buffer(), key_pool_, diag_);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700261
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700262 // Append the types.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700263 buffer->AppendBuffer(std::move(type_buffer));
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700264
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800265 // If there are libraries (or if the package ID is 0x00), encode a library chunk.
266 if (package_->id.value() == 0x00 || !shared_libs_->empty()) {
267 FlattenLibrarySpec(buffer);
268 }
269
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700270 pkg_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700271 return true;
272 }
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700273
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700274 private:
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700275 DISALLOW_COPY_AND_ASSIGN(PackageFlattener);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700276
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700277 template <typename T, bool IsItem>
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700278 T* WriteEntry(FlatEntry* entry, BigBuffer* buffer) {
Adam Lesinski46708052017-09-29 14:49:15 -0700279 static_assert(
280 std::is_same<ResTable_entry, T>::value || std::is_same<ResTable_entry_ext, T>::value,
281 "T must be ResTable_entry or ResTable_entry_ext");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700282
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700283 T* result = buffer->NextBlock<T>();
284 ResTable_entry* out_entry = (ResTable_entry*)result;
Adam Lesinski71be7052017-12-12 16:48:07 -0800285 if (entry->entry->visibility.level == Visibility::Level::kPublic) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700286 out_entry->flags |= ResTable_entry::FLAG_PUBLIC;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700287 }
288
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700289 if (entry->value->IsWeak()) {
290 out_entry->flags |= ResTable_entry::FLAG_WEAK;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700291 }
292
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700293 if (!IsItem) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700294 out_entry->flags |= ResTable_entry::FLAG_COMPLEX;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700295 }
296
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700297 out_entry->flags = util::HostToDevice16(out_entry->flags);
298 out_entry->key.index = util::HostToDevice32(entry->entry_key);
299 out_entry->size = util::HostToDevice16(sizeof(T));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700300 return result;
301 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700302
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700303 bool FlattenValue(FlatEntry* entry, BigBuffer* buffer) {
304 if (Item* item = ValueCast<Item>(entry->value)) {
305 WriteEntry<ResTable_entry, true>(entry, buffer);
306 Res_value* outValue = buffer->NextBlock<Res_value>();
307 CHECK(item->Flatten(outValue)) << "flatten failed";
308 outValue->size = util::HostToDevice16(sizeof(*outValue));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700309 } else {
Adam Lesinski46708052017-09-29 14:49:15 -0700310 ResTable_entry_ext* out_entry = WriteEntry<ResTable_entry_ext, false>(entry, buffer);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700311 MapFlattenVisitor visitor(out_entry, buffer);
312 entry->value->Accept(&visitor);
313 visitor.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700314 }
315 return true;
316 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700317
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800318 bool FlattenConfig(const ResourceTableType* type, const ConfigDescription& config,
319 const size_t num_total_entries, std::vector<FlatEntry>* entries,
320 BigBuffer* buffer) {
321 CHECK(num_total_entries != 0);
322 CHECK(num_total_entries <= std::numeric_limits<uint16_t>::max());
323
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700324 ChunkWriter type_writer(buffer);
Adam Lesinski46708052017-09-29 14:49:15 -0700325 ResTable_type* type_header = type_writer.StartChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700326 type_header->id = type->id.value();
327 type_header->config = config;
328 type_header->config.swapHtoD();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700329
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800330 std::vector<uint32_t> offsets;
331 offsets.resize(num_total_entries, 0xffffffffu);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700332
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800333 BigBuffer values_buffer(512);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700334 for (FlatEntry& flat_entry : *entries) {
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800335 CHECK(static_cast<size_t>(flat_entry.entry->id.value()) < num_total_entries);
336 offsets[flat_entry.entry->id.value()] = values_buffer.size();
337 if (!FlattenValue(&flat_entry, &values_buffer)) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700338 diag_->Error(DiagMessage()
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700339 << "failed to flatten resource '"
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800340 << ResourceNameRef(package_->name, type->type, flat_entry.entry->name)
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700341 << "' for configuration '" << config << "'");
342 return false;
343 }
344 }
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800345
346 bool sparse_encode = use_sparse_entries_;
347
348 // Only sparse encode if the entries will be read on platforms O+.
349 sparse_encode =
350 sparse_encode && (context_->GetMinSdkVersion() >= SDK_O || config.sdkVersion >= SDK_O);
351
352 // Only sparse encode if the offsets are representable in 2 bytes.
353 sparse_encode =
354 sparse_encode && (values_buffer.size() / 4u) <= std::numeric_limits<uint16_t>::max();
355
356 // Only sparse encode if the ratio of populated entries to total entries is below some
357 // threshold.
358 sparse_encode =
359 sparse_encode && ((100 * entries->size()) / num_total_entries) < kSparseEncodingThreshold;
360
361 if (sparse_encode) {
362 type_header->entryCount = util::HostToDevice32(entries->size());
363 type_header->flags |= ResTable_type::FLAG_SPARSE;
364 ResTable_sparseTypeEntry* indices =
365 type_writer.NextBlock<ResTable_sparseTypeEntry>(entries->size());
366 for (size_t i = 0; i < num_total_entries; i++) {
367 if (offsets[i] != ResTable_type::NO_ENTRY) {
368 CHECK((offsets[i] & 0x03) == 0);
369 indices->idx = util::HostToDevice16(i);
370 indices->offset = util::HostToDevice16(offsets[i] / 4u);
371 indices++;
372 }
373 }
374 } else {
375 type_header->entryCount = util::HostToDevice32(num_total_entries);
376 uint32_t* indices = type_writer.NextBlock<uint32_t>(num_total_entries);
377 for (size_t i = 0; i < num_total_entries; i++) {
378 indices[i] = util::HostToDevice32(offsets[i]);
379 }
380 }
381
382 type_header->entriesStart = util::HostToDevice32(type_writer.size());
383 type_writer.buffer()->AppendBuffer(std::move(values_buffer));
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700384 type_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700385 return true;
386 }
387
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700388 std::vector<ResourceTableType*> CollectAndSortTypes() {
389 std::vector<ResourceTableType*> sorted_types;
390 for (auto& type : package_->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700391 if (type->type == ResourceType::kStyleable) {
392 // Styleables aren't real Resource Types, they are represented in the
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700393 // R.java file.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700394 continue;
395 }
396
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700397 CHECK(bool(type->id)) << "type must have an ID set";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700398
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700399 sorted_types.push_back(type.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700400 }
Adam Lesinski46708052017-09-29 14:49:15 -0700401 std::sort(sorted_types.begin(), sorted_types.end(), cmp_ids<ResourceTableType>);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700402 return sorted_types;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700403 }
404
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700405 std::vector<ResourceEntry*> CollectAndSortEntries(ResourceTableType* type) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700406 // Sort the entries by entry ID.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700407 std::vector<ResourceEntry*> sorted_entries;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700408 for (auto& entry : type->entries) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700409 CHECK(bool(entry->id)) << "entry must have an ID set";
410 sorted_entries.push_back(entry.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700411 }
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800412 std::sort(sorted_entries.begin(), sorted_entries.end(), cmp_ids<ResourceEntry>);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700413 return sorted_entries;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700414 }
415
Adam Lesinski46708052017-09-29 14:49:15 -0700416 bool FlattenTypeSpec(ResourceTableType* type, std::vector<ResourceEntry*>* sorted_entries,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700417 BigBuffer* buffer) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700418 ChunkWriter type_spec_writer(buffer);
419 ResTable_typeSpec* spec_header =
Adam Lesinski46708052017-09-29 14:49:15 -0700420 type_spec_writer.StartChunk<ResTable_typeSpec>(RES_TABLE_TYPE_SPEC_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700421 spec_header->id = type->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700422
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700423 if (sorted_entries->empty()) {
424 type_spec_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700425 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700426 }
427
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700428 // 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.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700431 const size_t num_entries = sorted_entries->back()->id.value() + 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700432
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700433 spec_header->entryCount = util::HostToDevice32(num_entries);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700434
435 // Reserve space for the masks of each resource in this type. These
436 // show for which configuration axis the resource changes.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700437 uint32_t* config_masks = type_spec_writer.NextBlock<uint32_t>(num_entries);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700438
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700439 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);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700442
443 // Populate the config masks for this entry.
444
Adam Lesinski71be7052017-12-12 16:48:07 -0800445 if (entry->visibility.level == Visibility::Level::kPublic) {
Adam Lesinski46708052017-09-29 14:49:15 -0700446 config_masks[entry->id.value()] |= util::HostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700447 }
448
Adam Lesinski71be7052017-12-12 16:48:07 -0800449 if (entry->overlayable) {
450 config_masks[entry->id.value()] |=
451 util::HostToDevice32(ResTable_typeSpec::SPEC_OVERLAYABLE);
452 }
453
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700454 const size_t config_count = entry->values.size();
455 for (size_t i = 0; i < config_count; i++) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700456 const ConfigDescription& config = entry->values[i]->config;
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700457 for (size_t j = i + 1; j < config_count; j++) {
458 config_masks[entry->id.value()] |=
459 util::HostToDevice32(config.diff(entry->values[j]->config));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700460 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700461 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700462 }
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700463 type_spec_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700464 return true;
465 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700466
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700467 bool FlattenTypes(BigBuffer* buffer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700468 // Sort the types by their IDs. They will be inserted into the StringPool in
469 // this order.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700470 std::vector<ResourceTableType*> sorted_types = CollectAndSortTypes();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700471
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700472 size_t expected_type_id = 1;
473 for (ResourceTableType* type : sorted_types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 // If there is a gap in the type IDs, fill in the StringPool
475 // with empty values until we reach the ID we expect.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700476 while (type->id.value() > expected_type_id) {
477 std::stringstream type_name;
478 type_name << "?" << expected_type_id;
479 type_pool_.MakeRef(type_name.str());
480 expected_type_id++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700481 }
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700482 expected_type_id++;
Adam Lesinski93190b72017-11-03 15:20:17 -0700483 type_pool_.MakeRef(to_string(type->type));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700484
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700485 std::vector<ResourceEntry*> sorted_entries = CollectAndSortEntries(type);
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800486 if (sorted_entries.empty()) {
487 continue;
488 }
489
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700490 if (!FlattenTypeSpec(type, &sorted_entries, buffer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 return false;
492 }
493
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800494 // Since the entries are sorted by ID, the last ID will be the largest.
495 const size_t num_entries = sorted_entries.back()->id.value() + 1;
496
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700497 // The binary resource table lists resource entries for each
498 // configuration.
499 // We store them inverted, where a resource entry lists the values for
500 // each
501 // configuration available. Here we reverse this to match the binary
502 // table.
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800503 std::map<ConfigDescription, std::vector<FlatEntry>> config_to_entry_list_map;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504
Luke Nicholsonb0643302017-12-01 15:29:03 -0800505 // hardcoded string uses characters which make it an invalid resource name
506 const std::string obfuscated_resource_name = "0_resource_name_obfuscated";
507
508 for (ResourceEntry* entry : sorted_entries) {
509 uint32_t local_key_index;
510 if (!collapse_key_stringpool_ ||
511 whitelisted_resources_.find(entry->name) != whitelisted_resources_.end()) {
512 local_key_index = (uint32_t)key_pool_.MakeRef(entry->name).index();
513 } else {
514 // resource isn't whitelisted, add it as obfuscated value
515 local_key_index = (uint32_t)key_pool_.MakeRef(obfuscated_resource_name).index();
516 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700517 // Group values by configuration.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700518 for (auto& config_value : entry->values) {
519 config_to_entry_list_map[config_value->config].push_back(
Luke Nicholsonb0643302017-12-01 15:29:03 -0800520 FlatEntry{entry, config_value->value.get(), local_key_index});
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700521 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700523
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 // Flatten a configuration value.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700525 for (auto& entry : config_to_entry_list_map) {
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800526 if (!FlattenConfig(type, entry.first, num_entries, &entry.second, buffer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700528 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700530 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700531 return true;
532 }
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700533
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800534 void FlattenLibrarySpec(BigBuffer* buffer) {
535 ChunkWriter lib_writer(buffer);
536 ResTable_lib_header* lib_header =
537 lib_writer.StartChunk<ResTable_lib_header>(RES_TABLE_LIBRARY_TYPE);
538
539 const size_t num_entries = (package_->id.value() == 0x00 ? 1 : 0) + shared_libs_->size();
540 CHECK(num_entries > 0);
541
542 lib_header->count = util::HostToDevice32(num_entries);
543
544 ResTable_lib_entry* lib_entry = buffer->NextBlock<ResTable_lib_entry>(num_entries);
545 if (package_->id.value() == 0x00) {
546 // Add this package
547 lib_entry->packageId = util::HostToDevice32(0x00);
548 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
549 util::Utf8ToUtf16(package_->name));
550 ++lib_entry;
551 }
552
553 for (auto& map_entry : *shared_libs_) {
554 lib_entry->packageId = util::HostToDevice32(map_entry.first);
555 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
556 util::Utf8ToUtf16(map_entry.second));
557 ++lib_entry;
558 }
559 lib_writer.Finish();
560 }
561
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800562 IAaptContext* context_;
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700563 IDiagnostics* diag_;
564 ResourceTablePackage* package_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800565 const std::map<size_t, std::string>* shared_libs_;
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800566 bool use_sparse_entries_;
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700567 StringPool type_pool_;
568 StringPool key_pool_;
Luke Nicholsonb0643302017-12-01 15:29:03 -0800569 bool collapse_key_stringpool_;
570 const std::set<std::string>& whitelisted_resources_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700571};
572
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573} // namespace
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700574
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700575bool TableFlattener::Consume(IAaptContext* context, ResourceTable* table) {
Adam Lesinski060b53d2017-07-28 17:10:35 -0700576 // We must do this before writing the resources, since the string pool IDs may change.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700577 table->string_pool.Prune();
Adam Lesinski060b53d2017-07-28 17:10:35 -0700578 table->string_pool.Sort([](const StringPool::Context& a, const StringPool::Context& b) -> int {
579 int diff = util::compare(a.priority, b.priority);
580 if (diff == 0) {
581 diff = a.config.compare(b.config);
582 }
583 return diff;
584 });
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700585
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700586 // Write the ResTable header.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700587 ChunkWriter table_writer(buffer_);
Adam Lesinski4ca56972017-04-26 21:49:53 -0700588 ResTable_header* table_header = table_writer.StartChunk<ResTable_header>(RES_TABLE_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700589 table_header->packageCount = util::HostToDevice32(table->packages.size());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700590
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591 // Flatten the values string pool.
Ryan Mitchella15c2a82018-03-26 11:05:31 -0700592 StringPool::FlattenUtf8(table_writer.buffer(), table->string_pool,
593 context->GetDiagnostics());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700594
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700595 BigBuffer package_buffer(1024);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700596
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700597 // Flatten each package.
598 for (auto& package : table->packages) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700599 if (context->GetPackageType() == PackageType::kApp) {
600 // Write a self mapping entry for this package if the ID is non-standard (0x7f).
601 const uint8_t package_id = package->id.value();
602 if (package_id != kFrameworkPackageId && package_id != kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800603 auto result = table->included_packages_.insert({package_id, package->name});
604 if (!result.second && result.first->second != package->name) {
605 // A mapping for this package ID already exists, and is a different package. Error!
606 context->GetDiagnostics()->Error(
607 DiagMessage() << android::base::StringPrintf(
608 "can't map package ID %02x to '%s'. Already mapped to '%s'", package_id,
609 package->name.c_str(), result.first->second.c_str()));
610 return false;
611 }
Adam Lesinski8780eb62017-10-31 17:44:39 -0700612 }
613 }
614
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800615 PackageFlattener flattener(context, package.get(), &table->included_packages_,
Luke Nicholsonb0643302017-12-01 15:29:03 -0800616 options_.use_sparse_entries, options_.collapse_key_stringpool,
617 options_.whitelisted_resources);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700618 if (!flattener.FlattenPackage(&package_buffer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700620 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700621 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700622
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623 // Finally merge all the packages into the main buffer.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700624 table_writer.buffer()->AppendBuffer(std::move(package_buffer));
625 table_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700627}
628
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700629} // namespace aapt