blob: 26d7c2ca055c95230edc594dd7a452e9e1eff2d7 [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
Elliott Hughese7d2cc32015-12-08 08:57:14 -080026#include <android-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 Lesinski28cacf02015-11-23 14:22:47 -0800111 StringPool* mSourcePool;
112 StringPool* mCommentPool;
Adam Lesinski467f1712015-11-16 17:35:44 -0800113 bool mUseExtendedChunks;
Adam Lesinski28cacf02015-11-23 14:22:47 -0800114
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700115 size_t mEntryCount = 0;
Adam Lesinski24b8ff02015-12-16 14:01:57 -0800116 const Reference* mParent = nullptr;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700117
Adam Lesinski467f1712015-11-16 17:35:44 -0800118 MapFlattenVisitor(SymbolWriter* symbols, FlatEntry* entry, BigBuffer* buffer,
Adam Lesinski28cacf02015-11-23 14:22:47 -0800119 StringPool* sourcePool, StringPool* commentPool,
Adam Lesinski467f1712015-11-16 17:35:44 -0800120 bool useExtendedChunks) :
Adam Lesinski28cacf02015-11-23 14:22:47 -0800121 mSymbols(symbols), mEntry(entry), mBuffer(buffer), mSourcePool(sourcePool),
122 mCommentPool(commentPool), mUseExtendedChunks(useExtendedChunks) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700123 }
124
125 void flattenKey(Reference* key, ResTable_map* outEntry) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800126 if (!key->id || (key->privateReference && mUseExtendedChunks)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700127 assert(key->name && "reference must have a name");
128
129 outEntry->name.ident = util::hostToDevice32(0);
Adam Lesinski467f1712015-11-16 17:35:44 -0800130 mSymbols->addSymbol(*key, (mBuffer->size() - sizeof(ResTable_map)) +
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700131 offsetof(ResTable_map, name));
132 } else {
133 outEntry->name.ident = util::hostToDevice32(key->id.value().id);
134 }
135 }
136
137 void flattenValue(Item* value, ResTable_map* outEntry) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800138 bool privateRef = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139 if (Reference* ref = valueCast<Reference>(value)) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800140 privateRef = ref->privateReference && mUseExtendedChunks;
141 if (!ref->id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700142 assert(ref->name && "reference must have a name");
143
Adam Lesinski467f1712015-11-16 17:35:44 -0800144 mSymbols->addSymbol(*ref, (mBuffer->size() - sizeof(ResTable_map)) +
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700145 offsetof(ResTable_map, value) + offsetof(Res_value, data));
146 }
147 }
148
149 bool result = value->flatten(&outEntry->value);
Adam Lesinski467f1712015-11-16 17:35:44 -0800150 if (privateRef) {
151 outEntry->value.data = 0;
152 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700153 assert(result && "flatten failed");
154 }
155
156 void flattenEntry(Reference* key, Item* value) {
157 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
158 flattenKey(key, outEntry);
159 flattenValue(value, outEntry);
160 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
161 mEntryCount++;
162 }
163
Adam Lesinski28cacf02015-11-23 14:22:47 -0800164 void flattenMetaData(Value* value) {
165 if (!mUseExtendedChunks) {
166 return;
167 }
168
169 Reference key(ResourceId{ ExtendedResTableMapTypes::ATTR_SOURCE_PATH });
170 StringPool::Ref sourcePathRef = mSourcePool->makeRef(
171 util::utf8ToUtf16(value->getSource().path));
172 BinaryPrimitive val(Res_value::TYPE_INT_DEC,
173 static_cast<uint32_t>(sourcePathRef.getIndex()));
174 flattenEntry(&key, &val);
175
176 if (value->getSource().line) {
177 key.id = ResourceId(ExtendedResTableMapTypes::ATTR_SOURCE_LINE);
178 val.value.data = static_cast<uint32_t>(value->getSource().line.value());
179 flattenEntry(&key, &val);
180 }
181
182 if (!value->getComment().empty()) {
183 key.id = ResourceId(ExtendedResTableMapTypes::ATTR_COMMENT);
184 StringPool::Ref commentRef = mCommentPool->makeRef(value->getComment());
185 val.value.data = static_cast<uint32_t>(commentRef.getIndex());
186 flattenEntry(&key, &val);
187 }
188 }
189
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700190 void visit(Attribute* attr) override {
191 {
192 Reference key(ResourceId{ ResTable_map::ATTR_TYPE });
193 BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->typeMask);
194 flattenEntry(&key, &val);
195 }
196
Adam Lesinskia5870652015-11-20 15:32:30 -0800197 if (attr->minInt != std::numeric_limits<int32_t>::min()) {
198 Reference key(ResourceId{ ResTable_map::ATTR_MIN });
199 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->minInt));
200 flattenEntry(&key, &val);
201 }
202
203 if (attr->maxInt != std::numeric_limits<int32_t>::max()) {
204 Reference key(ResourceId{ ResTable_map::ATTR_MAX });
205 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->maxInt));
206 flattenEntry(&key, &val);
207 }
208
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700209 for (Attribute::Symbol& s : attr->symbols) {
210 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
211 flattenEntry(&s.symbol, &val);
212 }
213 }
214
215 static bool cmpStyleEntries(const Style::Entry& a, const Style::Entry& b) {
216 if (a.key.id) {
217 if (b.key.id) {
218 return a.key.id.value() < b.key.id.value();
219 }
220 return true;
221 } else if (!b.key.id) {
222 return a.key.name.value() < b.key.name.value();
223 }
224 return false;
225 }
226
227 void visit(Style* style) override {
228 if (style->parent) {
Adam Lesinski24b8ff02015-12-16 14:01:57 -0800229 // Parents are treated a bit differently, so record the existence and move on.
230 mParent = &style->parent.value();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700231 }
232
233 // Sort the style.
234 std::sort(style->entries.begin(), style->entries.end(), cmpStyleEntries);
235
236 for (Style::Entry& entry : style->entries) {
237 flattenEntry(&entry.key, entry.value.get());
Adam Lesinski28cacf02015-11-23 14:22:47 -0800238 flattenMetaData(&entry.key);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700239 }
240 }
241
242 void visit(Styleable* styleable) override {
243 for (auto& attrRef : styleable->entries) {
244 BinaryPrimitive val(Res_value{});
245 flattenEntry(&attrRef, &val);
Adam Lesinski28cacf02015-11-23 14:22:47 -0800246 flattenMetaData(&attrRef);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700247 }
248 }
249
250 void visit(Array* array) override {
251 for (auto& item : array->items) {
252 ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
253 flattenValue(item.get(), outEntry);
254 outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
255 mEntryCount++;
Adam Lesinski28cacf02015-11-23 14:22:47 -0800256 flattenMetaData(item.get());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700257 }
258 }
259
260 void visit(Plural* plural) override {
261 const size_t count = plural->values.size();
262 for (size_t i = 0; i < count; i++) {
263 if (!plural->values[i]) {
264 continue;
265 }
266
267 ResourceId q;
268 switch (i) {
269 case Plural::Zero:
270 q.id = android::ResTable_map::ATTR_ZERO;
271 break;
272
273 case Plural::One:
274 q.id = android::ResTable_map::ATTR_ONE;
275 break;
276
277 case Plural::Two:
278 q.id = android::ResTable_map::ATTR_TWO;
279 break;
280
281 case Plural::Few:
282 q.id = android::ResTable_map::ATTR_FEW;
283 break;
284
285 case Plural::Many:
286 q.id = android::ResTable_map::ATTR_MANY;
287 break;
288
289 case Plural::Other:
290 q.id = android::ResTable_map::ATTR_OTHER;
291 break;
292
293 default:
294 assert(false);
295 break;
296 }
297
298 Reference key(q);
299 flattenEntry(&key, plural->values[i].get());
Adam Lesinski28cacf02015-11-23 14:22:47 -0800300 flattenMetaData(plural->values[i].get());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700301 }
302 }
303};
304
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700305class PackageFlattener {
306public:
307 PackageFlattener(IDiagnostics* diag, TableFlattenerOptions options,
308 ResourceTablePackage* package, SymbolWriter* symbolWriter,
309 StringPool* sourcePool) :
310 mDiag(diag), mOptions(options), mPackage(package), mSymbols(symbolWriter),
311 mSourcePool(sourcePool) {
312 }
313
314 bool flattenPackage(BigBuffer* buffer) {
315 ChunkWriter pkgWriter(buffer);
316 ResTable_package* pkgHeader = pkgWriter.startChunk<ResTable_package>(
317 RES_TABLE_PACKAGE_TYPE);
318 pkgHeader->id = util::hostToDevice32(mPackage->id.value());
319
320 if (mPackage->name.size() >= arraysize(pkgHeader->name)) {
321 mDiag->error(DiagMessage() <<
322 "package name '" << mPackage->name << "' is too long");
323 return false;
324 }
325
326 // Copy the package name in device endianness.
327 strcpy16_htod(pkgHeader->name, arraysize(pkgHeader->name), mPackage->name);
328
329 // Serialize the types. We do this now so that our type and key strings
330 // are populated. We write those first.
331 BigBuffer typeBuffer(1024);
332 flattenTypes(&typeBuffer);
333
334 pkgHeader->typeStrings = util::hostToDevice32(pkgWriter.size());
335 StringPool::flattenUtf16(pkgWriter.getBuffer(), mTypePool);
336
337 pkgHeader->keyStrings = util::hostToDevice32(pkgWriter.size());
338 StringPool::flattenUtf16(pkgWriter.getBuffer(), mKeyPool);
339
340 // Add the ResTable_package header/type/key strings to the offset.
341 mSymbols->shiftAllOffsets(pkgWriter.size());
342
343 // Append the types.
344 buffer->appendBuffer(std::move(typeBuffer));
345
346 pkgWriter.finish();
347 return true;
348 }
349
350private:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700351 IDiagnostics* mDiag;
352 TableFlattenerOptions mOptions;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700353 ResourceTablePackage* mPackage;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700354 StringPool mTypePool;
355 StringPool mKeyPool;
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700356 SymbolWriter* mSymbols;
357 StringPool* mSourcePool;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700358
Adam Lesinskie78fd612015-10-22 12:48:43 -0700359 template <typename T, bool IsItem>
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700360 T* writeEntry(FlatEntry* entry, BigBuffer* buffer) {
361 static_assert(std::is_same<ResTable_entry, T>::value ||
362 std::is_same<ResTable_entry_ext, T>::value,
363 "T must be ResTable_entry or ResTable_entry_ext");
364
365 T* result = buffer->nextBlock<T>();
366 ResTable_entry* outEntry = (ResTable_entry*)(result);
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700367 if (entry->entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700368 outEntry->flags |= ResTable_entry::FLAG_PUBLIC;
369 }
370
371 if (entry->value->isWeak()) {
372 outEntry->flags |= ResTable_entry::FLAG_WEAK;
373 }
374
Adam Lesinskie78fd612015-10-22 12:48:43 -0700375 if (!IsItem) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700376 outEntry->flags |= ResTable_entry::FLAG_COMPLEX;
377 }
378
379 outEntry->key.index = util::hostToDevice32(entry->entryKey);
380 outEntry->size = sizeof(T);
381
382 if (mOptions.useExtendedChunks) {
383 // Write the extra source block. This will be ignored by the Android runtime.
384 ResTable_entry_source* sourceBlock = buffer->nextBlock<ResTable_entry_source>();
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700385 sourceBlock->path.index = util::hostToDevice32(entry->sourcePathKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700386 sourceBlock->line = util::hostToDevice32(entry->sourceLine);
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700387 sourceBlock->comment.index = util::hostToDevice32(entry->commentKey);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700388 outEntry->size += sizeof(*sourceBlock);
389 }
390
391 outEntry->flags = util::hostToDevice16(outEntry->flags);
392 outEntry->size = util::hostToDevice16(outEntry->size);
393 return result;
394 }
395
396 bool flattenValue(FlatEntry* entry, BigBuffer* buffer) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700397 if (Item* item = valueCast<Item>(entry->value)) {
398 writeEntry<ResTable_entry, true>(entry, buffer);
Adam Lesinski467f1712015-11-16 17:35:44 -0800399 bool privateRef = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700400 if (Reference* ref = valueCast<Reference>(entry->value)) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800401 // If there is no ID or the reference is private and we allow extended chunks,
402 // write out a 0 and mark the symbol table with the name of the reference.
403 privateRef = (ref->privateReference && mOptions.useExtendedChunks);
404 if (!ref->id || privateRef) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700405 assert(ref->name && "reference must have at least a name");
Adam Lesinski467f1712015-11-16 17:35:44 -0800406 mSymbols->addSymbol(*ref, buffer->size() + offsetof(Res_value, data));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700407 }
408 }
409 Res_value* outValue = buffer->nextBlock<Res_value>();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700410 bool result = item->flatten(outValue);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700411 assert(result && "flatten failed");
Adam Lesinski467f1712015-11-16 17:35:44 -0800412 if (privateRef) {
413 // Force the value of 0 so we look up the symbol at unflatten time.
414 outValue->data = 0;
415 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700416 outValue->size = util::hostToDevice16(sizeof(*outValue));
417 } else {
418 const size_t beforeEntry = buffer->size();
Adam Lesinskie78fd612015-10-22 12:48:43 -0700419 ResTable_entry_ext* outEntry = writeEntry<ResTable_entry_ext, false>(entry, buffer);
Adam Lesinski28cacf02015-11-23 14:22:47 -0800420 MapFlattenVisitor visitor(mSymbols, entry, buffer, mSourcePool, mSourcePool,
421 mOptions.useExtendedChunks);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700422 entry->value->accept(&visitor);
423 outEntry->count = util::hostToDevice32(visitor.mEntryCount);
Adam Lesinski24b8ff02015-12-16 14:01:57 -0800424 if (visitor.mParent) {
425 const bool forceSymbol = visitor.mParent->privateReference &&
426 mOptions.useExtendedChunks;
427 if (!visitor.mParent->id || forceSymbol) {
428 assert(visitor.mParent->name && "reference must have a name");
429 mSymbols->addSymbol(*visitor.mParent,
430 beforeEntry + offsetof(ResTable_entry_ext, parent));
431 } else {
432 outEntry->parent.ident = util::hostToDevice32(visitor.mParent->id.value().id);
433 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700434 }
435 }
436 return true;
437 }
438
439 bool flattenConfig(const ResourceTableType* type, const ConfigDescription& config,
440 std::vector<FlatEntry>* entries, BigBuffer* buffer) {
441 ChunkWriter typeWriter(buffer);
442 ResTable_type* typeHeader = typeWriter.startChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
443 typeHeader->id = type->id.value();
444 typeHeader->config = config;
445 typeHeader->config.swapHtoD();
446
447 auto maxAccum = [](uint32_t max, const std::unique_ptr<ResourceEntry>& a) -> uint32_t {
448 return std::max(max, (uint32_t) a->id.value());
449 };
450
451 // Find the largest entry ID. That is how many entries we will have.
452 const uint32_t entryCount =
453 std::accumulate(type->entries.begin(), type->entries.end(), 0, maxAccum) + 1;
454
455 typeHeader->entryCount = util::hostToDevice32(entryCount);
456 uint32_t* indices = typeWriter.nextBlock<uint32_t>(entryCount);
457
458 assert((size_t) entryCount <= std::numeric_limits<uint16_t>::max() + 1);
459 memset(indices, 0xff, entryCount * sizeof(uint32_t));
460
461 typeHeader->entriesStart = util::hostToDevice32(typeWriter.size());
462
463 const size_t entryStart = typeWriter.getBuffer()->size();
464 for (FlatEntry& flatEntry : *entries) {
465 assert(flatEntry.entry->id.value() < entryCount);
466 indices[flatEntry.entry->id.value()] = util::hostToDevice32(
467 typeWriter.getBuffer()->size() - entryStart);
468 if (!flattenValue(&flatEntry, typeWriter.getBuffer())) {
469 mDiag->error(DiagMessage()
470 << "failed to flatten resource '"
471 << ResourceNameRef(mPackage->name, type->type, flatEntry.entry->name)
472 << "' for configuration '" << config << "'");
473 return false;
474 }
475 }
476 typeWriter.finish();
477 return true;
478 }
479
480 std::vector<ResourceTableType*> collectAndSortTypes() {
481 std::vector<ResourceTableType*> sortedTypes;
482 for (auto& type : mPackage->types) {
483 if (type->type == ResourceType::kStyleable && !mOptions.useExtendedChunks) {
484 // Styleables aren't real Resource Types, they are represented in the R.java
485 // file.
486 continue;
487 }
488
489 assert(type->id && "type must have an ID set");
490
491 sortedTypes.push_back(type.get());
492 }
493 std::sort(sortedTypes.begin(), sortedTypes.end(), cmpIds<ResourceTableType>);
494 return sortedTypes;
495 }
496
497 std::vector<ResourceEntry*> collectAndSortEntries(ResourceTableType* type) {
498 // Sort the entries by entry ID.
499 std::vector<ResourceEntry*> sortedEntries;
500 for (auto& entry : type->entries) {
501 assert(entry->id && "entry must have an ID set");
502 sortedEntries.push_back(entry.get());
503 }
504 std::sort(sortedEntries.begin(), sortedEntries.end(), cmpIds<ResourceEntry>);
505 return sortedEntries;
506 }
507
508 bool flattenTypeSpec(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
509 BigBuffer* buffer) {
510 ChunkWriter typeSpecWriter(buffer);
511 ResTable_typeSpec* specHeader = typeSpecWriter.startChunk<ResTable_typeSpec>(
512 RES_TABLE_TYPE_SPEC_TYPE);
513 specHeader->id = type->id.value();
514
515 if (sortedEntries->empty()) {
516 typeSpecWriter.finish();
517 return true;
518 }
519
520 // We can't just take the size of the vector. There may be holes in the entry ID space.
521 // Since the entries are sorted by ID, the last one will be the biggest.
522 const size_t numEntries = sortedEntries->back()->id.value() + 1;
523
524 specHeader->entryCount = util::hostToDevice32(numEntries);
525
526 // Reserve space for the masks of each resource in this type. These
527 // show for which configuration axis the resource changes.
528 uint32_t* configMasks = typeSpecWriter.nextBlock<uint32_t>(numEntries);
529
530 const size_t actualNumEntries = sortedEntries->size();
531 for (size_t entryIndex = 0; entryIndex < actualNumEntries; entryIndex++) {
532 ResourceEntry* entry = sortedEntries->at(entryIndex);
533
534 // Populate the config masks for this entry.
535
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700536 if (entry->symbolStatus.state == SymbolState::kPublic) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700537 configMasks[entry->id.value()] |=
538 util::hostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
539 }
540
541 const size_t configCount = entry->values.size();
542 for (size_t i = 0; i < configCount; i++) {
543 const ConfigDescription& config = entry->values[i].config;
544 for (size_t j = i + 1; j < configCount; j++) {
545 configMasks[entry->id.value()] |= util::hostToDevice32(
546 config.diff(entry->values[j].config));
547 }
548 }
549 }
550 typeSpecWriter.finish();
551 return true;
552 }
553
554 bool flattenPublic(ResourceTableType* type, std::vector<ResourceEntry*>* sortedEntries,
555 BigBuffer* buffer) {
556 ChunkWriter publicWriter(buffer);
557 Public_header* publicHeader = publicWriter.startChunk<Public_header>(RES_TABLE_PUBLIC_TYPE);
558 publicHeader->typeId = type->id.value();
559
560 for (ResourceEntry* entry : *sortedEntries) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700561 if (entry->symbolStatus.state != SymbolState::kUndefined) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700562 // Write the public status of this entry.
563 Public_entry* publicEntry = publicWriter.nextBlock<Public_entry>();
564 publicEntry->entryId = util::hostToDevice32(entry->id.value());
565 publicEntry->key.index = util::hostToDevice32(mKeyPool.makeRef(
566 entry->name).getIndex());
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700567 publicEntry->source.path.index = util::hostToDevice32(mSourcePool->makeRef(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700568 util::utf8ToUtf16(entry->symbolStatus.source.path)).getIndex());
569 if (entry->symbolStatus.source.line) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700570 publicEntry->source.line = util::hostToDevice32(
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700571 entry->symbolStatus.source.line.value());
572 }
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700573 publicEntry->source.comment.index = util::hostToDevice32(mSourcePool->makeRef(
574 entry->symbolStatus.comment).getIndex());
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700575
576 switch (entry->symbolStatus.state) {
577 case SymbolState::kPrivate:
578 publicEntry->state = Public_entry::kPrivate;
579 break;
580
581 case SymbolState::kPublic:
582 publicEntry->state = Public_entry::kPublic;
583 break;
584
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800585 case SymbolState::kUndefined:
586 publicEntry->state = Public_entry::kUndefined;
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700587 break;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700588 }
589
590 // Don't hostToDevice until the last step.
591 publicHeader->count += 1;
592 }
593 }
594
595 publicHeader->count = util::hostToDevice32(publicHeader->count);
596 publicWriter.finish();
597 return true;
598 }
599
600 bool flattenTypes(BigBuffer* buffer) {
601 // Sort the types by their IDs. They will be inserted into the StringPool in this order.
602 std::vector<ResourceTableType*> sortedTypes = collectAndSortTypes();
603
604 size_t expectedTypeId = 1;
605 for (ResourceTableType* type : sortedTypes) {
606 // If there is a gap in the type IDs, fill in the StringPool
607 // with empty values until we reach the ID we expect.
608 while (type->id.value() > expectedTypeId) {
609 std::u16string typeName(u"?");
610 typeName += expectedTypeId;
611 mTypePool.makeRef(typeName);
612 expectedTypeId++;
613 }
614 expectedTypeId++;
615 mTypePool.makeRef(toString(type->type));
616
617 std::vector<ResourceEntry*> sortedEntries = collectAndSortEntries(type);
618
619 if (!flattenTypeSpec(type, &sortedEntries, buffer)) {
620 return false;
621 }
622
623 if (mOptions.useExtendedChunks) {
624 if (!flattenPublic(type, &sortedEntries, buffer)) {
625 return false;
626 }
627 }
628
629 // The binary resource table lists resource entries for each configuration.
630 // We store them inverted, where a resource entry lists the values for each
631 // configuration available. Here we reverse this to match the binary table.
632 std::map<ConfigDescription, std::vector<FlatEntry>> configToEntryListMap;
633 for (ResourceEntry* entry : sortedEntries) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700634 const uint32_t keyIndex = (uint32_t) mKeyPool.makeRef(entry->name).getIndex();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700635
636 // Group values by configuration.
637 for (auto& configValue : entry->values) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700638 Value* value = configValue.value.get();
639
640 const StringPool::Ref sourceRef = mSourcePool->makeRef(
641 util::utf8ToUtf16(value->getSource().path));
642
643 uint32_t lineNumber = 0;
644 if (value->getSource().line) {
645 lineNumber = value->getSource().line.value();
646 }
647
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700648 const StringPool::Ref commentRef = mSourcePool->makeRef(value->getComment());
649
Adam Lesinskie78fd612015-10-22 12:48:43 -0700650 configToEntryListMap[configValue.config]
651 .push_back(FlatEntry{
652 entry,
653 value,
654 keyIndex,
655 (uint32_t) sourceRef.getIndex(),
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700656 lineNumber,
657 (uint32_t) commentRef.getIndex() });
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700658 }
659 }
660
661 // Flatten a configuration value.
662 for (auto& entry : configToEntryListMap) {
663 if (!flattenConfig(type, entry.first, &entry.second, buffer)) {
664 return false;
665 }
666 }
667 }
668 return true;
669 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700670};
671
672} // namespace
673
674bool TableFlattener::consume(IAaptContext* context, ResourceTable* table) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700675 // We must do this before writing the resources, since the string pool IDs may change.
676 table->stringPool.sort([](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
677 int diff = a.context.priority - b.context.priority;
678 if (diff < 0) return true;
679 if (diff > 0) return false;
680 diff = a.context.config.compare(b.context.config);
681 if (diff < 0) return true;
682 if (diff > 0) return false;
683 return a.value < b.value;
684 });
685 table->stringPool.prune();
686
687 // Write the ResTable header.
688 ChunkWriter tableWriter(mBuffer);
689 ResTable_header* tableHeader = tableWriter.startChunk<ResTable_header>(RES_TABLE_TYPE);
690 tableHeader->packageCount = util::hostToDevice32(table->packages.size());
691
692 // Flatten the values string pool.
693 StringPool::flattenUtf8(tableWriter.getBuffer(), table->stringPool);
694
695 // If we have a reference to a symbol that doesn't exist, we don't know its resource ID.
696 // We encode the name of the symbol along with the offset of where to include the resource ID
697 // once it is found.
698 StringPool symbolPool;
699 std::vector<SymbolWriter::Entry> symbolOffsets;
700
701 // String pool holding the source paths of each value.
702 StringPool sourcePool;
703
704 BigBuffer packageBuffer(1024);
705
706 // Flatten each package.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700707 for (auto& package : table->packages) {
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700708 const size_t beforePackageSize = packageBuffer.size();
709
710 // All packages will share a single global symbol pool.
711 SymbolWriter packageSymbolWriter(&symbolPool);
712
713 PackageFlattener flattener(context->getDiagnostics(), mOptions, package.get(),
714 &packageSymbolWriter, &sourcePool);
715 if (!flattener.flattenPackage(&packageBuffer)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700716 return false;
717 }
718
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700719 // The symbols are offset only from their own Package start. Offset them from the
720 // start of the packageBuffer.
721 packageSymbolWriter.shiftAllOffsets(beforePackageSize);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700722
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700723 // Extract all the symbols to offset
724 symbolOffsets.insert(symbolOffsets.end(),
725 std::make_move_iterator(packageSymbolWriter.symbols.begin()),
726 std::make_move_iterator(packageSymbolWriter.symbols.end()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700727 }
728
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700729 SymbolTable_entry* symbolEntryData = nullptr;
730 if (mOptions.useExtendedChunks) {
731 if (!symbolOffsets.empty()) {
732 // Sort the offsets so we can scan them linearly.
733 std::sort(symbolOffsets.begin(), symbolOffsets.end(),
734 [](const SymbolWriter::Entry& a, const SymbolWriter::Entry& b) -> bool {
735 return a.offset < b.offset;
736 });
737
738 // Write the Symbol header.
739 ChunkWriter symbolWriter(tableWriter.getBuffer());
740 SymbolTable_header* symbolHeader = symbolWriter.startChunk<SymbolTable_header>(
741 RES_TABLE_SYMBOL_TABLE_TYPE);
742 symbolHeader->count = util::hostToDevice32(symbolOffsets.size());
743
744 symbolEntryData = symbolWriter.nextBlock<SymbolTable_entry>(symbolOffsets.size());
745 StringPool::flattenUtf8(symbolWriter.getBuffer(), symbolPool);
746 symbolWriter.finish();
747 }
748
749 if (sourcePool.size() > 0) {
750 // Write out source pool.
751 ChunkWriter srcWriter(tableWriter.getBuffer());
752 srcWriter.startChunk<ResChunk_header>(RES_TABLE_SOURCE_POOL_TYPE);
753 StringPool::flattenUtf8(srcWriter.getBuffer(), sourcePool);
754 srcWriter.finish();
755 }
756 }
757
758 const size_t beforePackagesSize = tableWriter.size();
759
760 // Finally merge all the packages into the main buffer.
761 tableWriter.getBuffer()->appendBuffer(std::move(packageBuffer));
762
763 // Update the offsets to their final values.
764 if (symbolEntryData) {
765 for (SymbolWriter::Entry& entry : symbolOffsets) {
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700766 symbolEntryData->name.index = util::hostToDevice32(entry.name.getIndex());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700767
768 // The symbols were all calculated with the packageBuffer offset. We need to
769 // add the beginning of the output buffer.
770 symbolEntryData->offset = util::hostToDevice32(entry.offset + beforePackagesSize);
771 symbolEntryData++;
772 }
773 }
774
775 tableWriter.finish();
776 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700777}
778
779} // namespace aapt