blob: 21e476fc9c2910de828221ce36cec056854d383c [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 "ResourceUtils.h"
19#include "ResourceValues.h"
20#include "Source.h"
21#include "ValueVisitor.h"
22
23#include "flatten/ResourceTypeExtensions.h"
24#include "unflatten/BinaryResourceParser.h"
25#include "unflatten/ResChunkPullParser.h"
26#include "util/Util.h"
27
28#include <androidfw/ResourceTypes.h>
29#include <androidfw/TypeWrappers.h>
Elliott Hughese7d2cc32015-12-08 08:57:14 -080030#include <android-base/macros.h>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070031
32#include <map>
33#include <string>
34
35namespace aapt {
36
37using namespace android;
38
39/*
40 * Visitor that converts a reference's resource ID to a resource name,
41 * given a mapping from resource ID to resource name.
42 */
43class ReferenceIdToNameVisitor : public ValueVisitor {
44private:
45 const std::map<ResourceId, ResourceName>* mMapping;
46
47public:
48 using ValueVisitor::visit;
49
50 ReferenceIdToNameVisitor(const std::map<ResourceId, ResourceName>* mapping) :
51 mMapping(mapping) {
52 assert(mMapping);
53 }
54
55 void visit(Reference* reference) override {
56 if (!reference->id || !reference->id.value().isValid()) {
57 return;
58 }
59
60 ResourceId id = reference->id.value();
61 auto cacheIter = mMapping->find(id);
62 if (cacheIter != mMapping->end()) {
63 reference->name = cacheIter->second;
64 reference->id = {};
65 }
66 }
67};
68
69BinaryResourceParser::BinaryResourceParser(IAaptContext* context, ResourceTable* table,
70 const Source& source, const void* data, size_t len) :
71 mContext(context), mTable(table), mSource(source), mData(data), mDataLen(len) {
72}
73
74bool BinaryResourceParser::parse() {
75 ResChunkPullParser parser(mData, mDataLen);
76
77 bool error = false;
78 while(ResChunkPullParser::isGoodEvent(parser.next())) {
79 if (parser.getChunk()->type != android::RES_TABLE_TYPE) {
80 mContext->getDiagnostics()->warn(DiagMessage(mSource)
81 << "unknown chunk of type '"
82 << (int) parser.getChunk()->type << "'");
83 continue;
84 }
85
86 if (!parseTable(parser.getChunk())) {
87 error = true;
88 }
89 }
90
91 if (parser.getEvent() == ResChunkPullParser::Event::BadDocument) {
92 mContext->getDiagnostics()->error(DiagMessage(mSource)
93 << "corrupt resource table: "
94 << parser.getLastError());
95 return false;
96 }
97 return !error;
98}
99
Adam Lesinski467f1712015-11-16 17:35:44 -0800100Maybe<Reference> BinaryResourceParser::getSymbol(const void* data) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700101 if (!mSymbolEntries || mSymbolEntryCount == 0) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800102 return {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700103 }
104
105 if ((uintptr_t) data < (uintptr_t) mData) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800106 return {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700107 }
108
109 // We only support 32 bit offsets right now.
110 const uintptr_t offset = (uintptr_t) data - (uintptr_t) mData;
111 if (offset > std::numeric_limits<uint32_t>::max()) {
Adam Lesinski467f1712015-11-16 17:35:44 -0800112 return {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700113 }
114
115 for (size_t i = 0; i < mSymbolEntryCount; i++) {
116 if (util::deviceToHost32(mSymbolEntries[i].offset) == offset) {
117 // This offset is a symbol!
118 const StringPiece16 str = util::getString(
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700119 mSymbolPool, util::deviceToHost32(mSymbolEntries[i].name.index));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120
Adam Lesinski467f1712015-11-16 17:35:44 -0800121 ResourceNameRef nameRef;
122 bool privateRef = false;
123 if (!ResourceUtils::parseResourceName(str, &nameRef, &privateRef)) {
124 return {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700125 }
126
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700127 // Since we scan the symbol table in order, we can start looking for the
128 // next symbol from this point.
129 mSymbolEntryCount -= i + 1;
130 mSymbolEntries += i + 1;
Adam Lesinski467f1712015-11-16 17:35:44 -0800131
132 Reference ref(nameRef);
133 ref.privateReference = privateRef;
134 return Maybe<Reference>(std::move(ref));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700135 }
136 }
Adam Lesinski467f1712015-11-16 17:35:44 -0800137 return {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700138}
139
140/**
141 * Parses the SymbolTable_header, which is present on non-final resource tables
142 * after the compile phase.
143 *
144 * | SymbolTable_header |
145 * |--------------------|
146 * |SymbolTable_entry 0 |
147 * |SymbolTable_entry 1 |
148 * | ... |
149 * |SymbolTable_entry n |
150 * |--------------------|
151 *
152 */
153bool BinaryResourceParser::parseSymbolTable(const ResChunk_header* chunk) {
154 const SymbolTable_header* header = convertTo<SymbolTable_header>(chunk);
155 if (!header) {
156 mContext->getDiagnostics()->error(DiagMessage(mSource)
157 << "corrupt SymbolTable_header");
158 return false;
159 }
160
161 const uint32_t entrySizeBytes =
162 util::deviceToHost32(header->count) * sizeof(SymbolTable_entry);
163 if (entrySizeBytes > getChunkDataLen(&header->header)) {
164 mContext->getDiagnostics()->error(DiagMessage(mSource)
165 << "SymbolTable_header data section too long");
166 return false;
167 }
168
169 mSymbolEntries = (const SymbolTable_entry*) getChunkData(&header->header);
170 mSymbolEntryCount = util::deviceToHost32(header->count);
171
172 // Skip over the symbol entries and parse the StringPool chunk that should be next.
173 ResChunkPullParser parser(getChunkData(&header->header) + entrySizeBytes,
174 getChunkDataLen(&header->header) - entrySizeBytes);
175 if (!ResChunkPullParser::isGoodEvent(parser.next())) {
176 mContext->getDiagnostics()->error(DiagMessage(mSource)
177 << "failed to parse chunk in SymbolTable: "
178 << parser.getLastError());
179 return false;
180 }
181
182 const ResChunk_header* nextChunk = parser.getChunk();
183 if (util::deviceToHost16(nextChunk->type) != android::RES_STRING_POOL_TYPE) {
184 mContext->getDiagnostics()->error(DiagMessage(mSource)
185 << "expected string pool in SymbolTable but got "
186 << "chunk of type "
187 << (int) util::deviceToHost16(nextChunk->type));
188 return false;
189 }
190
191 if (mSymbolPool.setTo(nextChunk, util::deviceToHost32(nextChunk->size)) != NO_ERROR) {
192 mContext->getDiagnostics()->error(DiagMessage(mSource)
193 << "corrupt string pool in SymbolTable: "
194 << mSymbolPool.getError());
195 return false;
196 }
197 return true;
198}
199
200/**
201 * Parses the resource table, which contains all the packages, types, and entries.
202 */
203bool BinaryResourceParser::parseTable(const ResChunk_header* chunk) {
204 const ResTable_header* tableHeader = convertTo<ResTable_header>(chunk);
205 if (!tableHeader) {
206 mContext->getDiagnostics()->error(DiagMessage(mSource) << "corrupt ResTable_header chunk");
207 return false;
208 }
209
210 ResChunkPullParser parser(getChunkData(&tableHeader->header),
211 getChunkDataLen(&tableHeader->header));
212 while (ResChunkPullParser::isGoodEvent(parser.next())) {
213 switch (util::deviceToHost16(parser.getChunk()->type)) {
214 case android::RES_STRING_POOL_TYPE:
215 if (mValuePool.getError() == NO_INIT) {
216 status_t err = mValuePool.setTo(parser.getChunk(),
217 util::deviceToHost32(parser.getChunk()->size));
218 if (err != NO_ERROR) {
219 mContext->getDiagnostics()->error(DiagMessage(mSource)
220 << "corrupt string pool in ResTable: "
221 << mValuePool.getError());
222 return false;
223 }
224
225 // Reserve some space for the strings we are going to add.
226 mTable->stringPool.hintWillAdd(mValuePool.size(), mValuePool.styleCount());
227 } else {
228 mContext->getDiagnostics()->warn(DiagMessage(mSource)
229 << "unexpected string pool in ResTable");
230 }
231 break;
232
233 case RES_TABLE_SYMBOL_TABLE_TYPE:
234 if (!parseSymbolTable(parser.getChunk())) {
235 return false;
236 }
237 break;
238
239 case RES_TABLE_SOURCE_POOL_TYPE: {
240 status_t err = mSourcePool.setTo(getChunkData(parser.getChunk()),
241 getChunkDataLen(parser.getChunk()));
242 if (err != NO_ERROR) {
243 mContext->getDiagnostics()->error(DiagMessage(mSource)
244 << "corrupt source string pool in ResTable: "
245 << mSourcePool.getError());
246 return false;
247 }
248 break;
249 }
250
251 case android::RES_TABLE_PACKAGE_TYPE:
252 if (!parsePackage(parser.getChunk())) {
253 return false;
254 }
255 break;
256
257 default:
258 mContext->getDiagnostics()
259 ->warn(DiagMessage(mSource)
260 << "unexpected chunk type "
261 << (int) util::deviceToHost16(parser.getChunk()->type));
262 break;
263 }
264 }
265
266 if (parser.getEvent() == ResChunkPullParser::Event::BadDocument) {
267 mContext->getDiagnostics()->error(DiagMessage(mSource)
268 << "corrupt resource table: " << parser.getLastError());
269 return false;
270 }
271 return true;
272}
273
274
275bool BinaryResourceParser::parsePackage(const ResChunk_header* chunk) {
276 const ResTable_package* packageHeader = convertTo<ResTable_package>(chunk);
277 if (!packageHeader) {
278 mContext->getDiagnostics()->error(DiagMessage(mSource)
279 << "corrupt ResTable_package chunk");
280 return false;
281 }
282
283 uint32_t packageId = util::deviceToHost32(packageHeader->id);
284 if (packageId > std::numeric_limits<uint8_t>::max()) {
285 mContext->getDiagnostics()->error(DiagMessage(mSource)
286 << "package ID is too big (" << packageId << ")");
287 return false;
288 }
289
290 // Extract the package name.
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700291 size_t len = strnlen16((const char16_t*) packageHeader->name, arraysize(packageHeader->name));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700292 std::u16string packageName;
293 packageName.resize(len);
294 for (size_t i = 0; i < len; i++) {
295 packageName[i] = util::deviceToHost16(packageHeader->name[i]);
296 }
297
298 ResourceTablePackage* package = mTable->createPackage(packageName, (uint8_t) packageId);
299 if (!package) {
300 mContext->getDiagnostics()->error(DiagMessage(mSource)
301 << "incompatible package '" << packageName
302 << "' with ID " << packageId);
303 return false;
304 }
305
Adam Lesinskie352b992015-11-16 11:59:14 -0800306 // There can be multiple packages in a table, so
307 // clear the type and key pool in case they were set from a previous package.
308 mTypePool.uninit();
309 mKeyPool.uninit();
310
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700311 ResChunkPullParser parser(getChunkData(&packageHeader->header),
312 getChunkDataLen(&packageHeader->header));
313 while (ResChunkPullParser::isGoodEvent(parser.next())) {
314 switch (util::deviceToHost16(parser.getChunk()->type)) {
315 case android::RES_STRING_POOL_TYPE:
316 if (mTypePool.getError() == NO_INIT) {
317 status_t err = mTypePool.setTo(parser.getChunk(),
318 util::deviceToHost32(parser.getChunk()->size));
319 if (err != NO_ERROR) {
320 mContext->getDiagnostics()->error(DiagMessage(mSource)
321 << "corrupt type string pool in "
322 << "ResTable_package: "
323 << mTypePool.getError());
324 return false;
325 }
326 } else if (mKeyPool.getError() == NO_INIT) {
327 status_t err = mKeyPool.setTo(parser.getChunk(),
328 util::deviceToHost32(parser.getChunk()->size));
329 if (err != NO_ERROR) {
330 mContext->getDiagnostics()->error(DiagMessage(mSource)
331 << "corrupt key string pool in "
332 << "ResTable_package: "
333 << mKeyPool.getError());
334 return false;
335 }
336 } else {
337 mContext->getDiagnostics()->warn(DiagMessage(mSource) << "unexpected string pool");
338 }
339 break;
340
341 case android::RES_TABLE_TYPE_SPEC_TYPE:
342 if (!parseTypeSpec(parser.getChunk())) {
343 return false;
344 }
345 break;
346
347 case android::RES_TABLE_TYPE_TYPE:
348 if (!parseType(package, parser.getChunk())) {
349 return false;
350 }
351 break;
352
353 case RES_TABLE_PUBLIC_TYPE:
354 if (!parsePublic(package, parser.getChunk())) {
355 return false;
356 }
357 break;
358
359 default:
360 mContext->getDiagnostics()
361 ->warn(DiagMessage(mSource)
362 << "unexpected chunk type "
363 << (int) util::deviceToHost16(parser.getChunk()->type));
364 break;
365 }
366 }
367
368 if (parser.getEvent() == ResChunkPullParser::Event::BadDocument) {
369 mContext->getDiagnostics()->error(DiagMessage(mSource)
370 << "corrupt ResTable_package: "
371 << parser.getLastError());
372 return false;
373 }
374
375 // Now go through the table and change local resource ID references to
376 // symbolic references.
377 ReferenceIdToNameVisitor visitor(&mIdIndex);
378 for (auto& package : mTable->packages) {
379 for (auto& type : package->types) {
380 for (auto& entry : type->entries) {
381 for (auto& configValue : entry->values) {
382 configValue.value->accept(&visitor);
383 }
384 }
385 }
386 }
387 return true;
388}
389
390bool BinaryResourceParser::parsePublic(const ResourceTablePackage* package,
391 const ResChunk_header* chunk) {
392 const Public_header* header = convertTo<Public_header>(chunk);
393 if (!header) {
394 mContext->getDiagnostics()->error(DiagMessage(mSource)
395 << "corrupt Public_header chunk");
396 return false;
397 }
398
399 if (header->typeId == 0) {
400 mContext->getDiagnostics()->error(DiagMessage(mSource)
401 << "invalid type ID "
402 << (int) header->typeId);
403 return false;
404 }
405
406 StringPiece16 typeStr16 = util::getString(mTypePool, header->typeId - 1);
407 const ResourceType* parsedType = parseResourceType(typeStr16);
408 if (!parsedType) {
409 mContext->getDiagnostics()->error(DiagMessage(mSource)
410 << "invalid type '" << typeStr16 << "'");
411 return false;
412 }
413
414 const uintptr_t chunkEnd = (uintptr_t) chunk + util::deviceToHost32(chunk->size);
415 const Public_entry* entry = (const Public_entry*) getChunkData(&header->header);
416 for (uint32_t i = 0; i < util::deviceToHost32(header->count); i++) {
417 if ((uintptr_t) entry + sizeof(*entry) > chunkEnd) {
418 mContext->getDiagnostics()->error(DiagMessage(mSource)
419 << "Public_entry data section is too long");
420 return false;
421 }
422
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700423 const ResourceId resId(package->id.value(), header->typeId,
424 util::deviceToHost16(entry->entryId));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700425
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700426 const ResourceName name(package->name, *parsedType,
427 util::getString(mKeyPool, entry->key.index).toString());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700428
Adam Lesinskie78fd612015-10-22 12:48:43 -0700429 Symbol symbol;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700430 if (mSourcePool.getError() == NO_ERROR) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700431 symbol.source.path = util::utf16ToUtf8(util::getString(
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700432 mSourcePool, util::deviceToHost32(entry->source.path.index)));
433 symbol.source.line = util::deviceToHost32(entry->source.line);
434 }
435
436 StringPiece16 comment = util::getString(mSourcePool,
437 util::deviceToHost32(entry->source.comment.index));
438 if (!comment.empty()) {
439 symbol.comment = comment.toString();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700440 }
441
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700442 switch (util::deviceToHost16(entry->state)) {
443 case Public_entry::kPrivate:
Adam Lesinskie78fd612015-10-22 12:48:43 -0700444 symbol.state = SymbolState::kPrivate;
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700445 break;
446
447 case Public_entry::kPublic:
Adam Lesinskie78fd612015-10-22 12:48:43 -0700448 symbol.state = SymbolState::kPublic;
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700449 break;
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800450
451 case Public_entry::kUndefined:
452 symbol.state = SymbolState::kUndefined;
453 break;
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700454 }
455
Adam Lesinskie78fd612015-10-22 12:48:43 -0700456 if (!mTable->setSymbolStateAllowMangled(name, resId, symbol, mContext->getDiagnostics())) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700457 return false;
458 }
459
460 // Add this resource name->id mapping to the index so
461 // that we can resolve all ID references to name references.
462 auto cacheIter = mIdIndex.find(resId);
463 if (cacheIter == mIdIndex.end()) {
464 mIdIndex.insert({ resId, name });
465 }
466
467 entry++;
468 }
469 return true;
470}
471
472bool BinaryResourceParser::parseTypeSpec(const ResChunk_header* chunk) {
473 if (mTypePool.getError() != NO_ERROR) {
474 mContext->getDiagnostics()->error(DiagMessage(mSource)
475 << "missing type string pool");
476 return false;
477 }
478
479 const ResTable_typeSpec* typeSpec = convertTo<ResTable_typeSpec>(chunk);
480 if (!typeSpec) {
481 mContext->getDiagnostics()->error(DiagMessage(mSource)
482 << "corrupt ResTable_typeSpec chunk");
483 return false;
484 }
485
486 if (typeSpec->id == 0) {
487 mContext->getDiagnostics()->error(DiagMessage(mSource)
488 << "ResTable_typeSpec has invalid id: " << typeSpec->id);
489 return false;
490 }
491 return true;
492}
493
494bool BinaryResourceParser::parseType(const ResourceTablePackage* package,
495 const ResChunk_header* chunk) {
496 if (mTypePool.getError() != NO_ERROR) {
497 mContext->getDiagnostics()->error(DiagMessage(mSource)
498 << "missing type string pool");
499 return false;
500 }
501
502 if (mKeyPool.getError() != NO_ERROR) {
503 mContext->getDiagnostics()->error(DiagMessage(mSource)
504 << "missing key string pool");
505 return false;
506 }
507
508 const ResTable_type* type = convertTo<ResTable_type>(chunk);
509 if (!type) {
510 mContext->getDiagnostics()->error(DiagMessage(mSource)
511 << "corrupt ResTable_type chunk");
512 return false;
513 }
514
515 if (type->id == 0) {
516 mContext->getDiagnostics()->error(DiagMessage(mSource)
517 << "ResTable_type has invalid id: " << (int) type->id);
518 return false;
519 }
520
521 ConfigDescription config;
522 config.copyFromDtoH(type->config);
523
524 StringPiece16 typeStr16 = util::getString(mTypePool, type->id - 1);
525
526 const ResourceType* parsedType = parseResourceType(typeStr16);
527 if (!parsedType) {
528 mContext->getDiagnostics()->error(DiagMessage(mSource)
529 << "invalid type name '" << typeStr16
530 << "' for type with ID " << (int) type->id);
531 return false;
532 }
533
534 TypeVariant tv(type);
535 for (auto it = tv.beginEntries(); it != tv.endEntries(); ++it) {
536 const ResTable_entry* entry = *it;
537 if (!entry) {
538 continue;
539 }
540
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700541 const ResourceName name(package->name, *parsedType,
542 util::getString(mKeyPool,
543 util::deviceToHost32(entry->key.index)).toString());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700544
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700545 const ResourceId resId(package->id.value(), type->id, static_cast<uint16_t>(it.index()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700546
547 std::unique_ptr<Value> resourceValue;
548 const ResTable_entry_source* sourceBlock = nullptr;
549
550 if (entry->flags & ResTable_entry::FLAG_COMPLEX) {
551 const ResTable_map_entry* mapEntry = static_cast<const ResTable_map_entry*>(entry);
552 if (util::deviceToHost32(mapEntry->size) - sizeof(*mapEntry) == sizeof(*sourceBlock)) {
553 const uint8_t* data = (const uint8_t*) mapEntry;
554 data += util::deviceToHost32(mapEntry->size) - sizeof(*sourceBlock);
555 sourceBlock = (const ResTable_entry_source*) data;
556 }
557
558 // TODO(adamlesinski): Check that the entry count is valid.
559 resourceValue = parseMapEntry(name, config, mapEntry);
560 } else {
561 if (util::deviceToHost32(entry->size) - sizeof(*entry) == sizeof(*sourceBlock)) {
562 const uint8_t* data = (const uint8_t*) entry;
563 data += util::deviceToHost32(entry->size) - sizeof(*sourceBlock);
564 sourceBlock = (const ResTable_entry_source*) data;
565 }
566
567 const Res_value* value = (const Res_value*)(
568 (const uint8_t*) entry + util::deviceToHost32(entry->size));
569 resourceValue = parseValue(name, config, value, entry->flags);
570 }
571
Adam Lesinski467f1712015-11-16 17:35:44 -0800572 if (!resourceValue) {
573 mContext->getDiagnostics()->error(DiagMessage(mSource)
574 << "failed to parse value for resource " << name
575 << " (" << resId << ") with configuration '"
576 << config << "'");
577 return false;
578 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700579
580 Source source = mSource;
581 if (sourceBlock) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800582 StringPiece path = util::getString8(mSourcePool,
583 util::deviceToHost32(sourceBlock->path.index));
584 if (!path.empty()) {
585 source.path = path.toString();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700586 }
587 source.line = util::deviceToHost32(sourceBlock->line);
588 }
589
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700590 StringPiece16 comment = util::getString(mSourcePool,
591 util::deviceToHost32(sourceBlock->comment.index));
592 if (!comment.empty()) {
593 resourceValue->setComment(comment);
594 }
595
Adam Lesinskie78fd612015-10-22 12:48:43 -0700596 resourceValue->setSource(source);
597 if (!mTable->addResourceAllowMangled(name, config, std::move(resourceValue),
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700598 mContext->getDiagnostics())) {
599 return false;
600 }
601
602 if ((entry->flags & ResTable_entry::FLAG_PUBLIC) != 0) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700603 Symbol symbol;
604 symbol.state = SymbolState::kPublic;
605 symbol.source = mSource.withLine(0);
606 if (!mTable->setSymbolStateAllowMangled(name, resId, symbol,
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700607 mContext->getDiagnostics())) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700608 return false;
609 }
610 }
611
612 // Add this resource name->id mapping to the index so
613 // that we can resolve all ID references to name references.
614 auto cacheIter = mIdIndex.find(resId);
615 if (cacheIter == mIdIndex.end()) {
616 mIdIndex.insert({ resId, name });
617 }
618 }
619 return true;
620}
621
622std::unique_ptr<Item> BinaryResourceParser::parseValue(const ResourceNameRef& name,
623 const ConfigDescription& config,
624 const Res_value* value,
625 uint16_t flags) {
626 if (name.type == ResourceType::kId) {
627 return util::make_unique<Id>();
628 }
629
630 const uint32_t data = util::deviceToHost32(value->data);
631
632 if (value->dataType == Res_value::TYPE_STRING) {
633 StringPiece16 str = util::getString(mValuePool, data);
634
635 const ResStringPool_span* spans = mValuePool.styleAt(data);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700636
637 // Check if the string has a valid style associated with it.
638 if (spans != nullptr && spans->name.index != ResStringPool_span::END) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700639 StyleString styleStr = { str.toString() };
640 while (spans->name.index != ResStringPool_span::END) {
641 styleStr.spans.push_back(Span{
642 util::getString(mValuePool, spans->name.index).toString(),
643 spans->firstChar,
644 spans->lastChar
645 });
646 spans++;
647 }
648 return util::make_unique<StyledString>(mTable->stringPool.makeRef(
649 styleStr, StringPool::Context{1, config}));
650 } else {
651 if (name.type != ResourceType::kString &&
652 util::stringStartsWith<char16_t>(str, u"res/")) {
653 // This must be a FileReference.
654 return util::make_unique<FileReference>(mTable->stringPool.makeRef(
655 str, StringPool::Context{ 0, config }));
656 }
657
658 // There are no styles associated with this string, so treat it as
659 // a simple string.
660 return util::make_unique<String>(mTable->stringPool.makeRef(
661 str, StringPool::Context{1, config}));
662 }
663 }
664
665 if (value->dataType == Res_value::TYPE_REFERENCE ||
666 value->dataType == Res_value::TYPE_ATTRIBUTE) {
667 const Reference::Type type = (value->dataType == Res_value::TYPE_REFERENCE) ?
Adam Lesinski467f1712015-11-16 17:35:44 -0800668 Reference::Type::kResource : Reference::Type::kAttribute;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700669
670 if (data != 0) {
671 // This is a normal reference.
672 return util::make_unique<Reference>(data, type);
673 }
674
675 // This reference has an invalid ID. Check if it is an unresolved symbol.
Adam Lesinski467f1712015-11-16 17:35:44 -0800676 if (Maybe<Reference> ref = getSymbol(&value->data)) {
677 ref.value().referenceType = type;
678 return util::make_unique<Reference>(std::move(ref.value()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700679 }
680
681 // This is not an unresolved symbol, so it must be the magic @null reference.
682 Res_value nullType = {};
683 nullType.dataType = Res_value::TYPE_REFERENCE;
684 return util::make_unique<BinaryPrimitive>(nullType);
685 }
686
687 if (value->dataType == ExtendedTypes::TYPE_RAW_STRING) {
688 return util::make_unique<RawString>(mTable->stringPool.makeRef(
689 util::getString(mValuePool, data), StringPool::Context{ 1, config }));
690 }
691
692 // Treat this as a raw binary primitive.
693 return util::make_unique<BinaryPrimitive>(*value);
694}
695
696std::unique_ptr<Value> BinaryResourceParser::parseMapEntry(const ResourceNameRef& name,
697 const ConfigDescription& config,
698 const ResTable_map_entry* map) {
699 switch (name.type) {
700 case ResourceType::kStyle:
701 return parseStyle(name, config, map);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700702 case ResourceType::kAttrPrivate:
703 // fallthrough
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700704 case ResourceType::kAttr:
705 return parseAttr(name, config, map);
706 case ResourceType::kArray:
707 return parseArray(name, config, map);
708 case ResourceType::kStyleable:
709 return parseStyleable(name, config, map);
710 case ResourceType::kPlurals:
711 return parsePlural(name, config, map);
712 default:
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700713 assert(false && "unknown map type");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700714 break;
715 }
716 return {};
717}
718
719std::unique_ptr<Style> BinaryResourceParser::parseStyle(const ResourceNameRef& name,
720 const ConfigDescription& config,
721 const ResTable_map_entry* map) {
722 std::unique_ptr<Style> style = util::make_unique<Style>();
723 if (util::deviceToHost32(map->parent.ident) == 0) {
724 // The parent is either not set or it is an unresolved symbol.
725 // Check to see if it is a symbol.
Adam Lesinski467f1712015-11-16 17:35:44 -0800726 style->parent = getSymbol(&map->parent.ident);
727
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700728 } else {
729 // The parent is a regular reference to a resource.
730 style->parent = Reference(util::deviceToHost32(map->parent.ident));
731 }
732
733 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800734 if (Res_INTERNALID(util::deviceToHost32(mapEntry.name.ident))) {
735 if (style->entries.empty()) {
736 mContext->getDiagnostics()->error(DiagMessage(mSource)
737 << "out-of-sequence meta data in style");
738 return {};
739 }
740 collectMetaData(mapEntry, &style->entries.back().key);
741 continue;
742 }
743
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700744 style->entries.emplace_back();
745 Style::Entry& styleEntry = style->entries.back();
746
747 if (util::deviceToHost32(mapEntry.name.ident) == 0) {
748 // The map entry's key (attribute) is not set. This must be
749 // a symbol reference, so resolve it.
Adam Lesinski467f1712015-11-16 17:35:44 -0800750 Maybe<Reference> symbol = getSymbol(&mapEntry.name.ident);
751 if (!symbol) {
752 mContext->getDiagnostics()->error(DiagMessage(mSource)
753 << "unresolved style attribute");
754 return {};
755 }
756 styleEntry.key = std::move(symbol.value());
757
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700758 } else {
759 // The map entry's key (attribute) is a regular reference.
760 styleEntry.key.id = ResourceId(util::deviceToHost32(mapEntry.name.ident));
761 }
762
763 // Parse the attribute's value.
764 styleEntry.value = parseValue(name, config, &mapEntry.value, 0);
Adam Lesinski467f1712015-11-16 17:35:44 -0800765 if (!styleEntry.value) {
766 return {};
767 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700768 }
769 return style;
770}
771
772std::unique_ptr<Attribute> BinaryResourceParser::parseAttr(const ResourceNameRef& name,
773 const ConfigDescription& config,
774 const ResTable_map_entry* map) {
775 const bool isWeak = (util::deviceToHost16(map->flags) & ResTable_entry::FLAG_WEAK) != 0;
776 std::unique_ptr<Attribute> attr = util::make_unique<Attribute>(isWeak);
777
778 // First we must discover what type of attribute this is. Find the type mask.
779 auto typeMaskIter = std::find_if(begin(map), end(map), [](const ResTable_map& entry) -> bool {
780 return util::deviceToHost32(entry.name.ident) == ResTable_map::ATTR_TYPE;
781 });
782
783 if (typeMaskIter != end(map)) {
784 attr->typeMask = util::deviceToHost32(typeMaskIter->value.data);
785 }
786
Adam Lesinskia5870652015-11-20 15:32:30 -0800787 for (const ResTable_map& mapEntry : map) {
788 if (Res_INTERNALID(util::deviceToHost32(mapEntry.name.ident))) {
789 switch (util::deviceToHost32(mapEntry.name.ident)) {
790 case ResTable_map::ATTR_MIN:
791 attr->minInt = static_cast<int32_t>(mapEntry.value.data);
792 break;
793 case ResTable_map::ATTR_MAX:
794 attr->maxInt = static_cast<int32_t>(mapEntry.value.data);
795 break;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700796 }
Adam Lesinskia5870652015-11-20 15:32:30 -0800797 continue;
798 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700799
Adam Lesinskia5870652015-11-20 15:32:30 -0800800 if (attr->typeMask & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700801 Attribute::Symbol symbol;
802 symbol.value = util::deviceToHost32(mapEntry.value.data);
803 if (util::deviceToHost32(mapEntry.name.ident) == 0) {
804 // The map entry's key (id) is not set. This must be
805 // a symbol reference, so resolve it.
Adam Lesinski467f1712015-11-16 17:35:44 -0800806 Maybe<Reference> ref = getSymbol(&mapEntry.name.ident);
807 if (!ref) {
808 mContext->getDiagnostics()->error(DiagMessage(mSource)
809 << "unresolved attribute symbol");
810 return {};
811 }
812 symbol.symbol = std::move(ref.value());
813
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700814 } else {
815 // The map entry's key (id) is a regular reference.
816 symbol.symbol.id = ResourceId(util::deviceToHost32(mapEntry.name.ident));
817 }
818
819 attr->symbols.push_back(std::move(symbol));
820 }
821 }
822
Adam Lesinskia5870652015-11-20 15:32:30 -0800823 // TODO(adamlesinski): Find i80n, attributes.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700824 return attr;
825}
826
Adam Lesinski28cacf02015-11-23 14:22:47 -0800827static bool isMetaDataEntry(const ResTable_map& mapEntry) {
828 switch (util::deviceToHost32(mapEntry.name.ident)) {
829 case ExtendedResTableMapTypes::ATTR_SOURCE_PATH:
830 case ExtendedResTableMapTypes::ATTR_SOURCE_LINE:
831 case ExtendedResTableMapTypes::ATTR_COMMENT:
832 return true;
833 }
834 return false;
835}
836
837bool BinaryResourceParser::collectMetaData(const ResTable_map& mapEntry, Value* value) {
838 switch (util::deviceToHost32(mapEntry.name.ident)) {
839 case ExtendedResTableMapTypes::ATTR_SOURCE_PATH:
840 value->setSource(Source(util::getString8(mSourcePool,
841 util::deviceToHost32(mapEntry.value.data))));
842 return true;
843 break;
844
845 case ExtendedResTableMapTypes::ATTR_SOURCE_LINE:
846 value->setSource(value->getSource().withLine(util::deviceToHost32(mapEntry.value.data)));
847 return true;
848 break;
849
850 case ExtendedResTableMapTypes::ATTR_COMMENT:
851 value->setComment(util::getString(mSourcePool, util::deviceToHost32(mapEntry.value.data)));
852 return true;
853 break;
854 }
855 return false;
856}
857
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700858std::unique_ptr<Array> BinaryResourceParser::parseArray(const ResourceNameRef& name,
859 const ConfigDescription& config,
860 const ResTable_map_entry* map) {
861 std::unique_ptr<Array> array = util::make_unique<Array>();
Adam Lesinski28cacf02015-11-23 14:22:47 -0800862 Source source;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700863 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800864 if (isMetaDataEntry(mapEntry)) {
865 if (array->items.empty()) {
866 mContext->getDiagnostics()->error(DiagMessage(mSource)
867 << "out-of-sequence meta data in array");
868 return {};
869 }
870 collectMetaData(mapEntry, array->items.back().get());
871 continue;
872 }
873
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700874 array->items.push_back(parseValue(name, config, &mapEntry.value, 0));
875 }
876 return array;
877}
878
879std::unique_ptr<Styleable> BinaryResourceParser::parseStyleable(const ResourceNameRef& name,
880 const ConfigDescription& config,
881 const ResTable_map_entry* map) {
882 std::unique_ptr<Styleable> styleable = util::make_unique<Styleable>();
883 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800884 if (isMetaDataEntry(mapEntry)) {
885 if (styleable->entries.empty()) {
886 mContext->getDiagnostics()->error(DiagMessage(mSource)
887 << "out-of-sequence meta data in styleable");
888 return {};
889 }
890 collectMetaData(mapEntry, &styleable->entries.back());
891 continue;
892 }
893
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700894 if (util::deviceToHost32(mapEntry.name.ident) == 0) {
895 // The map entry's key (attribute) is not set. This must be
896 // a symbol reference, so resolve it.
Adam Lesinski467f1712015-11-16 17:35:44 -0800897 Maybe<Reference> ref = getSymbol(&mapEntry.name.ident);
898 if (!ref) {
899 mContext->getDiagnostics()->error(DiagMessage(mSource)
900 << "unresolved styleable symbol");
901 return {};
902 }
903 styleable->entries.emplace_back(std::move(ref.value()));
904
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700905 } else {
906 // The map entry's key (attribute) is a regular reference.
907 styleable->entries.emplace_back(util::deviceToHost32(mapEntry.name.ident));
908 }
909 }
910 return styleable;
911}
912
913std::unique_ptr<Plural> BinaryResourceParser::parsePlural(const ResourceNameRef& name,
914 const ConfigDescription& config,
915 const ResTable_map_entry* map) {
916 std::unique_ptr<Plural> plural = util::make_unique<Plural>();
Adam Lesinski28cacf02015-11-23 14:22:47 -0800917 Item* lastEntry = nullptr;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700918 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800919 if (isMetaDataEntry(mapEntry)) {
920 if (!lastEntry) {
921 mContext->getDiagnostics()->error(DiagMessage(mSource)
922 << "out-of-sequence meta data in plural");
923 return {};
924 }
925 collectMetaData(mapEntry, lastEntry);
926 continue;
927 }
928
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700929 std::unique_ptr<Item> item = parseValue(name, config, &mapEntry.value, 0);
Adam Lesinski467f1712015-11-16 17:35:44 -0800930 if (!item) {
931 return {};
932 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700933
Adam Lesinski28cacf02015-11-23 14:22:47 -0800934 lastEntry = item.get();
935
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700936 switch (util::deviceToHost32(mapEntry.name.ident)) {
Adam Lesinskia5870652015-11-20 15:32:30 -0800937 case ResTable_map::ATTR_ZERO:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700938 plural->values[Plural::Zero] = std::move(item);
939 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800940 case ResTable_map::ATTR_ONE:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700941 plural->values[Plural::One] = std::move(item);
942 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800943 case ResTable_map::ATTR_TWO:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700944 plural->values[Plural::Two] = std::move(item);
945 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800946 case ResTable_map::ATTR_FEW:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700947 plural->values[Plural::Few] = std::move(item);
948 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800949 case ResTable_map::ATTR_MANY:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700950 plural->values[Plural::Many] = std::move(item);
951 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800952 case ResTable_map::ATTR_OTHER:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700953 plural->values[Plural::Other] = std::move(item);
954 break;
955 }
956 }
957 return plural;
958}
959
960} // namespace aapt