blob: c3061850f0b233b04a458b6122fa9ff1b2eab8ce [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
27#include <androidfw/ResourceTypes.h>
28#include <sstream>
29
30namespace aapt {
31
32struct FlatEntry {
33 const ResourceEntry& entry;
34 const Value& value;
35 uint32_t entryKey;
36 uint32_t sourcePathKey;
37 uint32_t sourceLine;
38};
39
40/**
41 * Visitor that knows how to encode Map values.
42 */
43class MapFlattener : public ConstValueVisitor {
44public:
45 MapFlattener(BigBuffer* out, const FlatEntry& flatEntry,
46 std::vector<std::pair<ResourceNameRef, uint32_t>>& symbols) :
47 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()) {
67 mSymbols.push_back({
68 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()) {
82 mSymbols.push_back(std::make_pair(ResourceNameRef(key.name),
83 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) {
92 mSymbols.push_back(std::make_pair(ResourceNameRef(reference.name),
93 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;
190 std::vector<std::pair<ResourceNameRef, uint32_t>>& mSymbols;
191 android::ResTable_map_entry* mMap;
192};
193
194TableFlattener::TableFlattener(Options options)
195: mOptions(options) {
196}
197
198bool TableFlattener::flattenValue(BigBuffer* out, const FlatEntry& flatEntry,
199 std::vector<std::pair<ResourceNameRef, uint32_t>>& symbolEntries) {
200 if (flatEntry.value.isItem()) {
201 android::ResTable_entry* entry = out->nextBlock<android::ResTable_entry>();
202
203 if (flatEntry.entry.publicStatus.isPublic) {
204 entry->flags |= android::ResTable_entry::FLAG_PUBLIC;
205 }
206
207 if (flatEntry.value.isWeak()) {
208 entry->flags |= android::ResTable_entry::FLAG_WEAK;
209 }
210
211 entry->key.index = flatEntry.entryKey;
212 entry->size = sizeof(*entry);
213
214 if (mOptions.useExtendedChunks) {
215 // Write the extra source block. This will be ignored by
216 // the Android runtime.
217 ResTable_entry_source* sourceBlock = out->nextBlock<ResTable_entry_source>();
218 sourceBlock->pathIndex = flatEntry.sourcePathKey;
219 sourceBlock->line = flatEntry.sourceLine;
220
221 entry->size += sizeof(*sourceBlock);
222 }
223
224 android::Res_value* outValue = out->nextBlock<android::Res_value>();
225
226 const Item& item = static_cast<const Item&>(flatEntry.value);
227 if (!item.flatten(*outValue)) {
228 return false;
229 }
230
231 if (outValue->data == 0x0) {
232 visitFunc<Reference>(item, [&](const Reference& reference) {
233 symbolEntries.push_back({
234 ResourceNameRef(reference.name),
235 out->size() - sizeof(outValue->data)
236 });
237 });
238 }
239 outValue->size = sizeof(*outValue);
240 return true;
241 }
242
243 MapFlattener flattener(out, flatEntry, symbolEntries);
244 flatEntry.value.accept(flattener, {});
245 return true;
246}
247
248bool TableFlattener::flatten(BigBuffer* out, const ResourceTable& table) {
249 const size_t beginning = out->size();
250
251 if (table.getPackage().size() == 0) {
252 Logger::error()
253 << "ResourceTable has no package name."
254 << std::endl;
255 return false;
256 }
257
258 if (table.getPackageId() == ResourceTable::kUnsetPackageId) {
259 Logger::error()
260 << "ResourceTable has no package ID set."
261 << std::endl;
262 return false;
263 }
264
265 std::vector<std::pair<ResourceNameRef, uint32_t>> symbolEntries;
266
267 StringPool typePool;
268 StringPool keyPool;
269 StringPool sourcePool;
270
271 // Sort the types by their IDs. They will be inserted into the StringPool
272 // in this order.
273 std::vector<ResourceTableType*> sortedTypes;
274 for (const auto& type : table) {
275 if (type->type == ResourceType::kStyleable && !mOptions.useExtendedChunks) {
276 continue;
277 }
278
279 auto iter = std::lower_bound(std::begin(sortedTypes), std::end(sortedTypes), type.get(),
280 [](const ResourceTableType* lhs, const ResourceTableType* rhs) -> bool {
281 return lhs->typeId < rhs->typeId;
282 });
283 sortedTypes.insert(iter, type.get());
284 }
285
286 BigBuffer typeBlock(1024);
287 size_t expectedTypeId = 1;
288 for (const ResourceTableType* type : sortedTypes) {
289 if (type->typeId == ResourceTableType::kUnsetTypeId
290 || type->typeId == 0) {
291 Logger::error()
292 << "resource type '"
293 << type->type
294 << "' from package '"
295 << table.getPackage()
296 << "' has no ID."
297 << std::endl;
298 return false;
299 }
300
301 // If there is a gap in the type IDs, fill in the StringPool
302 // with empty values until we reach the ID we expect.
303 while (type->typeId > expectedTypeId) {
304 std::u16string typeName(u"?");
305 typeName += expectedTypeId;
306 typePool.makeRef(typeName);
307 expectedTypeId++;
308 }
309 expectedTypeId++;
310 typePool.makeRef(toString(type->type));
311
312 android::ResTable_typeSpec* spec = typeBlock.nextBlock<android::ResTable_typeSpec>();
313 spec->header.type = android::RES_TABLE_TYPE_SPEC_TYPE;
314 spec->header.headerSize = sizeof(*spec);
315 spec->header.size = spec->header.headerSize + (type->entries.size() * sizeof(uint32_t));
316 spec->id = type->typeId;
317 spec->entryCount = type->entries.size();
318
319 // Reserve space for the masks of each resource in this type. These
320 // show for which configuration axis the resource changes.
321 uint32_t* configMasks = typeBlock.nextBlock<uint32_t>(type->entries.size());
322
323 // Sort the entries by entry ID and write their configuration masks.
324 std::vector<ResourceEntry*> entries;
325 const size_t entryCount = type->entries.size();
326 for (size_t entryIndex = 0; entryIndex < entryCount; entryIndex++) {
327 const auto& entry = type->entries[entryIndex];
328
329 if (entry->entryId == ResourceEntry::kUnsetEntryId) {
330 Logger::error()
331 << "resource '"
332 << ResourceName{ table.getPackage(), type->type, entry->name }
333 << "' has no ID."
334 << std::endl;
335 return false;
336 }
337
338 auto iter = std::lower_bound(std::begin(entries), std::end(entries), entry.get(),
339 [](const ResourceEntry* lhs, const ResourceEntry* rhs) -> bool {
340 return lhs->entryId < rhs->entryId;
341 });
342 entries.insert(iter, entry.get());
343
344 // Populate the config masks for this entry.
345 if (entry->publicStatus.isPublic) {
346 configMasks[entry->entryId] |= android::ResTable_typeSpec::SPEC_PUBLIC;
347 }
348
349 const size_t configCount = entry->values.size();
350 for (size_t i = 0; i < configCount; i++) {
351 const ConfigDescription& config = entry->values[i].config;
352 for (size_t j = i + 1; j < configCount; j++) {
353 configMasks[entry->entryId] |= config.diff(entry->values[j].config);
354 }
355 }
356 }
357
358 // The binary resource table lists resource entries for each configuration.
359 // We store them inverted, where a resource entry lists the values for each
360 // configuration available. Here we reverse this to match the binary table.
361 std::map<ConfigDescription, std::vector<FlatEntry>> data;
362 for (const ResourceEntry* entry : entries) {
363 size_t keyIndex = keyPool.makeRef(entry->name).getIndex();
364
365 if (keyIndex > std::numeric_limits<uint32_t>::max()) {
366 Logger::error()
367 << "resource key string pool exceeded max size."
368 << std::endl;
369 return false;
370 }
371
372 for (const auto& configValue : entry->values) {
373 data[configValue.config].push_back(FlatEntry{
374 *entry,
375 *configValue.value,
376 static_cast<uint32_t>(keyIndex),
377 static_cast<uint32_t>(sourcePool.makeRef(util::utf8ToUtf16(
378 configValue.source.path)).getIndex()),
379 static_cast<uint32_t>(configValue.source.line)
380 });
381 }
382 }
383
384 // Begin flattening a configuration for the current type.
385 for (const auto& entry : data) {
386 const size_t typeHeaderStart = typeBlock.size();
387 android::ResTable_type* typeHeader = typeBlock.nextBlock<android::ResTable_type>();
388 typeHeader->header.type = android::RES_TABLE_TYPE_TYPE;
389 typeHeader->header.headerSize = sizeof(*typeHeader);
390 typeHeader->id = type->typeId;
391 typeHeader->entryCount = type->entries.size();
392 typeHeader->entriesStart = typeHeader->header.headerSize
393 + (sizeof(uint32_t) * type->entries.size());
394 typeHeader->config = entry.first;
395
396 uint32_t* indices = typeBlock.nextBlock<uint32_t>(type->entries.size());
397 memset(indices, 0xff, type->entries.size() * sizeof(uint32_t));
398
399 const size_t entryStart = typeBlock.size();
400 for (const FlatEntry& flatEntry : entry.second) {
401 assert(flatEntry.entry.entryId < type->entries.size());
402 indices[flatEntry.entry.entryId] = typeBlock.size() - entryStart;
403 if (!flattenValue(&typeBlock, flatEntry, symbolEntries)) {
404 Logger::error()
405 << "failed to flatten resource '"
406 << ResourceNameRef {
407 table.getPackage(), type->type, flatEntry.entry.name }
408 << "' for configuration '"
409 << entry.first
410 << "'."
411 << std::endl;
412 return false;
413 }
414 }
415
416 typeBlock.align4();
417 typeHeader->header.size = typeBlock.size() - typeHeaderStart;
418 }
419 }
420
421 const size_t beforeTable = out->size();
422 android::ResTable_header* header = out->nextBlock<android::ResTable_header>();
423 header->header.type = android::RES_TABLE_TYPE;
424 header->header.headerSize = sizeof(*header);
425 header->packageCount = 1;
426
427 SymbolTable_entry* symbolEntryData = nullptr;
428 if (!symbolEntries.empty() && mOptions.useExtendedChunks) {
429 const size_t beforeSymbolTable = out->size();
430 StringPool symbolPool;
431 SymbolTable_header* symbolHeader = out->nextBlock<SymbolTable_header>();
432 symbolHeader->header.type = RES_TABLE_SYMBOL_TABLE_TYPE;
433 symbolHeader->header.headerSize = sizeof(*symbolHeader);
434 symbolHeader->count = symbolEntries.size();
435
436 symbolEntryData = out->nextBlock<SymbolTable_entry>(symbolHeader->count);
437
438 size_t i = 0;
439 for (const auto& entry : symbolEntries) {
440 symbolEntryData[i].offset = entry.second;
441 StringPool::Ref ref = symbolPool.makeRef(
442 entry.first.package.toString() + u":" +
443 toString(entry.first.type).toString() + u"/" +
444 entry.first.entry.toString());
445 symbolEntryData[i].stringIndex = ref.getIndex();
446 i++;
447 }
448
449 StringPool::flattenUtf8(out, symbolPool);
450 out->align4();
451 symbolHeader->header.size = out->size() - beforeSymbolTable;
452 }
453
454 if (sourcePool.size() > 0 && mOptions.useExtendedChunks) {
455 const size_t beforeSourcePool = out->size();
456 android::ResChunk_header* sourceHeader = out->nextBlock<android::ResChunk_header>();
457 sourceHeader->type = RES_TABLE_SOURCE_POOL_TYPE;
458 sourceHeader->headerSize = sizeof(*sourceHeader);
459 StringPool::flattenUtf8(out, sourcePool);
460 out->align4();
461 sourceHeader->size = out->size() - beforeSourcePool;
462 }
463
464 StringPool::flattenUtf8(out, table.getValueStringPool());
465
466 const size_t beforePackageIndex = out->size();
467 android::ResTable_package* package = out->nextBlock<android::ResTable_package>();
468 package->header.type = android::RES_TABLE_PACKAGE_TYPE;
469 package->header.headerSize = sizeof(*package);
470
471 if (table.getPackageId() > std::numeric_limits<uint8_t>::max()) {
472 Logger::error()
473 << "package ID 0x'"
474 << std::hex << table.getPackageId() << std::dec
475 << "' is invalid."
476 << std::endl;
477 return false;
478 }
479 package->id = table.getPackageId();
480
481 if (table.getPackage().size() >= sizeof(package->name) / sizeof(package->name[0])) {
482 Logger::error()
483 << "package name '"
484 << table.getPackage()
485 << "' is too long."
486 << std::endl;
487 return false;
488 }
489 memcpy(package->name, reinterpret_cast<const uint16_t*>(table.getPackage().data()),
490 table.getPackage().length() * sizeof(char16_t));
491 package->name[table.getPackage().length()] = 0;
492
493 package->typeStrings = package->header.headerSize;
494 StringPool::flattenUtf8(out, typePool);
495 package->keyStrings = out->size() - beforePackageIndex;
496 StringPool::flattenUtf8(out, keyPool);
497
498 if (symbolEntryData != nullptr) {
499 for (size_t i = 0; i < symbolEntries.size(); i++) {
500 symbolEntryData[i].offset += out->size() - beginning;
501 }
502 }
503
504 out->appendBuffer(std::move(typeBlock));
505
506 package->header.size = out->size() - beforePackageIndex;
507 header->header.size = out->size() - beforeTable;
508 return true;
509}
510
511} // namespace aapt