blob: 4aadadce5019819746802dd873e1ec34a52a70e1 [file] [log] [blame]
Adam Lesinski6f6ceb72014-11-14 14:48:12 -08001/*
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 "BigBuffer.h"
18#include "ConfigDescription.h"
19#include "Logger.h"
20#include "ResourceTable.h"
21#include "ResourceTypeExtensions.h"
22#include "ResourceValues.h"
23#include "StringPool.h"
24#include "TableFlattener.h"
25#include "Util.h"
26
Adam Lesinskica2fc352015-04-03 12:08:26 -070027#include <algorithm>
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080028#include <androidfw/ResourceTypes.h>
29#include <sstream>
30
31namespace aapt {
32
33struct FlatEntry {
34 const ResourceEntry& entry;
35 const Value& value;
36 uint32_t entryKey;
37 uint32_t sourcePathKey;
38 uint32_t sourceLine;
39};
40
41/**
42 * Visitor that knows how to encode Map values.
43 */
44class MapFlattener : public ConstValueVisitor {
45public:
Adam Lesinskid5c4f872015-04-21 13:56:10 -070046 MapFlattener(BigBuffer* out, const FlatEntry& flatEntry, SymbolEntryVector* symbols) :
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080047 mOut(out), mSymbols(symbols) {
48 mMap = mOut->nextBlock<android::ResTable_map_entry>();
49 mMap->key.index = flatEntry.entryKey;
50 mMap->flags = android::ResTable_entry::FLAG_COMPLEX;
51 if (flatEntry.entry.publicStatus.isPublic) {
52 mMap->flags |= android::ResTable_entry::FLAG_PUBLIC;
53 }
54 if (flatEntry.value.isWeak()) {
55 mMap->flags |= android::ResTable_entry::FLAG_WEAK;
56 }
57
58 ResTable_entry_source* sourceBlock = mOut->nextBlock<ResTable_entry_source>();
59 sourceBlock->pathIndex = flatEntry.sourcePathKey;
60 sourceBlock->line = flatEntry.sourceLine;
61
62 mMap->size = sizeof(*mMap) + sizeof(*sourceBlock);
63 }
64
65 void flattenParent(const Reference& ref) {
66 if (!ref.id.isValid()) {
Adam Lesinskid5c4f872015-04-21 13:56:10 -070067 mSymbols->push_back({
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080068 ResourceNameRef(ref.name),
69 (mOut->size() - mMap->size) + sizeof(*mMap) - sizeof(android::ResTable_entry)
70 });
71 }
72 mMap->parent.ident = ref.id.id;
73 }
74
75 void flattenEntry(const Reference& key, const Item& value) {
76 mMap->count++;
77
78 android::ResTable_map* outMapEntry = mOut->nextBlock<android::ResTable_map>();
79
80 // Write the key.
81 if (!Res_INTERNALID(key.id.id) && !key.id.isValid()) {
Adam Lesinskid5c4f872015-04-21 13:56:10 -070082 mSymbols->push_back(std::make_pair(ResourceNameRef(key.name),
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080083 mOut->size() - sizeof(*outMapEntry)));
84 }
85 outMapEntry->name.ident = key.id.id;
86
87 // Write the value.
88 value.flatten(outMapEntry->value);
89
90 if (outMapEntry->value.data == 0x0) {
91 visitFunc<Reference>(value, [&](const Reference& reference) {
Adam Lesinskid5c4f872015-04-21 13:56:10 -070092 mSymbols->push_back(std::make_pair(ResourceNameRef(reference.name),
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080093 mOut->size() - sizeof(outMapEntry->value.data)));
94 });
95 }
96 outMapEntry->value.size = sizeof(outMapEntry->value);
97 }
98
99 static bool compareStyleEntries(const Style::Entry* lhs, const Style::Entry* rhs) {
100 return lhs->key.id < rhs->key.id;
101 }
102
103 void visit(const Style& style, ValueVisitorArgs&) override {
104 if (style.parent.name.isValid()) {
105 flattenParent(style.parent);
106 }
107
108 // First sort the entries by ID.
109 std::vector<const Style::Entry*> sortedEntries;
110 for (const auto& styleEntry : style.entries) {
111 auto iter = std::lower_bound(sortedEntries.begin(), sortedEntries.end(),
112 &styleEntry, compareStyleEntries);
113 sortedEntries.insert(iter, &styleEntry);
114 }
115
116 for (const Style::Entry* styleEntry : sortedEntries) {
117 flattenEntry(styleEntry->key, *styleEntry->value);
118 }
119 }
120
121 void visit(const Attribute& attr, ValueVisitorArgs&) override {
122 android::Res_value tempVal;
123 tempVal.dataType = android::Res_value::TYPE_INT_DEC;
124 tempVal.data = attr.typeMask;
125 flattenEntry(Reference(ResourceId{android::ResTable_map::ATTR_TYPE}),
126 BinaryPrimitive(tempVal));
127
128 for (const auto& symbol : attr.symbols) {
129 tempVal.data = symbol.value;
130 flattenEntry(symbol.symbol, BinaryPrimitive(tempVal));
131 }
132 }
133
134 void visit(const Styleable& styleable, ValueVisitorArgs&) override {
135 for (const auto& attr : styleable.entries) {
136 flattenEntry(attr, BinaryPrimitive(android::Res_value{}));
137 }
138 }
139
140 void visit(const Array& array, ValueVisitorArgs&) override {
141 for (const auto& item : array.items) {
142 flattenEntry({}, *item);
143 }
144 }
145
146 void visit(const Plural& plural, ValueVisitorArgs&) override {
147 const size_t count = plural.values.size();
148 for (size_t i = 0; i < count; i++) {
149 if (!plural.values[i]) {
150 continue;
151 }
152
153 ResourceId q;
154 switch (i) {
155 case Plural::Zero:
156 q.id = android::ResTable_map::ATTR_ZERO;
157 break;
158
159 case Plural::One:
160 q.id = android::ResTable_map::ATTR_ONE;
161 break;
162
163 case Plural::Two:
164 q.id = android::ResTable_map::ATTR_TWO;
165 break;
166
167 case Plural::Few:
168 q.id = android::ResTable_map::ATTR_FEW;
169 break;
170
171 case Plural::Many:
172 q.id = android::ResTable_map::ATTR_MANY;
173 break;
174
175 case Plural::Other:
176 q.id = android::ResTable_map::ATTR_OTHER;
177 break;
178
179 default:
180 assert(false);
181 break;
182 }
183
184 flattenEntry(Reference(q), *plural.values[i]);
185 }
186 }
187
188private:
189 BigBuffer* mOut;
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700190 SymbolEntryVector* mSymbols;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800191 android::ResTable_map_entry* mMap;
192};
193
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700194/**
195 * Flattens a value, with special handling for References.
196 */
197struct ValueFlattener : ConstValueVisitor {
198 ValueFlattener(BigBuffer* out, SymbolEntryVector* symbols) :
199 result(false), mOut(out), mOutValue(nullptr), mSymbols(symbols) {
200 mOutValue = mOut->nextBlock<android::Res_value>();
201 }
202
203 virtual void visit(const Reference& ref, ValueVisitorArgs& a) override {
204 visitItem(ref, a);
205 if (mOutValue->data == 0x0) {
206 mSymbols->push_back({
207 ResourceNameRef(ref.name),
208 mOut->size() - sizeof(mOutValue->data)});
209 }
210 }
211
212 virtual void visitItem(const Item& item, ValueVisitorArgs&) override {
213 result = item.flatten(*mOutValue);
214 mOutValue->size = sizeof(*mOutValue);
215 }
216
217 bool result;
218
219private:
220 BigBuffer* mOut;
221 android::Res_value* mOutValue;
222 SymbolEntryVector* mSymbols;
223};
224
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800225TableFlattener::TableFlattener(Options options)
226: mOptions(options) {
227}
228
229bool TableFlattener::flattenValue(BigBuffer* out, const FlatEntry& flatEntry,
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700230 SymbolEntryVector* symbols) {
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800231 if (flatEntry.value.isItem()) {
232 android::ResTable_entry* entry = out->nextBlock<android::ResTable_entry>();
233
234 if (flatEntry.entry.publicStatus.isPublic) {
235 entry->flags |= android::ResTable_entry::FLAG_PUBLIC;
236 }
237
238 if (flatEntry.value.isWeak()) {
239 entry->flags |= android::ResTable_entry::FLAG_WEAK;
240 }
241
242 entry->key.index = flatEntry.entryKey;
243 entry->size = sizeof(*entry);
244
245 if (mOptions.useExtendedChunks) {
246 // Write the extra source block. This will be ignored by
247 // the Android runtime.
248 ResTable_entry_source* sourceBlock = out->nextBlock<ResTable_entry_source>();
249 sourceBlock->pathIndex = flatEntry.sourcePathKey;
250 sourceBlock->line = flatEntry.sourceLine;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800251 entry->size += sizeof(*sourceBlock);
252 }
253
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700254 const Item* item = static_cast<const Item*>(&flatEntry.value);
255 ValueFlattener flattener(out, symbols);
256 item->accept(flattener, {});
257 return flattener.result;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800258 }
259
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700260 MapFlattener flattener(out, flatEntry, symbols);
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800261 flatEntry.value.accept(flattener, {});
262 return true;
263}
264
265bool TableFlattener::flatten(BigBuffer* out, const ResourceTable& table) {
266 const size_t beginning = out->size();
267
268 if (table.getPackage().size() == 0) {
269 Logger::error()
270 << "ResourceTable has no package name."
271 << std::endl;
272 return false;
273 }
274
275 if (table.getPackageId() == ResourceTable::kUnsetPackageId) {
276 Logger::error()
277 << "ResourceTable has no package ID set."
278 << std::endl;
279 return false;
280 }
281
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700282 SymbolEntryVector symbolEntries;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800283
284 StringPool typePool;
285 StringPool keyPool;
286 StringPool sourcePool;
287
288 // Sort the types by their IDs. They will be inserted into the StringPool
289 // in this order.
290 std::vector<ResourceTableType*> sortedTypes;
291 for (const auto& type : table) {
292 if (type->type == ResourceType::kStyleable && !mOptions.useExtendedChunks) {
293 continue;
294 }
295
296 auto iter = std::lower_bound(std::begin(sortedTypes), std::end(sortedTypes), type.get(),
297 [](const ResourceTableType* lhs, const ResourceTableType* rhs) -> bool {
298 return lhs->typeId < rhs->typeId;
299 });
300 sortedTypes.insert(iter, type.get());
301 }
302
303 BigBuffer typeBlock(1024);
304 size_t expectedTypeId = 1;
305 for (const ResourceTableType* type : sortedTypes) {
306 if (type->typeId == ResourceTableType::kUnsetTypeId
307 || type->typeId == 0) {
308 Logger::error()
309 << "resource type '"
310 << type->type
311 << "' from package '"
312 << table.getPackage()
313 << "' has no ID."
314 << std::endl;
315 return false;
316 }
317
318 // If there is a gap in the type IDs, fill in the StringPool
319 // with empty values until we reach the ID we expect.
320 while (type->typeId > expectedTypeId) {
321 std::u16string typeName(u"?");
322 typeName += expectedTypeId;
323 typePool.makeRef(typeName);
324 expectedTypeId++;
325 }
326 expectedTypeId++;
327 typePool.makeRef(toString(type->type));
328
329 android::ResTable_typeSpec* spec = typeBlock.nextBlock<android::ResTable_typeSpec>();
330 spec->header.type = android::RES_TABLE_TYPE_SPEC_TYPE;
331 spec->header.headerSize = sizeof(*spec);
332 spec->header.size = spec->header.headerSize + (type->entries.size() * sizeof(uint32_t));
333 spec->id = type->typeId;
334 spec->entryCount = type->entries.size();
335
336 // Reserve space for the masks of each resource in this type. These
337 // show for which configuration axis the resource changes.
338 uint32_t* configMasks = typeBlock.nextBlock<uint32_t>(type->entries.size());
339
340 // Sort the entries by entry ID and write their configuration masks.
341 std::vector<ResourceEntry*> entries;
342 const size_t entryCount = type->entries.size();
343 for (size_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
344 const auto& entry = type->entries[entryIndex];
345
346 if (entry->entryId == ResourceEntry::kUnsetEntryId) {
347 Logger::error()
348 << "resource '"
349 << ResourceName{ table.getPackage(), type->type, entry->name }
350 << "' has no ID."
351 << std::endl;
352 return false;
353 }
354
355 auto iter = std::lower_bound(std::begin(entries), std::end(entries), entry.get(),
356 [](const ResourceEntry* lhs, const ResourceEntry* rhs) -> bool {
357 return lhs->entryId < rhs->entryId;
358 });
359 entries.insert(iter, entry.get());
360
361 // Populate the config masks for this entry.
362 if (entry->publicStatus.isPublic) {
363 configMasks[entry->entryId] |= android::ResTable_typeSpec::SPEC_PUBLIC;
364 }
365
366 const size_t configCount = entry->values.size();
367 for (size_t i = 0; i < configCount; i++) {
368 const ConfigDescription& config = entry->values[i].config;
369 for (size_t j = i + 1; j < configCount; j++) {
370 configMasks[entry->entryId] |= config.diff(entry->values[j].config);
371 }
372 }
373 }
374
375 // The binary resource table lists resource entries for each configuration.
376 // We store them inverted, where a resource entry lists the values for each
377 // configuration available. Here we reverse this to match the binary table.
378 std::map<ConfigDescription, std::vector<FlatEntry>> data;
379 for (const ResourceEntry* entry : entries) {
380 size_t keyIndex = keyPool.makeRef(entry->name).getIndex();
381
382 if (keyIndex > std::numeric_limits<uint32_t>::max()) {
383 Logger::error()
384 << "resource key string pool exceeded max size."
385 << std::endl;
386 return false;
387 }
388
389 for (const auto& configValue : entry->values) {
390 data[configValue.config].push_back(FlatEntry{
391 *entry,
392 *configValue.value,
393 static_cast<uint32_t>(keyIndex),
394 static_cast<uint32_t>(sourcePool.makeRef(util::utf8ToUtf16(
395 configValue.source.path)).getIndex()),
396 static_cast<uint32_t>(configValue.source.line)
397 });
398 }
399 }
400
401 // Begin flattening a configuration for the current type.
402 for (const auto& entry : data) {
403 const size_t typeHeaderStart = typeBlock.size();
404 android::ResTable_type* typeHeader = typeBlock.nextBlock<android::ResTable_type>();
405 typeHeader->header.type = android::RES_TABLE_TYPE_TYPE;
406 typeHeader->header.headerSize = sizeof(*typeHeader);
407 typeHeader->id = type->typeId;
408 typeHeader->entryCount = type->entries.size();
409 typeHeader->entriesStart = typeHeader->header.headerSize
410 + (sizeof(uint32_t) * type->entries.size());
411 typeHeader->config = entry.first;
412
413 uint32_t* indices = typeBlock.nextBlock<uint32_t>(type->entries.size());
414 memset(indices, 0xff, type->entries.size() * sizeof(uint32_t));
415
416 const size_t entryStart = typeBlock.size();
417 for (const FlatEntry& flatEntry : entry.second) {
418 assert(flatEntry.entry.entryId < type->entries.size());
419 indices[flatEntry.entry.entryId] = typeBlock.size() - entryStart;
Adam Lesinskid5c4f872015-04-21 13:56:10 -0700420 if (!flattenValue(&typeBlock, flatEntry, &symbolEntries)) {
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800421 Logger::error()
422 << "failed to flatten resource '"
423 << ResourceNameRef {
424 table.getPackage(), type->type, flatEntry.entry.name }
425 << "' for configuration '"
426 << entry.first
427 << "'."
428 << std::endl;
429 return false;
430 }
431 }
432
433 typeBlock.align4();
434 typeHeader->header.size = typeBlock.size() - typeHeaderStart;
435 }
436 }
437
438 const size_t beforeTable = out->size();
439 android::ResTable_header* header = out->nextBlock<android::ResTable_header>();
440 header->header.type = android::RES_TABLE_TYPE;
441 header->header.headerSize = sizeof(*header);
442 header->packageCount = 1;
443
444 SymbolTable_entry* symbolEntryData = nullptr;
445 if (!symbolEntries.empty() && mOptions.useExtendedChunks) {
446 const size_t beforeSymbolTable = out->size();
447 StringPool symbolPool;
448 SymbolTable_header* symbolHeader = out->nextBlock<SymbolTable_header>();
449 symbolHeader->header.type = RES_TABLE_SYMBOL_TABLE_TYPE;
450 symbolHeader->header.headerSize = sizeof(*symbolHeader);
451 symbolHeader->count = symbolEntries.size();
452
453 symbolEntryData = out->nextBlock<SymbolTable_entry>(symbolHeader->count);
454
455 size_t i = 0;
456 for (const auto& entry : symbolEntries) {
457 symbolEntryData[i].offset = entry.second;
458 StringPool::Ref ref = symbolPool.makeRef(
459 entry.first.package.toString() + u":" +
460 toString(entry.first.type).toString() + u"/" +
461 entry.first.entry.toString());
462 symbolEntryData[i].stringIndex = ref.getIndex();
463 i++;
464 }
465
466 StringPool::flattenUtf8(out, symbolPool);
467 out->align4();
468 symbolHeader->header.size = out->size() - beforeSymbolTable;
469 }
470
471 if (sourcePool.size() > 0 && mOptions.useExtendedChunks) {
472 const size_t beforeSourcePool = out->size();
473 android::ResChunk_header* sourceHeader = out->nextBlock<android::ResChunk_header>();
474 sourceHeader->type = RES_TABLE_SOURCE_POOL_TYPE;
475 sourceHeader->headerSize = sizeof(*sourceHeader);
476 StringPool::flattenUtf8(out, sourcePool);
477 out->align4();
478 sourceHeader->size = out->size() - beforeSourcePool;
479 }
480
481 StringPool::flattenUtf8(out, table.getValueStringPool());
482
483 const size_t beforePackageIndex = out->size();
484 android::ResTable_package* package = out->nextBlock<android::ResTable_package>();
485 package->header.type = android::RES_TABLE_PACKAGE_TYPE;
486 package->header.headerSize = sizeof(*package);
487
488 if (table.getPackageId() > std::numeric_limits<uint8_t>::max()) {
489 Logger::error()
490 << "package ID 0x'"
491 << std::hex << table.getPackageId() << std::dec
492 << "' is invalid."
493 << std::endl;
494 return false;
495 }
496 package->id = table.getPackageId();
497
498 if (table.getPackage().size() >= sizeof(package->name) / sizeof(package->name[0])) {
499 Logger::error()
500 << "package name '"
501 << table.getPackage()
502 << "' is too long."
503 << std::endl;
504 return false;
505 }
506 memcpy(package->name, reinterpret_cast<const uint16_t*>(table.getPackage().data()),
507 table.getPackage().length() * sizeof(char16_t));
508 package->name[table.getPackage().length()] = 0;
509
510 package->typeStrings = package->header.headerSize;
511 StringPool::flattenUtf8(out, typePool);
512 package->keyStrings = out->size() - beforePackageIndex;
513 StringPool::flattenUtf8(out, keyPool);
514
515 if (symbolEntryData != nullptr) {
516 for (size_t i = 0; i < symbolEntries.size(); i++) {
517 symbolEntryData[i].offset += out->size() - beginning;
518 }
519 }
520
521 out->appendBuffer(std::move(typeBlock));
522
523 package->header.size = out->size() - beforePackageIndex;
524 header->header.size = out->size() - beforeTable;
525 return true;
526}
527
528} // namespace aapt