blob: 6b90fb276b6ddecfbd9f8f07595bb132309e70a7 [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
17#include "ResourceTable.h"
18#include "ResourceValues.h"
19#include "ValueVisitor.h"
20
21#include "flatten/ChunkWriter.h"
22#include "flatten/ResourceTypeExtensions.h"
23#include "flatten/TableFlattener.h"
24#include "util/BigBuffer.h"
25
Adam Lesinski9ba47d82015-10-13 11:37:10 -070026#include <base/macros.h>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070027#include <type_traits>
28#include <numeric>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070029
30using namespace android;
31
32namespace aapt {
33
34namespace {
35
36template <typename T>
37static bool cmpIds(const T* a, const T* b) {
38 return a->id.value() < b->id.value();
39}
40
41static void strcpy16_htod(uint16_t* dst, size_t len, const StringPiece16& src) {
42 if (len == 0) {
43 return;
44 }
45
46 size_t i;
47 const char16_t* srcData = src.data();
48 for (i = 0; i < len - 1 && i < src.size(); i++) {
49 dst[i] = util::hostToDevice16((uint16_t) srcData[i]);
50 }
51 dst[i] = 0;
52}
53
54struct FlatEntry {
55 ResourceEntry* entry;
56 Value* value;
Adam Lesinski3b4cd942015-10-30 16:31:42 -070057
58 // The entry string pool index to the entry's name.
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059 uint32_t entryKey;
Adam Lesinski3b4cd942015-10-30 16:31:42 -070060
61 // The source string pool index to the source file path.
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062 uint32_t sourcePathKey;
63 uint32_t sourceLine;
Adam Lesinski3b4cd942015-10-30 16:31:42 -070064
65 // The source string pool index to the comment.
66 uint32_t commentKey;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067};
68
Adam Lesinski9ba47d82015-10-13 11:37:10 -070069class SymbolWriter {
70public:
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071 struct Entry {
72 StringPool::Ref name;
73 size_t offset;
74 };
75
Adam Lesinski1ab598f2015-08-14 14:26:04 -070076 std::vector<Entry> symbols;
77
Adam Lesinski9ba47d82015-10-13 11:37:10 -070078 explicit SymbolWriter(StringPool* pool) : mPool(pool) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079 }
Adam Lesinski9ba47d82015-10-13 11:37:10 -070080
81 void addSymbol(const ResourceNameRef& name, size_t offset) {
82 symbols.push_back(Entry{ mPool->makeRef(name.package.toString() + u":" +
83 toString(name.type).toString() + u"/" +
84 name.entry.toString()), offset });
85 }
86
87 void shiftAllOffsets(size_t offset) {
88 for (Entry& entry : symbols) {
89 entry.offset += offset;
90 }
91 }
92
93private:
94 StringPool* mPool;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070095};
96
97struct MapFlattenVisitor : public RawValueVisitor {
98 using RawValueVisitor::visit;
99
100 SymbolWriter* mSymbols;
101 FlatEntry* mEntry;
102 BigBuffer* mBuffer;
103 size_t mEntryCount = 0;
104 Maybe<uint32_t> mParentIdent;
105 Maybe<ResourceNameRef> mParentName;
106
107 MapFlattenVisitor(SymbolWriter* symbols, FlatEntry* entry, BigBuffer* buffer) :
108 mSymbols(symbols), mEntry(entry), mBuffer(buffer) {
109 }
110
111 void flattenKey(Reference* key, ResTable_map* outEntry) {
112 if (!key->id) {
113 assert(key->name && "reference must have a name");
114
115 outEntry->name.ident = util::hostToDevice32(0);
116 mSymbols->addSymbol(key->name.value(), (mBuffer->size() - sizeof(ResTable_map)) +
117 offsetof(ResTable_map, name));
118 } else {
119 outEntry->name.ident = util::hostToDevice32(key->id.value().id);
120 }
121 }
122
123 void flattenValue(Item* value, ResTable_map* outEntry) {
124 if (Reference* ref = valueCast<Reference>(value)) {
125 if (!ref->id) {
126 assert(ref->name && "reference must have a name");
127
128 mSymbols->addSymbol(ref->name.value(), (mBuffer->size() - sizeof(ResTable_map)) +
129 offsetof(ResTable_map, value) + offsetof(Res_value, data));
130 }
131 }
132
133 bool result = value->flatten(&outEntry->value);
134 assert(result && "flatten failed");
135 }
136
137 void flattenEntry(Reference* key, Item* value) {
138 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
139 flattenKey(key, outEntry);
140 flattenValue(value, outEntry);
141 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
142 mEntryCount++;
143 }
144
145 void visit(Attribute* attr) override {
146 {
147 Reference key(ResourceId{ ResTable_map::ATTR_TYPE });
148 BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->typeMask);
149 flattenEntry(&key, &val);
150 }
151
152 for (Attribute::Symbol& s : attr->symbols) {
153 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
154 flattenEntry(&s.symbol, &val);
155 }
156 }
157
158 static bool cmpStyleEntries(const Style::Entry& a, const Style::Entry& b) {
159 if (a.key.id) {
160 if (b.key.id) {
161 return a.key.id.value() < b.key.id.value();
162 }
163 return true;
164 } else if (!b.key.id) {
165 return a.key.name.value() < b.key.name.value();
166 }
167 return false;
168 }
169
170 void visit(Style* style) override {
171 if (style->parent) {
172 if (!style->parent.value().id) {
173 assert(style->parent.value().name && "reference must have a name");
174 mParentName = style->parent.value().name;
175 } else {
176 mParentIdent = style->parent.value().id.value().id;
177 }
178 }
179
180 // Sort the style.
181 std::sort(style->entries.begin(), style->entries.end(), cmpStyleEntries);
182
183 for (Style::Entry& entry : style->entries) {
184 flattenEntry(&entry.key, entry.value.get());
185 }
186 }
187
188 void visit(Styleable* styleable) override {
189 for (auto& attrRef : styleable->entries) {
190 BinaryPrimitive val(Res_value{});
191 flattenEntry(&attrRef, &val);
192 }
193 }
194
195 void visit(Array* array) override {
196 for (auto& item : array->items) {
197 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
198 flattenValue(item.get(), outEntry);
199 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
200 mEntryCount++;
201 }
202 }
203
204 void visit(Plural* plural) override {
205 const size_t count = plural->values.size();
206 for (size_t i = 0; i < count; i++) {
207 if (!plural->values[i]) {
208 continue;
209 }
210
211 ResourceId q;
212 switch (i) {
213 case Plural::Zero:
214 q.id = android::ResTable_map::ATTR_ZERO;
215 break;
216
217 case Plural::One:
218 q.id = android::ResTable_map::ATTR_ONE;
219 break;
220
221 case Plural::Two:
222 q.id = android::ResTable_map::ATTR_TWO;
223 break;
224
225 case Plural::Few:
226 q.id = android::ResTable_map::ATTR_FEW;
227 break;
228
229 case Plural::Many:
230 q.id = android::ResTable_map::ATTR_MANY;
231 break;
232
233 case Plural::Other:
234 q.id = android::ResTable_map::ATTR_OTHER;
235 break;
236
237 default:
238 assert(false);
239 break;
240 }
241
242 Reference key(q);
243 flattenEntry(&key, plural->values[i].get());
244 }
245 }
246};
247
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700248class PackageFlattener {
249public:
250 PackageFlattener(IDiagnostics* diag, TableFlattenerOptions options,
251 ResourceTablePackage* package, SymbolWriter* symbolWriter,
252 StringPool* sourcePool) :
253 mDiag(diag), mOptions(options), mPackage(package), mSymbols(symbolWriter),
254 mSourcePool(sourcePool) {
255 }
256
257 bool flattenPackage(BigBuffer* buffer) {
258 ChunkWriter pkgWriter(buffer);
259 ResTable_package* pkgHeader = pkgWriter.startChunk<ResTable_package>(
260 RES_TABLE_PACKAGE_TYPE);
261 pkgHeader->id = util::hostToDevice32(mPackage->id.value());
262
263 if (mPackage->name.size() >= arraysize(pkgHeader->name)) {
264 mDiag->error(DiagMessage() <<
265 "package name '" << mPackage->name << "' is too long");
266 return false;
267 }
268
269 // Copy the package name in device endianness.
270 strcpy16_htod(pkgHeader->name, arraysize(pkgHeader->name), mPackage->name);
271
272 // Serialize the types. We do this now so that our type and key strings
273 // are populated. We write those first.
274 BigBuffer typeBuffer(1024);
275 flattenTypes(&typeBuffer);
276
277 pkgHeader->typeStrings = util::hostToDevice32(pkgWriter.size());
278 StringPool::flattenUtf16(pkgWriter.getBuffer(), mTypePool);
279
280 pkgHeader->keyStrings = util::hostToDevice32(pkgWriter.size());
281 StringPool::flattenUtf16(pkgWriter.getBuffer(), mKeyPool);
282
283 // Add the ResTable_package header/type/key strings to the offset.
284 mSymbols->shiftAllOffsets(pkgWriter.size());
285
286 // Append the types.
287 buffer->appendBuffer(std::move(typeBuffer));
288
289 pkgWriter.finish();
290 return true;
291 }
292
293private:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700294 IDiagnostics* mDiag;
295 TableFlattenerOptions mOptions;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700296 ResourceTablePackage* mPackage;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700297 StringPool mTypePool;
298 StringPool mKeyPool;
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700299 SymbolWriter* mSymbols;
300 StringPool* mSourcePool;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700301
Adam Lesinskie78fd612015-10-22 12:48:43 -0700302 template <typename T, bool IsItem>
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700303 T* writeEntry(FlatEntry* entry, BigBuffer* buffer) {
304 static_assert(std::is_same<ResTable_entry, T>::value ||
305 std::is_same<ResTable_entry_ext, T>::value,
306 "T must be ResTable_entry or ResTable_entry_ext");
307
308 T* result = buffer->nextBlock<T>();
309 ResTable_entry* outEntry = (ResTable_entry*)(result);
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700310 if (entry->entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700311 outEntry->flags |= ResTable_entry::FLAG_PUBLIC;
312 }
313
314 if (entry->value->isWeak()) {
315 outEntry->flags |= ResTable_entry::FLAG_WEAK;
316 }
317
Adam Lesinskie78fd612015-10-22 12:48:43 -0700318 if (!IsItem) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700319 outEntry->flags |= ResTable_entry::FLAG_COMPLEX;
320 }
321
322 outEntry->key.index = util::hostToDevice32(entry->entryKey);
323 outEntry->size = sizeof(T);
324
325 if (mOptions.useExtendedChunks) {
326 // Write the extra source block. This will be ignored by the Android runtime.
327 ResTable_entry_source* sourceBlock = buffer->nextBlock<ResTable_entry_source>();
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700328 sourceBlock->path.index = util::hostToDevice32(entry->sourcePathKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700329 sourceBlock->line = util::hostToDevice32(entry->sourceLine);
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700330 sourceBlock->comment.index = util::hostToDevice32(entry->commentKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700331 outEntry->size += sizeof(*sourceBlock);
332 }
333
334 outEntry->flags = util::hostToDevice16(outEntry->flags);
335 outEntry->size = util::hostToDevice16(outEntry->size);
336 return result;
337 }
338
339 bool flattenValue(FlatEntry* entry, BigBuffer* buffer) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700340 if (Item* item = valueCast<Item>(entry->value)) {
341 writeEntry<ResTable_entry, true>(entry, buffer);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700342 if (Reference* ref = valueCast<Reference>(entry->value)) {
343 if (!ref->id) {
344 assert(ref->name && "reference must have at least a name");
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700345 mSymbols->addSymbol(ref->name.value(),
346 buffer->size() + offsetof(Res_value, data));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700347 }
348 }
349 Res_value* outValue = buffer->nextBlock<Res_value>();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700350 bool result = item->flatten(outValue);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700351 assert(result && "flatten failed");
352 outValue->size = util::hostToDevice16(sizeof(*outValue));
353 } else {
354 const size_t beforeEntry = buffer->size();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700355 ResTable_entry_ext* outEntry = writeEntry<ResTable_entry_ext, false>(entry, buffer);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700356 MapFlattenVisitor visitor(mSymbols, entry, buffer);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700357 entry->value->accept(&visitor);
358 outEntry->count = util::hostToDevice32(visitor.mEntryCount);
359 if (visitor.mParentName) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700360 mSymbols->addSymbol(visitor.mParentName.value(),
361 beforeEntry + offsetof(ResTable_entry_ext, parent));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700362 } else if (visitor.mParentIdent) {
363 outEntry->parent.ident = util::hostToDevice32(visitor.mParentIdent.value());
364 }
365 }
366 return true;
367 }
368
369 bool flattenConfig(const ResourceTableType* type, const ConfigDescription& config,
370 std::vector<FlatEntry>* entries, BigBuffer* buffer) {
371 ChunkWriter typeWriter(buffer);
372 ResTable_type* typeHeader = typeWriter.startChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
373 typeHeader->id = type->id.value();
374 typeHeader->config = config;
375 typeHeader->config.swapHtoD();
376
377 auto maxAccum = [](uint32_t max, const std::unique_ptr<ResourceEntry>& a) -> uint32_t {
378 return std::max(max, (uint32_t) a->id.value());
379 };
380
381 // Find the largest entry ID. That is how many entries we will have.
382 const uint32_t entryCount =
383 std::accumulate(type->entries.begin(), type->entries.end(), 0, maxAccum) + 1;
384
385 typeHeader->entryCount = util::hostToDevice32(entryCount);
386 uint32_t* indices = typeWriter.nextBlock<uint32_t>(entryCount);
387
388 assert((size_t) entryCount <= std::numeric_limits<uint16_t>::max() + 1);
389 memset(indices, 0xff, entryCount * sizeof(uint32_t));
390
391 typeHeader->entriesStart = util::hostToDevice32(typeWriter.size());
392
393 const size_t entryStart = typeWriter.getBuffer()->size();
394 for (FlatEntry& flatEntry : *entries) {
395 assert(flatEntry.entry->id.value() < entryCount);
396 indices[flatEntry.entry->id.value()] = util::hostToDevice32(
397 typeWriter.getBuffer()->size() - entryStart);
398 if (!flattenValue(&flatEntry, typeWriter.getBuffer())) {
399 mDiag->error(DiagMessage()
400 << "failed to flatten resource '"
401 << ResourceNameRef(mPackage->name, type->type, flatEntry.entry->name)
402 << "' for configuration '" << config << "'");
403 return false;
404 }
405 }
406 typeWriter.finish();
407 return true;
408 }
409
410 std::vector<ResourceTableType*> collectAndSortTypes() {
411 std::vector<ResourceTableType*> sortedTypes;
412 for (auto& type : mPackage->types) {
413 if (type->type == ResourceType::kStyleable && !mOptions.useExtendedChunks) {
414 // Styleables aren't real Resource Types, they are represented in the R.java
415 // file.
416 continue;
417 }
418
419 assert(type->id && "type must have an ID set");
420
421 sortedTypes.push_back(type.get());
422 }
423 std::sort(sortedTypes.begin(), sortedTypes.end(), cmpIds<ResourceTableType>);
424 return sortedTypes;
425 }
426
427 std::vector<ResourceEntry*> collectAndSortEntries(ResourceTableType* type) {
428 // Sort the entries by entry ID.
429 std::vector<ResourceEntry*> sortedEntries;
430 for (auto& entry : type->entries) {
431 assert(entry->id && "entry must have an ID set");
432 sortedEntries.push_back(entry.get());
433 }
434 std::sort(sortedEntries.begin(), sortedEntries.end(), cmpIds<ResourceEntry>);
435 return sortedEntries;
436 }
437
438 bool flattenTypeSpec(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
439 BigBuffer* buffer) {
440 ChunkWriter typeSpecWriter(buffer);
441 ResTable_typeSpec* specHeader = typeSpecWriter.startChunk<ResTable_typeSpec>(
442 RES_TABLE_TYPE_SPEC_TYPE);
443 specHeader->id = type->id.value();
444
445 if (sortedEntries->empty()) {
446 typeSpecWriter.finish();
447 return true;
448 }
449
450 // We can't just take the size of the vector. There may be holes in the entry ID space.
451 // Since the entries are sorted by ID, the last one will be the biggest.
452 const size_t numEntries = sortedEntries->back()->id.value() + 1;
453
454 specHeader->entryCount = util::hostToDevice32(numEntries);
455
456 // Reserve space for the masks of each resource in this type. These
457 // show for which configuration axis the resource changes.
458 uint32_t* configMasks = typeSpecWriter.nextBlock<uint32_t>(numEntries);
459
460 const size_t actualNumEntries = sortedEntries->size();
461 for (size_t entryIndex = 0; entryIndex < actualNumEntries; entryIndex++) {
462 ResourceEntry* entry = sortedEntries->at(entryIndex);
463
464 // Populate the config masks for this entry.
465
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700466 if (entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700467 configMasks[entry->id.value()] |=
468 util::hostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
469 }
470
471 const size_t configCount = entry->values.size();
472 for (size_t i = 0; i < configCount; i++) {
473 const ConfigDescription& config = entry->values[i].config;
474 for (size_t j = i + 1; j < configCount; j++) {
475 configMasks[entry->id.value()] |= util::hostToDevice32(
476 config.diff(entry->values[j].config));
477 }
478 }
479 }
480 typeSpecWriter.finish();
481 return true;
482 }
483
484 bool flattenPublic(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
485 BigBuffer* buffer) {
486 ChunkWriter publicWriter(buffer);
487 Public_header* publicHeader = publicWriter.startChunk<Public_header>(RES_TABLE_PUBLIC_TYPE);
488 publicHeader->typeId = type->id.value();
489
490 for (ResourceEntry* entry : *sortedEntries) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700491 if (entry->symbolStatus.state != SymbolState::kUndefined) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700492 // Write the public status of this entry.
493 Public_entry* publicEntry = publicWriter.nextBlock<Public_entry>();
494 publicEntry->entryId = util::hostToDevice32(entry->id.value());
495 publicEntry->key.index = util::hostToDevice32(mKeyPool.makeRef(
496 entry->name).getIndex());
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700497 publicEntry->source.path.index = util::hostToDevice32(mSourcePool->makeRef(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700498 util::utf8ToUtf16(entry->symbolStatus.source.path)).getIndex());
499 if (entry->symbolStatus.source.line) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700500 publicEntry->source.line = util::hostToDevice32(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700501 entry->symbolStatus.source.line.value());
502 }
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700503 publicEntry->source.comment.index = util::hostToDevice32(mSourcePool->makeRef(
504 entry->symbolStatus.comment).getIndex());
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700505
506 switch (entry->symbolStatus.state) {
507 case SymbolState::kPrivate:
508 publicEntry->state = Public_entry::kPrivate;
509 break;
510
511 case SymbolState::kPublic:
512 publicEntry->state = Public_entry::kPublic;
513 break;
514
515 default:
516 assert(false && "should not serialize any other state");
517 break;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700518 }
519
520 // Don't hostToDevice until the last step.
521 publicHeader->count += 1;
522 }
523 }
524
525 publicHeader->count = util::hostToDevice32(publicHeader->count);
526 publicWriter.finish();
527 return true;
528 }
529
530 bool flattenTypes(BigBuffer* buffer) {
531 // Sort the types by their IDs. They will be inserted into the StringPool in this order.
532 std::vector<ResourceTableType*> sortedTypes = collectAndSortTypes();
533
534 size_t expectedTypeId = 1;
535 for (ResourceTableType* type : sortedTypes) {
536 // If there is a gap in the type IDs, fill in the StringPool
537 // with empty values until we reach the ID we expect.
538 while (type->id.value() > expectedTypeId) {
539 std::u16string typeName(u"?");
540 typeName += expectedTypeId;
541 mTypePool.makeRef(typeName);
542 expectedTypeId++;
543 }
544 expectedTypeId++;
545 mTypePool.makeRef(toString(type->type));
546
547 std::vector<ResourceEntry*> sortedEntries = collectAndSortEntries(type);
548
549 if (!flattenTypeSpec(type, &sortedEntries, buffer)) {
550 return false;
551 }
552
553 if (mOptions.useExtendedChunks) {
554 if (!flattenPublic(type, &sortedEntries, buffer)) {
555 return false;
556 }
557 }
558
559 // The binary resource table lists resource entries for each configuration.
560 // We store them inverted, where a resource entry lists the values for each
561 // configuration available. Here we reverse this to match the binary table.
562 std::map<ConfigDescription, std::vector<FlatEntry>> configToEntryListMap;
563 for (ResourceEntry* entry : sortedEntries) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700564 const uint32_t keyIndex = (uint32_t) mKeyPool.makeRef(entry->name).getIndex();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700565
566 // Group values by configuration.
567 for (auto& configValue : entry->values) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700568 Value* value = configValue.value.get();
569
570 const StringPool::Ref sourceRef = mSourcePool->makeRef(
571 util::utf8ToUtf16(value->getSource().path));
572
573 uint32_t lineNumber = 0;
574 if (value->getSource().line) {
575 lineNumber = value->getSource().line.value();
576 }
577
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700578 const StringPool::Ref commentRef = mSourcePool->makeRef(value->getComment());
579
Adam Lesinskie78fd612015-10-22 12:48:43 -0700580 configToEntryListMap[configValue.config]
581 .push_back(FlatEntry{
582 entry,
583 value,
584 keyIndex,
585 (uint32_t) sourceRef.getIndex(),
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700586 lineNumber,
587 (uint32_t) commentRef.getIndex() });
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700588 }
589 }
590
591 // Flatten a configuration value.
592 for (auto& entry : configToEntryListMap) {
593 if (!flattenConfig(type, entry.first, &entry.second, buffer)) {
594 return false;
595 }
596 }
597 }
598 return true;
599 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700600};
601
602} // namespace
603
604bool TableFlattener::consume(IAaptContext* context, ResourceTable* table) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700605 // We must do this before writing the resources, since the string pool IDs may change.
606 table->stringPool.sort([](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
607 int diff = a.context.priority - b.context.priority;
608 if (diff < 0) return true;
609 if (diff > 0) return false;
610 diff = a.context.config.compare(b.context.config);
611 if (diff < 0) return true;
612 if (diff > 0) return false;
613 return a.value < b.value;
614 });
615 table->stringPool.prune();
616
617 // Write the ResTable header.
618 ChunkWriter tableWriter(mBuffer);
619 ResTable_header* tableHeader = tableWriter.startChunk<ResTable_header>(RES_TABLE_TYPE);
620 tableHeader->packageCount = util::hostToDevice32(table->packages.size());
621
622 // Flatten the values string pool.
623 StringPool::flattenUtf8(tableWriter.getBuffer(), table->stringPool);
624
625 // If we have a reference to a symbol that doesn't exist, we don't know its resource ID.
626 // We encode the name of the symbol along with the offset of where to include the resource ID
627 // once it is found.
628 StringPool symbolPool;
629 std::vector<SymbolWriter::Entry> symbolOffsets;
630
631 // String pool holding the source paths of each value.
632 StringPool sourcePool;
633
634 BigBuffer packageBuffer(1024);
635
636 // Flatten each package.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700637 for (auto& package : table->packages) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700638 const size_t beforePackageSize = packageBuffer.size();
639
640 // All packages will share a single global symbol pool.
641 SymbolWriter packageSymbolWriter(&symbolPool);
642
643 PackageFlattener flattener(context->getDiagnostics(), mOptions, package.get(),
644 &packageSymbolWriter, &sourcePool);
645 if (!flattener.flattenPackage(&packageBuffer)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700646 return false;
647 }
648
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700649 // The symbols are offset only from their own Package start. Offset them from the
650 // start of the packageBuffer.
651 packageSymbolWriter.shiftAllOffsets(beforePackageSize);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700652
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700653 // Extract all the symbols to offset
654 symbolOffsets.insert(symbolOffsets.end(),
655 std::make_move_iterator(packageSymbolWriter.symbols.begin()),
656 std::make_move_iterator(packageSymbolWriter.symbols.end()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700657 }
658
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700659 SymbolTable_entry* symbolEntryData = nullptr;
660 if (mOptions.useExtendedChunks) {
661 if (!symbolOffsets.empty()) {
662 // Sort the offsets so we can scan them linearly.
663 std::sort(symbolOffsets.begin(), symbolOffsets.end(),
664 [](const SymbolWriter::Entry& a, const SymbolWriter::Entry& b) -> bool {
665 return a.offset < b.offset;
666 });
667
668 // Write the Symbol header.
669 ChunkWriter symbolWriter(tableWriter.getBuffer());
670 SymbolTable_header* symbolHeader = symbolWriter.startChunk<SymbolTable_header>(
671 RES_TABLE_SYMBOL_TABLE_TYPE);
672 symbolHeader->count = util::hostToDevice32(symbolOffsets.size());
673
674 symbolEntryData = symbolWriter.nextBlock<SymbolTable_entry>(symbolOffsets.size());
675 StringPool::flattenUtf8(symbolWriter.getBuffer(), symbolPool);
676 symbolWriter.finish();
677 }
678
679 if (sourcePool.size() > 0) {
680 // Write out source pool.
681 ChunkWriter srcWriter(tableWriter.getBuffer());
682 srcWriter.startChunk<ResChunk_header>(RES_TABLE_SOURCE_POOL_TYPE);
683 StringPool::flattenUtf8(srcWriter.getBuffer(), sourcePool);
684 srcWriter.finish();
685 }
686 }
687
688 const size_t beforePackagesSize = tableWriter.size();
689
690 // Finally merge all the packages into the main buffer.
691 tableWriter.getBuffer()->appendBuffer(std::move(packageBuffer));
692
693 // Update the offsets to their final values.
694 if (symbolEntryData) {
695 for (SymbolWriter::Entry& entry : symbolOffsets) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700696 symbolEntryData->name.index = util::hostToDevice32(entry.name.getIndex());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700697
698 // The symbols were all calculated with the packageBuffer offset. We need to
699 // add the beginning of the output buffer.
700 symbolEntryData->offset = util::hostToDevice32(entry.offset + beforePackagesSize);
701 symbolEntryData++;
702 }
703 }
704
705 tableWriter.finish();
706 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700707}
708
709} // namespace aapt