blob: 05906102528f0db0eb1220bd436cf07d98e5ef4e [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
Adam Lesinskia5870652015-11-20 15:32:30 -0800168 if (attr->minInt != std::numeric_limits<int32_t>::min()) {
169 Reference key(ResourceId{ ResTable_map::ATTR_MIN });
170 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->minInt));
171 flattenEntry(&key, &val);
172 }
173
174 if (attr->maxInt != std::numeric_limits<int32_t>::max()) {
175 Reference key(ResourceId{ ResTable_map::ATTR_MAX });
176 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->maxInt));
177 flattenEntry(&key, &val);
178 }
179
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700180 for (Attribute::Symbol& s : attr->symbols) {
181 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
182 flattenEntry(&s.symbol, &val);
183 }
184 }
185
186 static bool cmpStyleEntries(const Style::Entry& a, const Style::Entry& b) {
187 if (a.key.id) {
188 if (b.key.id) {
189 return a.key.id.value() < b.key.id.value();
190 }
191 return true;
192 } else if (!b.key.id) {
193 return a.key.name.value() < b.key.name.value();
194 }
195 return false;
196 }
197
198 void visit(Style* style) override {
199 if (style->parent) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800200 bool privateRef = style->parent.value().privateReference && mUseExtendedChunks;
201 if (!style->parent.value().id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700202 assert(style->parent.value().name && "reference must have a name");
203 mParentName = style->parent.value().name;
204 } else {
205 mParentIdent = style->parent.value().id.value().id;
206 }
207 }
208
209 // Sort the style.
210 std::sort(style->entries.begin(), style->entries.end(), cmpStyleEntries);
211
212 for (Style::Entry& entry : style->entries) {
213 flattenEntry(&entry.key, entry.value.get());
214 }
215 }
216
217 void visit(Styleable* styleable) override {
218 for (auto& attrRef : styleable->entries) {
219 BinaryPrimitive val(Res_value{});
220 flattenEntry(&attrRef, &val);
221 }
222 }
223
224 void visit(Array* array) override {
225 for (auto& item : array->items) {
226 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
227 flattenValue(item.get(), outEntry);
228 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
229 mEntryCount++;
230 }
231 }
232
233 void visit(Plural* plural) override {
234 const size_t count = plural->values.size();
235 for (size_t i = 0; i < count; i++) {
236 if (!plural->values[i]) {
237 continue;
238 }
239
240 ResourceId q;
241 switch (i) {
242 case Plural::Zero:
243 q.id = android::ResTable_map::ATTR_ZERO;
244 break;
245
246 case Plural::One:
247 q.id = android::ResTable_map::ATTR_ONE;
248 break;
249
250 case Plural::Two:
251 q.id = android::ResTable_map::ATTR_TWO;
252 break;
253
254 case Plural::Few:
255 q.id = android::ResTable_map::ATTR_FEW;
256 break;
257
258 case Plural::Many:
259 q.id = android::ResTable_map::ATTR_MANY;
260 break;
261
262 case Plural::Other:
263 q.id = android::ResTable_map::ATTR_OTHER;
264 break;
265
266 default:
267 assert(false);
268 break;
269 }
270
271 Reference key(q);
272 flattenEntry(&key, plural->values[i].get());
273 }
274 }
275};
276
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700277class PackageFlattener {
278public:
279 PackageFlattener(IDiagnostics* diag, TableFlattenerOptions options,
280 ResourceTablePackage* package, SymbolWriter* symbolWriter,
281 StringPool* sourcePool) :
282 mDiag(diag), mOptions(options), mPackage(package), mSymbols(symbolWriter),
283 mSourcePool(sourcePool) {
284 }
285
286 bool flattenPackage(BigBuffer* buffer) {
287 ChunkWriter pkgWriter(buffer);
288 ResTable_package* pkgHeader = pkgWriter.startChunk<ResTable_package>(
289 RES_TABLE_PACKAGE_TYPE);
290 pkgHeader->id = util::hostToDevice32(mPackage->id.value());
291
292 if (mPackage->name.size() >= arraysize(pkgHeader->name)) {
293 mDiag->error(DiagMessage() <<
294 "package name '" << mPackage->name << "' is too long");
295 return false;
296 }
297
298 // Copy the package name in device endianness.
299 strcpy16_htod(pkgHeader->name, arraysize(pkgHeader->name), mPackage->name);
300
301 // Serialize the types. We do this now so that our type and key strings
302 // are populated. We write those first.
303 BigBuffer typeBuffer(1024);
304 flattenTypes(&typeBuffer);
305
306 pkgHeader->typeStrings = util::hostToDevice32(pkgWriter.size());
307 StringPool::flattenUtf16(pkgWriter.getBuffer(), mTypePool);
308
309 pkgHeader->keyStrings = util::hostToDevice32(pkgWriter.size());
310 StringPool::flattenUtf16(pkgWriter.getBuffer(), mKeyPool);
311
312 // Add the ResTable_package header/type/key strings to the offset.
313 mSymbols->shiftAllOffsets(pkgWriter.size());
314
315 // Append the types.
316 buffer->appendBuffer(std::move(typeBuffer));
317
318 pkgWriter.finish();
319 return true;
320 }
321
322private:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700323 IDiagnostics* mDiag;
324 TableFlattenerOptions mOptions;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700325 ResourceTablePackage* mPackage;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700326 StringPool mTypePool;
327 StringPool mKeyPool;
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700328 SymbolWriter* mSymbols;
329 StringPool* mSourcePool;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700330
Adam Lesinskie78fd612015-10-22 12:48:43 -0700331 template <typename T, bool IsItem>
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700332 T* writeEntry(FlatEntry* entry, BigBuffer* buffer) {
333 static_assert(std::is_same<ResTable_entry, T>::value ||
334 std::is_same<ResTable_entry_ext, T>::value,
335 "T must be ResTable_entry or ResTable_entry_ext");
336
337 T* result = buffer->nextBlock<T>();
338 ResTable_entry* outEntry = (ResTable_entry*)(result);
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700339 if (entry->entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700340 outEntry->flags |= ResTable_entry::FLAG_PUBLIC;
341 }
342
343 if (entry->value->isWeak()) {
344 outEntry->flags |= ResTable_entry::FLAG_WEAK;
345 }
346
Adam Lesinskie78fd612015-10-22 12:48:43 -0700347 if (!IsItem) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700348 outEntry->flags |= ResTable_entry::FLAG_COMPLEX;
349 }
350
351 outEntry->key.index = util::hostToDevice32(entry->entryKey);
352 outEntry->size = sizeof(T);
353
354 if (mOptions.useExtendedChunks) {
355 // Write the extra source block. This will be ignored by the Android runtime.
356 ResTable_entry_source* sourceBlock = buffer->nextBlock<ResTable_entry_source>();
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700357 sourceBlock->path.index = util::hostToDevice32(entry->sourcePathKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700358 sourceBlock->line = util::hostToDevice32(entry->sourceLine);
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700359 sourceBlock->comment.index = util::hostToDevice32(entry->commentKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700360 outEntry->size += sizeof(*sourceBlock);
361 }
362
363 outEntry->flags = util::hostToDevice16(outEntry->flags);
364 outEntry->size = util::hostToDevice16(outEntry->size);
365 return result;
366 }
367
368 bool flattenValue(FlatEntry* entry, BigBuffer* buffer) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700369 if (Item* item = valueCast<Item>(entry->value)) {
370 writeEntry<ResTable_entry, true>(entry, buffer);
Adam Lesinski467f1712015-11-16 17:35:44 -0800371 bool privateRef = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700372 if (Reference* ref = valueCast<Reference>(entry->value)) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800373 // If there is no ID or the reference is private and we allow extended chunks,
374 // write out a 0 and mark the symbol table with the name of the reference.
375 privateRef = (ref->privateReference && mOptions.useExtendedChunks);
376 if (!ref->id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700377 assert(ref->name && "reference must have at least a name");
Adam Lesinski467f1712015-11-16 17:35:44 -0800378 mSymbols->addSymbol(*ref, buffer->size() + offsetof(Res_value, data));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700379 }
380 }
381 Res_value* outValue = buffer->nextBlock<Res_value>();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700382 bool result = item->flatten(outValue);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700383 assert(result && "flatten failed");
Adam Lesinski467f1712015-11-16 17:35:44 -0800384 if (privateRef) {
385 // Force the value of 0 so we look up the symbol at unflatten time.
386 outValue->data = 0;
387 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700388 outValue->size = util::hostToDevice16(sizeof(*outValue));
389 } else {
390 const size_t beforeEntry = buffer->size();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700391 ResTable_entry_ext* outEntry = writeEntry<ResTable_entry_ext, false>(entry, buffer);
Adam Lesinski467f1712015-11-16 17:35:44 -0800392 MapFlattenVisitor visitor(mSymbols, entry, buffer, mOptions.useExtendedChunks);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700393 entry->value->accept(&visitor);
394 outEntry->count = util::hostToDevice32(visitor.mEntryCount);
395 if (visitor.mParentName) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700396 mSymbols->addSymbol(visitor.mParentName.value(),
397 beforeEntry + offsetof(ResTable_entry_ext, parent));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700398 } else if (visitor.mParentIdent) {
399 outEntry->parent.ident = util::hostToDevice32(visitor.mParentIdent.value());
400 }
401 }
402 return true;
403 }
404
405 bool flattenConfig(const ResourceTableType* type, const ConfigDescription& config,
406 std::vector<FlatEntry>* entries, BigBuffer* buffer) {
407 ChunkWriter typeWriter(buffer);
408 ResTable_type* typeHeader = typeWriter.startChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
409 typeHeader->id = type->id.value();
410 typeHeader->config = config;
411 typeHeader->config.swapHtoD();
412
413 auto maxAccum = [](uint32_t max, const std::unique_ptr<ResourceEntry>& a) -> uint32_t {
414 return std::max(max, (uint32_t) a->id.value());
415 };
416
417 // Find the largest entry ID. That is how many entries we will have.
418 const uint32_t entryCount =
419 std::accumulate(type->entries.begin(), type->entries.end(), 0, maxAccum) + 1;
420
421 typeHeader->entryCount = util::hostToDevice32(entryCount);
422 uint32_t* indices = typeWriter.nextBlock<uint32_t>(entryCount);
423
424 assert((size_t) entryCount <= std::numeric_limits<uint16_t>::max() + 1);
425 memset(indices, 0xff, entryCount * sizeof(uint32_t));
426
427 typeHeader->entriesStart = util::hostToDevice32(typeWriter.size());
428
429 const size_t entryStart = typeWriter.getBuffer()->size();
430 for (FlatEntry& flatEntry : *entries) {
431 assert(flatEntry.entry->id.value() < entryCount);
432 indices[flatEntry.entry->id.value()] = util::hostToDevice32(
433 typeWriter.getBuffer()->size() - entryStart);
434 if (!flattenValue(&flatEntry, typeWriter.getBuffer())) {
435 mDiag->error(DiagMessage()
436 << "failed to flatten resource '"
437 << ResourceNameRef(mPackage->name, type->type, flatEntry.entry->name)
438 << "' for configuration '" << config << "'");
439 return false;
440 }
441 }
442 typeWriter.finish();
443 return true;
444 }
445
446 std::vector<ResourceTableType*> collectAndSortTypes() {
447 std::vector<ResourceTableType*> sortedTypes;
448 for (auto& type : mPackage->types) {
449 if (type->type == ResourceType::kStyleable && !mOptions.useExtendedChunks) {
450 // Styleables aren't real Resource Types, they are represented in the R.java
451 // file.
452 continue;
453 }
454
455 assert(type->id && "type must have an ID set");
456
457 sortedTypes.push_back(type.get());
458 }
459 std::sort(sortedTypes.begin(), sortedTypes.end(), cmpIds<ResourceTableType>);
460 return sortedTypes;
461 }
462
463 std::vector<ResourceEntry*> collectAndSortEntries(ResourceTableType* type) {
464 // Sort the entries by entry ID.
465 std::vector<ResourceEntry*> sortedEntries;
466 for (auto& entry : type->entries) {
467 assert(entry->id && "entry must have an ID set");
468 sortedEntries.push_back(entry.get());
469 }
470 std::sort(sortedEntries.begin(), sortedEntries.end(), cmpIds<ResourceEntry>);
471 return sortedEntries;
472 }
473
474 bool flattenTypeSpec(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
475 BigBuffer* buffer) {
476 ChunkWriter typeSpecWriter(buffer);
477 ResTable_typeSpec* specHeader = typeSpecWriter.startChunk<ResTable_typeSpec>(
478 RES_TABLE_TYPE_SPEC_TYPE);
479 specHeader->id = type->id.value();
480
481 if (sortedEntries->empty()) {
482 typeSpecWriter.finish();
483 return true;
484 }
485
486 // We can't just take the size of the vector. There may be holes in the entry ID space.
487 // Since the entries are sorted by ID, the last one will be the biggest.
488 const size_t numEntries = sortedEntries->back()->id.value() + 1;
489
490 specHeader->entryCount = util::hostToDevice32(numEntries);
491
492 // Reserve space for the masks of each resource in this type. These
493 // show for which configuration axis the resource changes.
494 uint32_t* configMasks = typeSpecWriter.nextBlock<uint32_t>(numEntries);
495
496 const size_t actualNumEntries = sortedEntries->size();
497 for (size_t entryIndex = 0; entryIndex < actualNumEntries; entryIndex++) {
498 ResourceEntry* entry = sortedEntries->at(entryIndex);
499
500 // Populate the config masks for this entry.
501
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700502 if (entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700503 configMasks[entry->id.value()] |=
504 util::hostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
505 }
506
507 const size_t configCount = entry->values.size();
508 for (size_t i = 0; i < configCount; i++) {
509 const ConfigDescription& config = entry->values[i].config;
510 for (size_t j = i + 1; j < configCount; j++) {
511 configMasks[entry->id.value()] |= util::hostToDevice32(
512 config.diff(entry->values[j].config));
513 }
514 }
515 }
516 typeSpecWriter.finish();
517 return true;
518 }
519
520 bool flattenPublic(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
521 BigBuffer* buffer) {
522 ChunkWriter publicWriter(buffer);
523 Public_header* publicHeader = publicWriter.startChunk<Public_header>(RES_TABLE_PUBLIC_TYPE);
524 publicHeader->typeId = type->id.value();
525
526 for (ResourceEntry* entry : *sortedEntries) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700527 if (entry->symbolStatus.state != SymbolState::kUndefined) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700528 // Write the public status of this entry.
529 Public_entry* publicEntry = publicWriter.nextBlock<Public_entry>();
530 publicEntry->entryId = util::hostToDevice32(entry->id.value());
531 publicEntry->key.index = util::hostToDevice32(mKeyPool.makeRef(
532 entry->name).getIndex());
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700533 publicEntry->source.path.index = util::hostToDevice32(mSourcePool->makeRef(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700534 util::utf8ToUtf16(entry->symbolStatus.source.path)).getIndex());
535 if (entry->symbolStatus.source.line) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700536 publicEntry->source.line = util::hostToDevice32(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700537 entry->symbolStatus.source.line.value());
538 }
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700539 publicEntry->source.comment.index = util::hostToDevice32(mSourcePool->makeRef(
540 entry->symbolStatus.comment).getIndex());
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700541
542 switch (entry->symbolStatus.state) {
543 case SymbolState::kPrivate:
544 publicEntry->state = Public_entry::kPrivate;
545 break;
546
547 case SymbolState::kPublic:
548 publicEntry->state = Public_entry::kPublic;
549 break;
550
551 default:
552 assert(false && "should not serialize any other state");
553 break;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700554 }
555
556 // Don't hostToDevice until the last step.
557 publicHeader->count += 1;
558 }
559 }
560
561 publicHeader->count = util::hostToDevice32(publicHeader->count);
562 publicWriter.finish();
563 return true;
564 }
565
566 bool flattenTypes(BigBuffer* buffer) {
567 // Sort the types by their IDs. They will be inserted into the StringPool in this order.
568 std::vector<ResourceTableType*> sortedTypes = collectAndSortTypes();
569
570 size_t expectedTypeId = 1;
571 for (ResourceTableType* type : sortedTypes) {
572 // If there is a gap in the type IDs, fill in the StringPool
573 // with empty values until we reach the ID we expect.
574 while (type->id.value() > expectedTypeId) {
575 std::u16string typeName(u"?");
576 typeName += expectedTypeId;
577 mTypePool.makeRef(typeName);
578 expectedTypeId++;
579 }
580 expectedTypeId++;
581 mTypePool.makeRef(toString(type->type));
582
583 std::vector<ResourceEntry*> sortedEntries = collectAndSortEntries(type);
584
585 if (!flattenTypeSpec(type, &sortedEntries, buffer)) {
586 return false;
587 }
588
589 if (mOptions.useExtendedChunks) {
590 if (!flattenPublic(type, &sortedEntries, buffer)) {
591 return false;
592 }
593 }
594
595 // The binary resource table lists resource entries for each configuration.
596 // We store them inverted, where a resource entry lists the values for each
597 // configuration available. Here we reverse this to match the binary table.
598 std::map<ConfigDescription, std::vector<FlatEntry>> configToEntryListMap;
599 for (ResourceEntry* entry : sortedEntries) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700600 const uint32_t keyIndex = (uint32_t) mKeyPool.makeRef(entry->name).getIndex();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700601
602 // Group values by configuration.
603 for (auto& configValue : entry->values) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700604 Value* value = configValue.value.get();
605
606 const StringPool::Ref sourceRef = mSourcePool->makeRef(
607 util::utf8ToUtf16(value->getSource().path));
608
609 uint32_t lineNumber = 0;
610 if (value->getSource().line) {
611 lineNumber = value->getSource().line.value();
612 }
613
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700614 const StringPool::Ref commentRef = mSourcePool->makeRef(value->getComment());
615
Adam Lesinskie78fd612015-10-22 12:48:43 -0700616 configToEntryListMap[configValue.config]
617 .push_back(FlatEntry{
618 entry,
619 value,
620 keyIndex,
621 (uint32_t) sourceRef.getIndex(),
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700622 lineNumber,
623 (uint32_t) commentRef.getIndex() });
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700624 }
625 }
626
627 // Flatten a configuration value.
628 for (auto& entry : configToEntryListMap) {
629 if (!flattenConfig(type, entry.first, &entry.second, buffer)) {
630 return false;
631 }
632 }
633 }
634 return true;
635 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700636};
637
638} // namespace
639
640bool TableFlattener::consume(IAaptContext* context, ResourceTable* table) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700641 // We must do this before writing the resources, since the string pool IDs may change.
642 table->stringPool.sort([](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
643 int diff = a.context.priority - b.context.priority;
644 if (diff < 0) return true;
645 if (diff > 0) return false;
646 diff = a.context.config.compare(b.context.config);
647 if (diff < 0) return true;
648 if (diff > 0) return false;
649 return a.value < b.value;
650 });
651 table->stringPool.prune();
652
653 // Write the ResTable header.
654 ChunkWriter tableWriter(mBuffer);
655 ResTable_header* tableHeader = tableWriter.startChunk<ResTable_header>(RES_TABLE_TYPE);
656 tableHeader->packageCount = util::hostToDevice32(table->packages.size());
657
658 // Flatten the values string pool.
659 StringPool::flattenUtf8(tableWriter.getBuffer(), table->stringPool);
660
661 // If we have a reference to a symbol that doesn't exist, we don't know its resource ID.
662 // We encode the name of the symbol along with the offset of where to include the resource ID
663 // once it is found.
664 StringPool symbolPool;
665 std::vector<SymbolWriter::Entry> symbolOffsets;
666
667 // String pool holding the source paths of each value.
668 StringPool sourcePool;
669
670 BigBuffer packageBuffer(1024);
671
672 // Flatten each package.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700673 for (auto& package : table->packages) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700674 const size_t beforePackageSize = packageBuffer.size();
675
676 // All packages will share a single global symbol pool.
677 SymbolWriter packageSymbolWriter(&symbolPool);
678
679 PackageFlattener flattener(context->getDiagnostics(), mOptions, package.get(),
680 &packageSymbolWriter, &sourcePool);
681 if (!flattener.flattenPackage(&packageBuffer)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700682 return false;
683 }
684
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700685 // The symbols are offset only from their own Package start. Offset them from the
686 // start of the packageBuffer.
687 packageSymbolWriter.shiftAllOffsets(beforePackageSize);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700688
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700689 // Extract all the symbols to offset
690 symbolOffsets.insert(symbolOffsets.end(),
691 std::make_move_iterator(packageSymbolWriter.symbols.begin()),
692 std::make_move_iterator(packageSymbolWriter.symbols.end()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700693 }
694
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700695 SymbolTable_entry* symbolEntryData = nullptr;
696 if (mOptions.useExtendedChunks) {
697 if (!symbolOffsets.empty()) {
698 // Sort the offsets so we can scan them linearly.
699 std::sort(symbolOffsets.begin(), symbolOffsets.end(),
700 [](const SymbolWriter::Entry& a, const SymbolWriter::Entry& b) -> bool {
701 return a.offset < b.offset;
702 });
703
704 // Write the Symbol header.
705 ChunkWriter symbolWriter(tableWriter.getBuffer());
706 SymbolTable_header* symbolHeader = symbolWriter.startChunk<SymbolTable_header>(
707 RES_TABLE_SYMBOL_TABLE_TYPE);
708 symbolHeader->count = util::hostToDevice32(symbolOffsets.size());
709
710 symbolEntryData = symbolWriter.nextBlock<SymbolTable_entry>(symbolOffsets.size());
711 StringPool::flattenUtf8(symbolWriter.getBuffer(), symbolPool);
712 symbolWriter.finish();
713 }
714
715 if (sourcePool.size() > 0) {
716 // Write out source pool.
717 ChunkWriter srcWriter(tableWriter.getBuffer());
718 srcWriter.startChunk<ResChunk_header>(RES_TABLE_SOURCE_POOL_TYPE);
719 StringPool::flattenUtf8(srcWriter.getBuffer(), sourcePool);
720 srcWriter.finish();
721 }
722 }
723
724 const size_t beforePackagesSize = tableWriter.size();
725
726 // Finally merge all the packages into the main buffer.
727 tableWriter.getBuffer()->appendBuffer(std::move(packageBuffer));
728
729 // Update the offsets to their final values.
730 if (symbolEntryData) {
731 for (SymbolWriter::Entry& entry : symbolOffsets) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700732 symbolEntryData->name.index = util::hostToDevice32(entry.name.getIndex());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700733
734 // The symbols were all calculated with the packageBuffer offset. We need to
735 // add the beginning of the output buffer.
736 symbolEntryData->offset = util::hostToDevice32(entry.offset + beforePackagesSize);
737 symbolEntryData++;
738 }
739 }
740
741 tableWriter.finish();
742 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700743}
744
745} // namespace aapt