blob: 636e9774156e9b89deb7178d86e00358e6f60a08 [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
Adam Lesinski467f1712015-11-16 17:35:44 -080081 void addSymbol(const Reference& ref, size_t offset) {
82 const ResourceName& name = ref.name.value();
83 std::u16string fullName;
84 if (ref.privateReference) {
85 fullName += u"*";
86 }
87
88 if (!name.package.empty()) {
89 fullName += name.package + u":";
90 }
91 fullName += toString(name.type).toString() + u"/" + name.entry;
92 symbols.push_back(Entry{ mPool->makeRef(fullName), offset });
Adam Lesinski9ba47d82015-10-13 11:37:10 -070093 }
94
95 void shiftAllOffsets(size_t offset) {
96 for (Entry& entry : symbols) {
97 entry.offset += offset;
98 }
99 }
100
101private:
102 StringPool* mPool;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700103};
104
105struct MapFlattenVisitor : public RawValueVisitor {
106 using RawValueVisitor::visit;
107
108 SymbolWriter* mSymbols;
109 FlatEntry* mEntry;
110 BigBuffer* mBuffer;
Adam Lesinski467f1712015-11-16 17:35:44 -0800111 bool mUseExtendedChunks;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700112 size_t mEntryCount = 0;
113 Maybe<uint32_t> mParentIdent;
114 Maybe<ResourceNameRef> mParentName;
115
Adam Lesinski467f1712015-11-16 17:35:44 -0800116 MapFlattenVisitor(SymbolWriter* symbols, FlatEntry* entry, BigBuffer* buffer,
117 bool useExtendedChunks) :
118 mSymbols(symbols), mEntry(entry), mBuffer(buffer),
119 mUseExtendedChunks(useExtendedChunks) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120 }
121
122 void flattenKey(Reference* key, ResTable_map* outEntry) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800123 if (!key->id || (key->privateReference && mUseExtendedChunks)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700124 assert(key->name && "reference must have a name");
125
126 outEntry->name.ident = util::hostToDevice32(0);
Adam Lesinski467f1712015-11-16 17:35:44 -0800127 mSymbols->addSymbol(*key, (mBuffer->size() - sizeof(ResTable_map)) +
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700128 offsetof(ResTable_map, name));
129 } else {
130 outEntry->name.ident = util::hostToDevice32(key->id.value().id);
131 }
132 }
133
134 void flattenValue(Item* value, ResTable_map* outEntry) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800135 bool privateRef = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700136 if (Reference* ref = valueCast<Reference>(value)) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800137 privateRef = ref->privateReference && mUseExtendedChunks;
138 if (!ref->id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139 assert(ref->name && "reference must have a name");
140
Adam Lesinski467f1712015-11-16 17:35:44 -0800141 mSymbols->addSymbol(*ref, (mBuffer->size() - sizeof(ResTable_map)) +
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700142 offsetof(ResTable_map, value) + offsetof(Res_value, data));
143 }
144 }
145
146 bool result = value->flatten(&outEntry->value);
Adam Lesinski467f1712015-11-16 17:35:44 -0800147 if (privateRef) {
148 outEntry->value.data = 0;
149 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700150 assert(result && "flatten failed");
151 }
152
153 void flattenEntry(Reference* key, Item* value) {
154 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
155 flattenKey(key, outEntry);
156 flattenValue(value, outEntry);
157 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
158 mEntryCount++;
159 }
160
161 void visit(Attribute* attr) override {
162 {
163 Reference key(ResourceId{ ResTable_map::ATTR_TYPE });
164 BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->typeMask);
165 flattenEntry(&key, &val);
166 }
167
168 for (Attribute::Symbol& s : attr->symbols) {
169 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
170 flattenEntry(&s.symbol, &val);
171 }
172 }
173
174 static bool cmpStyleEntries(const Style::Entry& a, const Style::Entry& b) {
175 if (a.key.id) {
176 if (b.key.id) {
177 return a.key.id.value() < b.key.id.value();
178 }
179 return true;
180 } else if (!b.key.id) {
181 return a.key.name.value() < b.key.name.value();
182 }
183 return false;
184 }
185
186 void visit(Style* style) override {
187 if (style->parent) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800188 bool privateRef = style->parent.value().privateReference && mUseExtendedChunks;
189 if (!style->parent.value().id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700190 assert(style->parent.value().name && "reference must have a name");
191 mParentName = style->parent.value().name;
192 } else {
193 mParentIdent = style->parent.value().id.value().id;
194 }
195 }
196
197 // Sort the style.
198 std::sort(style->entries.begin(), style->entries.end(), cmpStyleEntries);
199
200 for (Style::Entry& entry : style->entries) {
201 flattenEntry(&entry.key, entry.value.get());
202 }
203 }
204
205 void visit(Styleable* styleable) override {
206 for (auto& attrRef : styleable->entries) {
207 BinaryPrimitive val(Res_value{});
208 flattenEntry(&attrRef, &val);
209 }
210 }
211
212 void visit(Array* array) override {
213 for (auto& item : array->items) {
214 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
215 flattenValue(item.get(), outEntry);
216 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
217 mEntryCount++;
218 }
219 }
220
221 void visit(Plural* plural) override {
222 const size_t count = plural->values.size();
223 for (size_t i = 0; i < count; i++) {
224 if (!plural->values[i]) {
225 continue;
226 }
227
228 ResourceId q;
229 switch (i) {
230 case Plural::Zero:
231 q.id = android::ResTable_map::ATTR_ZERO;
232 break;
233
234 case Plural::One:
235 q.id = android::ResTable_map::ATTR_ONE;
236 break;
237
238 case Plural::Two:
239 q.id = android::ResTable_map::ATTR_TWO;
240 break;
241
242 case Plural::Few:
243 q.id = android::ResTable_map::ATTR_FEW;
244 break;
245
246 case Plural::Many:
247 q.id = android::ResTable_map::ATTR_MANY;
248 break;
249
250 case Plural::Other:
251 q.id = android::ResTable_map::ATTR_OTHER;
252 break;
253
254 default:
255 assert(false);
256 break;
257 }
258
259 Reference key(q);
260 flattenEntry(&key, plural->values[i].get());
261 }
262 }
263};
264
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700265class PackageFlattener {
266public:
267 PackageFlattener(IDiagnostics* diag, TableFlattenerOptions options,
268 ResourceTablePackage* package, SymbolWriter* symbolWriter,
269 StringPool* sourcePool) :
270 mDiag(diag), mOptions(options), mPackage(package), mSymbols(symbolWriter),
271 mSourcePool(sourcePool) {
272 }
273
274 bool flattenPackage(BigBuffer* buffer) {
275 ChunkWriter pkgWriter(buffer);
276 ResTable_package* pkgHeader = pkgWriter.startChunk<ResTable_package>(
277 RES_TABLE_PACKAGE_TYPE);
278 pkgHeader->id = util::hostToDevice32(mPackage->id.value());
279
280 if (mPackage->name.size() >= arraysize(pkgHeader->name)) {
281 mDiag->error(DiagMessage() <<
282 "package name '" << mPackage->name << "' is too long");
283 return false;
284 }
285
286 // Copy the package name in device endianness.
287 strcpy16_htod(pkgHeader->name, arraysize(pkgHeader->name), mPackage->name);
288
289 // Serialize the types. We do this now so that our type and key strings
290 // are populated. We write those first.
291 BigBuffer typeBuffer(1024);
292 flattenTypes(&typeBuffer);
293
294 pkgHeader->typeStrings = util::hostToDevice32(pkgWriter.size());
295 StringPool::flattenUtf16(pkgWriter.getBuffer(), mTypePool);
296
297 pkgHeader->keyStrings = util::hostToDevice32(pkgWriter.size());
298 StringPool::flattenUtf16(pkgWriter.getBuffer(), mKeyPool);
299
300 // Add the ResTable_package header/type/key strings to the offset.
301 mSymbols->shiftAllOffsets(pkgWriter.size());
302
303 // Append the types.
304 buffer->appendBuffer(std::move(typeBuffer));
305
306 pkgWriter.finish();
307 return true;
308 }
309
310private:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700311 IDiagnostics* mDiag;
312 TableFlattenerOptions mOptions;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700313 ResourceTablePackage* mPackage;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700314 StringPool mTypePool;
315 StringPool mKeyPool;
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700316 SymbolWriter* mSymbols;
317 StringPool* mSourcePool;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700318
Adam Lesinskie78fd612015-10-22 12:48:43 -0700319 template <typename T, bool IsItem>
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700320 T* writeEntry(FlatEntry* entry, BigBuffer* buffer) {
321 static_assert(std::is_same<ResTable_entry, T>::value ||
322 std::is_same<ResTable_entry_ext, T>::value,
323 "T must be ResTable_entry or ResTable_entry_ext");
324
325 T* result = buffer->nextBlock<T>();
326 ResTable_entry* outEntry = (ResTable_entry*)(result);
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700327 if (entry->entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700328 outEntry->flags |= ResTable_entry::FLAG_PUBLIC;
329 }
330
331 if (entry->value->isWeak()) {
332 outEntry->flags |= ResTable_entry::FLAG_WEAK;
333 }
334
Adam Lesinskie78fd612015-10-22 12:48:43 -0700335 if (!IsItem) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700336 outEntry->flags |= ResTable_entry::FLAG_COMPLEX;
337 }
338
339 outEntry->key.index = util::hostToDevice32(entry->entryKey);
340 outEntry->size = sizeof(T);
341
342 if (mOptions.useExtendedChunks) {
343 // Write the extra source block. This will be ignored by the Android runtime.
344 ResTable_entry_source* sourceBlock = buffer->nextBlock<ResTable_entry_source>();
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700345 sourceBlock->path.index = util::hostToDevice32(entry->sourcePathKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700346 sourceBlock->line = util::hostToDevice32(entry->sourceLine);
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700347 sourceBlock->comment.index = util::hostToDevice32(entry->commentKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700348 outEntry->size += sizeof(*sourceBlock);
349 }
350
351 outEntry->flags = util::hostToDevice16(outEntry->flags);
352 outEntry->size = util::hostToDevice16(outEntry->size);
353 return result;
354 }
355
356 bool flattenValue(FlatEntry* entry, BigBuffer* buffer) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700357 if (Item* item = valueCast<Item>(entry->value)) {
358 writeEntry<ResTable_entry, true>(entry, buffer);
Adam Lesinski467f1712015-11-16 17:35:44 -0800359 bool privateRef = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700360 if (Reference* ref = valueCast<Reference>(entry->value)) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800361 // If there is no ID or the reference is private and we allow extended chunks,
362 // write out a 0 and mark the symbol table with the name of the reference.
363 privateRef = (ref->privateReference && mOptions.useExtendedChunks);
364 if (!ref->id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700365 assert(ref->name && "reference must have at least a name");
Adam Lesinski467f1712015-11-16 17:35:44 -0800366 mSymbols->addSymbol(*ref, buffer->size() + offsetof(Res_value, data));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700367 }
368 }
369 Res_value* outValue = buffer->nextBlock<Res_value>();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700370 bool result = item->flatten(outValue);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700371 assert(result && "flatten failed");
Adam Lesinski467f1712015-11-16 17:35:44 -0800372 if (privateRef) {
373 // Force the value of 0 so we look up the symbol at unflatten time.
374 outValue->data = 0;
375 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700376 outValue->size = util::hostToDevice16(sizeof(*outValue));
377 } else {
378 const size_t beforeEntry = buffer->size();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700379 ResTable_entry_ext* outEntry = writeEntry<ResTable_entry_ext, false>(entry, buffer);
Adam Lesinski467f1712015-11-16 17:35:44 -0800380 MapFlattenVisitor visitor(mSymbols, entry, buffer, mOptions.useExtendedChunks);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700381 entry->value->accept(&visitor);
382 outEntry->count = util::hostToDevice32(visitor.mEntryCount);
383 if (visitor.mParentName) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700384 mSymbols->addSymbol(visitor.mParentName.value(),
385 beforeEntry + offsetof(ResTable_entry_ext, parent));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700386 } else if (visitor.mParentIdent) {
387 outEntry->parent.ident = util::hostToDevice32(visitor.mParentIdent.value());
388 }
389 }
390 return true;
391 }
392
393 bool flattenConfig(const ResourceTableType* type, const ConfigDescription& config,
394 std::vector<FlatEntry>* entries, BigBuffer* buffer) {
395 ChunkWriter typeWriter(buffer);
396 ResTable_type* typeHeader = typeWriter.startChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
397 typeHeader->id = type->id.value();
398 typeHeader->config = config;
399 typeHeader->config.swapHtoD();
400
401 auto maxAccum = [](uint32_t max, const std::unique_ptr<ResourceEntry>& a) -> uint32_t {
402 return std::max(max, (uint32_t) a->id.value());
403 };
404
405 // Find the largest entry ID. That is how many entries we will have.
406 const uint32_t entryCount =
407 std::accumulate(type->entries.begin(), type->entries.end(), 0, maxAccum) + 1;
408
409 typeHeader->entryCount = util::hostToDevice32(entryCount);
410 uint32_t* indices = typeWriter.nextBlock<uint32_t>(entryCount);
411
412 assert((size_t) entryCount <= std::numeric_limits<uint16_t>::max() + 1);
413 memset(indices, 0xff, entryCount * sizeof(uint32_t));
414
415 typeHeader->entriesStart = util::hostToDevice32(typeWriter.size());
416
417 const size_t entryStart = typeWriter.getBuffer()->size();
418 for (FlatEntry& flatEntry : *entries) {
419 assert(flatEntry.entry->id.value() < entryCount);
420 indices[flatEntry.entry->id.value()] = util::hostToDevice32(
421 typeWriter.getBuffer()->size() - entryStart);
422 if (!flattenValue(&flatEntry, typeWriter.getBuffer())) {
423 mDiag->error(DiagMessage()
424 << "failed to flatten resource '"
425 << ResourceNameRef(mPackage->name, type->type, flatEntry.entry->name)
426 << "' for configuration '" << config << "'");
427 return false;
428 }
429 }
430 typeWriter.finish();
431 return true;
432 }
433
434 std::vector<ResourceTableType*> collectAndSortTypes() {
435 std::vector<ResourceTableType*> sortedTypes;
436 for (auto& type : mPackage->types) {
437 if (type->type == ResourceType::kStyleable && !mOptions.useExtendedChunks) {
438 // Styleables aren't real Resource Types, they are represented in the R.java
439 // file.
440 continue;
441 }
442
443 assert(type->id && "type must have an ID set");
444
445 sortedTypes.push_back(type.get());
446 }
447 std::sort(sortedTypes.begin(), sortedTypes.end(), cmpIds<ResourceTableType>);
448 return sortedTypes;
449 }
450
451 std::vector<ResourceEntry*> collectAndSortEntries(ResourceTableType* type) {
452 // Sort the entries by entry ID.
453 std::vector<ResourceEntry*> sortedEntries;
454 for (auto& entry : type->entries) {
455 assert(entry->id && "entry must have an ID set");
456 sortedEntries.push_back(entry.get());
457 }
458 std::sort(sortedEntries.begin(), sortedEntries.end(), cmpIds<ResourceEntry>);
459 return sortedEntries;
460 }
461
462 bool flattenTypeSpec(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
463 BigBuffer* buffer) {
464 ChunkWriter typeSpecWriter(buffer);
465 ResTable_typeSpec* specHeader = typeSpecWriter.startChunk<ResTable_typeSpec>(
466 RES_TABLE_TYPE_SPEC_TYPE);
467 specHeader->id = type->id.value();
468
469 if (sortedEntries->empty()) {
470 typeSpecWriter.finish();
471 return true;
472 }
473
474 // We can't just take the size of the vector. There may be holes in the entry ID space.
475 // Since the entries are sorted by ID, the last one will be the biggest.
476 const size_t numEntries = sortedEntries->back()->id.value() + 1;
477
478 specHeader->entryCount = util::hostToDevice32(numEntries);
479
480 // Reserve space for the masks of each resource in this type. These
481 // show for which configuration axis the resource changes.
482 uint32_t* configMasks = typeSpecWriter.nextBlock<uint32_t>(numEntries);
483
484 const size_t actualNumEntries = sortedEntries->size();
485 for (size_t entryIndex = 0; entryIndex < actualNumEntries; entryIndex++) {
486 ResourceEntry* entry = sortedEntries->at(entryIndex);
487
488 // Populate the config masks for this entry.
489
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700490 if (entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700491 configMasks[entry->id.value()] |=
492 util::hostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
493 }
494
495 const size_t configCount = entry->values.size();
496 for (size_t i = 0; i < configCount; i++) {
497 const ConfigDescription& config = entry->values[i].config;
498 for (size_t j = i + 1; j < configCount; j++) {
499 configMasks[entry->id.value()] |= util::hostToDevice32(
500 config.diff(entry->values[j].config));
501 }
502 }
503 }
504 typeSpecWriter.finish();
505 return true;
506 }
507
508 bool flattenPublic(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
509 BigBuffer* buffer) {
510 ChunkWriter publicWriter(buffer);
511 Public_header* publicHeader = publicWriter.startChunk<Public_header>(RES_TABLE_PUBLIC_TYPE);
512 publicHeader->typeId = type->id.value();
513
514 for (ResourceEntry* entry : *sortedEntries) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700515 if (entry->symbolStatus.state != SymbolState::kUndefined) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700516 // Write the public status of this entry.
517 Public_entry* publicEntry = publicWriter.nextBlock<Public_entry>();
518 publicEntry->entryId = util::hostToDevice32(entry->id.value());
519 publicEntry->key.index = util::hostToDevice32(mKeyPool.makeRef(
520 entry->name).getIndex());
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700521 publicEntry->source.path.index = util::hostToDevice32(mSourcePool->makeRef(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700522 util::utf8ToUtf16(entry->symbolStatus.source.path)).getIndex());
523 if (entry->symbolStatus.source.line) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700524 publicEntry->source.line = util::hostToDevice32(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700525 entry->symbolStatus.source.line.value());
526 }
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700527 publicEntry->source.comment.index = util::hostToDevice32(mSourcePool->makeRef(
528 entry->symbolStatus.comment).getIndex());
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700529
530 switch (entry->symbolStatus.state) {
531 case SymbolState::kPrivate:
532 publicEntry->state = Public_entry::kPrivate;
533 break;
534
535 case SymbolState::kPublic:
536 publicEntry->state = Public_entry::kPublic;
537 break;
538
539 default:
540 assert(false && "should not serialize any other state");
541 break;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700542 }
543
544 // Don't hostToDevice until the last step.
545 publicHeader->count += 1;
546 }
547 }
548
549 publicHeader->count = util::hostToDevice32(publicHeader->count);
550 publicWriter.finish();
551 return true;
552 }
553
554 bool flattenTypes(BigBuffer* buffer) {
555 // Sort the types by their IDs. They will be inserted into the StringPool in this order.
556 std::vector<ResourceTableType*> sortedTypes = collectAndSortTypes();
557
558 size_t expectedTypeId = 1;
559 for (ResourceTableType* type : sortedTypes) {
560 // If there is a gap in the type IDs, fill in the StringPool
561 // with empty values until we reach the ID we expect.
562 while (type->id.value() > expectedTypeId) {
563 std::u16string typeName(u"?");
564 typeName += expectedTypeId;
565 mTypePool.makeRef(typeName);
566 expectedTypeId++;
567 }
568 expectedTypeId++;
569 mTypePool.makeRef(toString(type->type));
570
571 std::vector<ResourceEntry*> sortedEntries = collectAndSortEntries(type);
572
573 if (!flattenTypeSpec(type, &sortedEntries, buffer)) {
574 return false;
575 }
576
577 if (mOptions.useExtendedChunks) {
578 if (!flattenPublic(type, &sortedEntries, buffer)) {
579 return false;
580 }
581 }
582
583 // The binary resource table lists resource entries for each configuration.
584 // We store them inverted, where a resource entry lists the values for each
585 // configuration available. Here we reverse this to match the binary table.
586 std::map<ConfigDescription, std::vector<FlatEntry>> configToEntryListMap;
587 for (ResourceEntry* entry : sortedEntries) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700588 const uint32_t keyIndex = (uint32_t) mKeyPool.makeRef(entry->name).getIndex();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700589
590 // Group values by configuration.
591 for (auto& configValue : entry->values) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700592 Value* value = configValue.value.get();
593
594 const StringPool::Ref sourceRef = mSourcePool->makeRef(
595 util::utf8ToUtf16(value->getSource().path));
596
597 uint32_t lineNumber = 0;
598 if (value->getSource().line) {
599 lineNumber = value->getSource().line.value();
600 }
601
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700602 const StringPool::Ref commentRef = mSourcePool->makeRef(value->getComment());
603
Adam Lesinskie78fd612015-10-22 12:48:43 -0700604 configToEntryListMap[configValue.config]
605 .push_back(FlatEntry{
606 entry,
607 value,
608 keyIndex,
609 (uint32_t) sourceRef.getIndex(),
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700610 lineNumber,
611 (uint32_t) commentRef.getIndex() });
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700612 }
613 }
614
615 // Flatten a configuration value.
616 for (auto& entry : configToEntryListMap) {
617 if (!flattenConfig(type, entry.first, &entry.second, buffer)) {
618 return false;
619 }
620 }
621 }
622 return true;
623 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700624};
625
626} // namespace
627
628bool TableFlattener::consume(IAaptContext* context, ResourceTable* table) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700629 // We must do this before writing the resources, since the string pool IDs may change.
630 table->stringPool.sort([](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
631 int diff = a.context.priority - b.context.priority;
632 if (diff < 0) return true;
633 if (diff > 0) return false;
634 diff = a.context.config.compare(b.context.config);
635 if (diff < 0) return true;
636 if (diff > 0) return false;
637 return a.value < b.value;
638 });
639 table->stringPool.prune();
640
641 // Write the ResTable header.
642 ChunkWriter tableWriter(mBuffer);
643 ResTable_header* tableHeader = tableWriter.startChunk<ResTable_header>(RES_TABLE_TYPE);
644 tableHeader->packageCount = util::hostToDevice32(table->packages.size());
645
646 // Flatten the values string pool.
647 StringPool::flattenUtf8(tableWriter.getBuffer(), table->stringPool);
648
649 // If we have a reference to a symbol that doesn't exist, we don't know its resource ID.
650 // We encode the name of the symbol along with the offset of where to include the resource ID
651 // once it is found.
652 StringPool symbolPool;
653 std::vector<SymbolWriter::Entry> symbolOffsets;
654
655 // String pool holding the source paths of each value.
656 StringPool sourcePool;
657
658 BigBuffer packageBuffer(1024);
659
660 // Flatten each package.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700661 for (auto& package : table->packages) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700662 const size_t beforePackageSize = packageBuffer.size();
663
664 // All packages will share a single global symbol pool.
665 SymbolWriter packageSymbolWriter(&symbolPool);
666
667 PackageFlattener flattener(context->getDiagnostics(), mOptions, package.get(),
668 &packageSymbolWriter, &sourcePool);
669 if (!flattener.flattenPackage(&packageBuffer)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700670 return false;
671 }
672
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700673 // The symbols are offset only from their own Package start. Offset them from the
674 // start of the packageBuffer.
675 packageSymbolWriter.shiftAllOffsets(beforePackageSize);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700676
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700677 // Extract all the symbols to offset
678 symbolOffsets.insert(symbolOffsets.end(),
679 std::make_move_iterator(packageSymbolWriter.symbols.begin()),
680 std::make_move_iterator(packageSymbolWriter.symbols.end()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700681 }
682
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700683 SymbolTable_entry* symbolEntryData = nullptr;
684 if (mOptions.useExtendedChunks) {
685 if (!symbolOffsets.empty()) {
686 // Sort the offsets so we can scan them linearly.
687 std::sort(symbolOffsets.begin(), symbolOffsets.end(),
688 [](const SymbolWriter::Entry& a, const SymbolWriter::Entry& b) -> bool {
689 return a.offset < b.offset;
690 });
691
692 // Write the Symbol header.
693 ChunkWriter symbolWriter(tableWriter.getBuffer());
694 SymbolTable_header* symbolHeader = symbolWriter.startChunk<SymbolTable_header>(
695 RES_TABLE_SYMBOL_TABLE_TYPE);
696 symbolHeader->count = util::hostToDevice32(symbolOffsets.size());
697
698 symbolEntryData = symbolWriter.nextBlock<SymbolTable_entry>(symbolOffsets.size());
699 StringPool::flattenUtf8(symbolWriter.getBuffer(), symbolPool);
700 symbolWriter.finish();
701 }
702
703 if (sourcePool.size() > 0) {
704 // Write out source pool.
705 ChunkWriter srcWriter(tableWriter.getBuffer());
706 srcWriter.startChunk<ResChunk_header>(RES_TABLE_SOURCE_POOL_TYPE);
707 StringPool::flattenUtf8(srcWriter.getBuffer(), sourcePool);
708 srcWriter.finish();
709 }
710 }
711
712 const size_t beforePackagesSize = tableWriter.size();
713
714 // Finally merge all the packages into the main buffer.
715 tableWriter.getBuffer()->appendBuffer(std::move(packageBuffer));
716
717 // Update the offsets to their final values.
718 if (symbolEntryData) {
719 for (SymbolWriter::Entry& entry : symbolOffsets) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700720 symbolEntryData->name.index = util::hostToDevice32(entry.name.getIndex());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700721
722 // The symbols were all calculated with the packageBuffer offset. We need to
723 // add the beginning of the output buffer.
724 symbolEntryData->offset = util::hostToDevice32(entry.offset + beforePackagesSize);
725 symbolEntryData++;
726 }
727 }
728
729 tableWriter.finish();
730 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700731}
732
733} // namespace aapt