blob: 46b520592f251e51cd2b61b919d2030e53651e25 [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;
450 }
451
Adam Lesinskie78fd612015-10-22 12:48:43 -0700452 if (!mTable->setSymbolStateAllowMangled(name, resId, symbol, mContext->getDiagnostics())) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700453 return false;
454 }
455
456 // Add this resource name->id mapping to the index so
457 // that we can resolve all ID references to name references.
458 auto cacheIter = mIdIndex.find(resId);
459 if (cacheIter == mIdIndex.end()) {
460 mIdIndex.insert({ resId, name });
461 }
462
463 entry++;
464 }
465 return true;
466}
467
468bool BinaryResourceParser::parseTypeSpec(const ResChunk_header* chunk) {
469 if (mTypePool.getError() != NO_ERROR) {
470 mContext->getDiagnostics()->error(DiagMessage(mSource)
471 << "missing type string pool");
472 return false;
473 }
474
475 const ResTable_typeSpec* typeSpec = convertTo<ResTable_typeSpec>(chunk);
476 if (!typeSpec) {
477 mContext->getDiagnostics()->error(DiagMessage(mSource)
478 << "corrupt ResTable_typeSpec chunk");
479 return false;
480 }
481
482 if (typeSpec->id == 0) {
483 mContext->getDiagnostics()->error(DiagMessage(mSource)
484 << "ResTable_typeSpec has invalid id: " << typeSpec->id);
485 return false;
486 }
487 return true;
488}
489
490bool BinaryResourceParser::parseType(const ResourceTablePackage* package,
491 const ResChunk_header* chunk) {
492 if (mTypePool.getError() != NO_ERROR) {
493 mContext->getDiagnostics()->error(DiagMessage(mSource)
494 << "missing type string pool");
495 return false;
496 }
497
498 if (mKeyPool.getError() != NO_ERROR) {
499 mContext->getDiagnostics()->error(DiagMessage(mSource)
500 << "missing key string pool");
501 return false;
502 }
503
504 const ResTable_type* type = convertTo<ResTable_type>(chunk);
505 if (!type) {
506 mContext->getDiagnostics()->error(DiagMessage(mSource)
507 << "corrupt ResTable_type chunk");
508 return false;
509 }
510
511 if (type->id == 0) {
512 mContext->getDiagnostics()->error(DiagMessage(mSource)
513 << "ResTable_type has invalid id: " << (int) type->id);
514 return false;
515 }
516
517 ConfigDescription config;
518 config.copyFromDtoH(type->config);
519
520 StringPiece16 typeStr16 = util::getString(mTypePool, type->id - 1);
521
522 const ResourceType* parsedType = parseResourceType(typeStr16);
523 if (!parsedType) {
524 mContext->getDiagnostics()->error(DiagMessage(mSource)
525 << "invalid type name '" << typeStr16
526 << "' for type with ID " << (int) type->id);
527 return false;
528 }
529
530 TypeVariant tv(type);
531 for (auto it = tv.beginEntries(); it != tv.endEntries(); ++it) {
532 const ResTable_entry* entry = *it;
533 if (!entry) {
534 continue;
535 }
536
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700537 const ResourceName name(package->name, *parsedType,
538 util::getString(mKeyPool,
539 util::deviceToHost32(entry->key.index)).toString());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700540
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700541 const ResourceId resId(package->id.value(), type->id, static_cast<uint16_t>(it.index()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700542
543 std::unique_ptr<Value> resourceValue;
544 const ResTable_entry_source* sourceBlock = nullptr;
545
546 if (entry->flags & ResTable_entry::FLAG_COMPLEX) {
547 const ResTable_map_entry* mapEntry = static_cast<const ResTable_map_entry*>(entry);
548 if (util::deviceToHost32(mapEntry->size) - sizeof(*mapEntry) == sizeof(*sourceBlock)) {
549 const uint8_t* data = (const uint8_t*) mapEntry;
550 data += util::deviceToHost32(mapEntry->size) - sizeof(*sourceBlock);
551 sourceBlock = (const ResTable_entry_source*) data;
552 }
553
554 // TODO(adamlesinski): Check that the entry count is valid.
555 resourceValue = parseMapEntry(name, config, mapEntry);
556 } else {
557 if (util::deviceToHost32(entry->size) - sizeof(*entry) == sizeof(*sourceBlock)) {
558 const uint8_t* data = (const uint8_t*) entry;
559 data += util::deviceToHost32(entry->size) - sizeof(*sourceBlock);
560 sourceBlock = (const ResTable_entry_source*) data;
561 }
562
563 const Res_value* value = (const Res_value*)(
564 (const uint8_t*) entry + util::deviceToHost32(entry->size));
565 resourceValue = parseValue(name, config, value, entry->flags);
566 }
567
Adam Lesinski467f1712015-11-16 17:35:44 -0800568 if (!resourceValue) {
569 mContext->getDiagnostics()->error(DiagMessage(mSource)
570 << "failed to parse value for resource " << name
571 << " (" << resId << ") with configuration '"
572 << config << "'");
573 return false;
574 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700575
576 Source source = mSource;
577 if (sourceBlock) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800578 StringPiece path = util::getString8(mSourcePool,
579 util::deviceToHost32(sourceBlock->path.index));
580 if (!path.empty()) {
581 source.path = path.toString();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700582 }
583 source.line = util::deviceToHost32(sourceBlock->line);
584 }
585
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700586 StringPiece16 comment = util::getString(mSourcePool,
587 util::deviceToHost32(sourceBlock->comment.index));
588 if (!comment.empty()) {
589 resourceValue->setComment(comment);
590 }
591
Adam Lesinskie78fd612015-10-22 12:48:43 -0700592 resourceValue->setSource(source);
593 if (!mTable->addResourceAllowMangled(name, config, std::move(resourceValue),
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700594 mContext->getDiagnostics())) {
595 return false;
596 }
597
598 if ((entry->flags & ResTable_entry::FLAG_PUBLIC) != 0) {
Adam Lesinskie78fd612015-10-22 12:48:43 -0700599 Symbol symbol;
600 symbol.state = SymbolState::kPublic;
601 symbol.source = mSource.withLine(0);
602 if (!mTable->setSymbolStateAllowMangled(name, resId, symbol,
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700603 mContext->getDiagnostics())) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700604 return false;
605 }
606 }
607
608 // Add this resource name->id mapping to the index so
609 // that we can resolve all ID references to name references.
610 auto cacheIter = mIdIndex.find(resId);
611 if (cacheIter == mIdIndex.end()) {
612 mIdIndex.insert({ resId, name });
613 }
614 }
615 return true;
616}
617
618std::unique_ptr<Item> BinaryResourceParser::parseValue(const ResourceNameRef& name,
619 const ConfigDescription& config,
620 const Res_value* value,
621 uint16_t flags) {
622 if (name.type == ResourceType::kId) {
623 return util::make_unique<Id>();
624 }
625
626 const uint32_t data = util::deviceToHost32(value->data);
627
628 if (value->dataType == Res_value::TYPE_STRING) {
629 StringPiece16 str = util::getString(mValuePool, data);
630
631 const ResStringPool_span* spans = mValuePool.styleAt(data);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700632
633 // Check if the string has a valid style associated with it.
634 if (spans != nullptr && spans->name.index != ResStringPool_span::END) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700635 StyleString styleStr = { str.toString() };
636 while (spans->name.index != ResStringPool_span::END) {
637 styleStr.spans.push_back(Span{
638 util::getString(mValuePool, spans->name.index).toString(),
639 spans->firstChar,
640 spans->lastChar
641 });
642 spans++;
643 }
644 return util::make_unique<StyledString>(mTable->stringPool.makeRef(
645 styleStr, StringPool::Context{1, config}));
646 } else {
647 if (name.type != ResourceType::kString &&
648 util::stringStartsWith<char16_t>(str, u"res/")) {
649 // This must be a FileReference.
650 return util::make_unique<FileReference>(mTable->stringPool.makeRef(
651 str, StringPool::Context{ 0, config }));
652 }
653
654 // There are no styles associated with this string, so treat it as
655 // a simple string.
656 return util::make_unique<String>(mTable->stringPool.makeRef(
657 str, StringPool::Context{1, config}));
658 }
659 }
660
661 if (value->dataType == Res_value::TYPE_REFERENCE ||
662 value->dataType == Res_value::TYPE_ATTRIBUTE) {
663 const Reference::Type type = (value->dataType == Res_value::TYPE_REFERENCE) ?
Adam Lesinski467f1712015-11-16 17:35:44 -0800664 Reference::Type::kResource : Reference::Type::kAttribute;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700665
666 if (data != 0) {
667 // This is a normal reference.
668 return util::make_unique<Reference>(data, type);
669 }
670
671 // This reference has an invalid ID. Check if it is an unresolved symbol.
Adam Lesinski467f1712015-11-16 17:35:44 -0800672 if (Maybe<Reference> ref = getSymbol(&value->data)) {
673 ref.value().referenceType = type;
674 return util::make_unique<Reference>(std::move(ref.value()));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700675 }
676
677 // This is not an unresolved symbol, so it must be the magic @null reference.
678 Res_value nullType = {};
679 nullType.dataType = Res_value::TYPE_REFERENCE;
680 return util::make_unique<BinaryPrimitive>(nullType);
681 }
682
683 if (value->dataType == ExtendedTypes::TYPE_RAW_STRING) {
684 return util::make_unique<RawString>(mTable->stringPool.makeRef(
685 util::getString(mValuePool, data), StringPool::Context{ 1, config }));
686 }
687
688 // Treat this as a raw binary primitive.
689 return util::make_unique<BinaryPrimitive>(*value);
690}
691
692std::unique_ptr<Value> BinaryResourceParser::parseMapEntry(const ResourceNameRef& name,
693 const ConfigDescription& config,
694 const ResTable_map_entry* map) {
695 switch (name.type) {
696 case ResourceType::kStyle:
697 return parseStyle(name, config, map);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700698 case ResourceType::kAttrPrivate:
699 // fallthrough
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700700 case ResourceType::kAttr:
701 return parseAttr(name, config, map);
702 case ResourceType::kArray:
703 return parseArray(name, config, map);
704 case ResourceType::kStyleable:
705 return parseStyleable(name, config, map);
706 case ResourceType::kPlurals:
707 return parsePlural(name, config, map);
708 default:
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700709 assert(false && "unknown map type");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700710 break;
711 }
712 return {};
713}
714
715std::unique_ptr<Style> BinaryResourceParser::parseStyle(const ResourceNameRef& name,
716 const ConfigDescription& config,
717 const ResTable_map_entry* map) {
718 std::unique_ptr<Style> style = util::make_unique<Style>();
719 if (util::deviceToHost32(map->parent.ident) == 0) {
720 // The parent is either not set or it is an unresolved symbol.
721 // Check to see if it is a symbol.
Adam Lesinski467f1712015-11-16 17:35:44 -0800722 style->parent = getSymbol(&map->parent.ident);
723
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700724 } else {
725 // The parent is a regular reference to a resource.
726 style->parent = Reference(util::deviceToHost32(map->parent.ident));
727 }
728
729 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800730 if (Res_INTERNALID(util::deviceToHost32(mapEntry.name.ident))) {
731 if (style->entries.empty()) {
732 mContext->getDiagnostics()->error(DiagMessage(mSource)
733 << "out-of-sequence meta data in style");
734 return {};
735 }
736 collectMetaData(mapEntry, &style->entries.back().key);
737 continue;
738 }
739
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700740 style->entries.emplace_back();
741 Style::Entry& styleEntry = style->entries.back();
742
743 if (util::deviceToHost32(mapEntry.name.ident) == 0) {
744 // The map entry's key (attribute) is not set. This must be
745 // a symbol reference, so resolve it.
Adam Lesinski467f1712015-11-16 17:35:44 -0800746 Maybe<Reference> symbol = getSymbol(&mapEntry.name.ident);
747 if (!symbol) {
748 mContext->getDiagnostics()->error(DiagMessage(mSource)
749 << "unresolved style attribute");
750 return {};
751 }
752 styleEntry.key = std::move(symbol.value());
753
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700754 } else {
755 // The map entry's key (attribute) is a regular reference.
756 styleEntry.key.id = ResourceId(util::deviceToHost32(mapEntry.name.ident));
757 }
758
759 // Parse the attribute's value.
760 styleEntry.value = parseValue(name, config, &mapEntry.value, 0);
Adam Lesinski467f1712015-11-16 17:35:44 -0800761 if (!styleEntry.value) {
762 return {};
763 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700764 }
765 return style;
766}
767
768std::unique_ptr<Attribute> BinaryResourceParser::parseAttr(const ResourceNameRef& name,
769 const ConfigDescription& config,
770 const ResTable_map_entry* map) {
771 const bool isWeak = (util::deviceToHost16(map->flags) & ResTable_entry::FLAG_WEAK) != 0;
772 std::unique_ptr<Attribute> attr = util::make_unique<Attribute>(isWeak);
773
774 // First we must discover what type of attribute this is. Find the type mask.
775 auto typeMaskIter = std::find_if(begin(map), end(map), [](const ResTable_map& entry) -> bool {
776 return util::deviceToHost32(entry.name.ident) == ResTable_map::ATTR_TYPE;
777 });
778
779 if (typeMaskIter != end(map)) {
780 attr->typeMask = util::deviceToHost32(typeMaskIter->value.data);
781 }
782
Adam Lesinskia5870652015-11-20 15:32:30 -0800783 for (const ResTable_map& mapEntry : map) {
784 if (Res_INTERNALID(util::deviceToHost32(mapEntry.name.ident))) {
785 switch (util::deviceToHost32(mapEntry.name.ident)) {
786 case ResTable_map::ATTR_MIN:
787 attr->minInt = static_cast<int32_t>(mapEntry.value.data);
788 break;
789 case ResTable_map::ATTR_MAX:
790 attr->maxInt = static_cast<int32_t>(mapEntry.value.data);
791 break;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700792 }
Adam Lesinskia5870652015-11-20 15:32:30 -0800793 continue;
794 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700795
Adam Lesinskia5870652015-11-20 15:32:30 -0800796 if (attr->typeMask & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700797 Attribute::Symbol symbol;
798 symbol.value = util::deviceToHost32(mapEntry.value.data);
799 if (util::deviceToHost32(mapEntry.name.ident) == 0) {
800 // The map entry's key (id) is not set. This must be
801 // a symbol reference, so resolve it.
Adam Lesinski467f1712015-11-16 17:35:44 -0800802 Maybe<Reference> ref = getSymbol(&mapEntry.name.ident);
803 if (!ref) {
804 mContext->getDiagnostics()->error(DiagMessage(mSource)
805 << "unresolved attribute symbol");
806 return {};
807 }
808 symbol.symbol = std::move(ref.value());
809
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700810 } else {
811 // The map entry's key (id) is a regular reference.
812 symbol.symbol.id = ResourceId(util::deviceToHost32(mapEntry.name.ident));
813 }
814
815 attr->symbols.push_back(std::move(symbol));
816 }
817 }
818
Adam Lesinskia5870652015-11-20 15:32:30 -0800819 // TODO(adamlesinski): Find i80n, attributes.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700820 return attr;
821}
822
Adam Lesinski28cacf02015-11-23 14:22:47 -0800823static bool isMetaDataEntry(const ResTable_map& mapEntry) {
824 switch (util::deviceToHost32(mapEntry.name.ident)) {
825 case ExtendedResTableMapTypes::ATTR_SOURCE_PATH:
826 case ExtendedResTableMapTypes::ATTR_SOURCE_LINE:
827 case ExtendedResTableMapTypes::ATTR_COMMENT:
828 return true;
829 }
830 return false;
831}
832
833bool BinaryResourceParser::collectMetaData(const ResTable_map& mapEntry, Value* value) {
834 switch (util::deviceToHost32(mapEntry.name.ident)) {
835 case ExtendedResTableMapTypes::ATTR_SOURCE_PATH:
836 value->setSource(Source(util::getString8(mSourcePool,
837 util::deviceToHost32(mapEntry.value.data))));
838 return true;
839 break;
840
841 case ExtendedResTableMapTypes::ATTR_SOURCE_LINE:
842 value->setSource(value->getSource().withLine(util::deviceToHost32(mapEntry.value.data)));
843 return true;
844 break;
845
846 case ExtendedResTableMapTypes::ATTR_COMMENT:
847 value->setComment(util::getString(mSourcePool, util::deviceToHost32(mapEntry.value.data)));
848 return true;
849 break;
850 }
851 return false;
852}
853
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700854std::unique_ptr<Array> BinaryResourceParser::parseArray(const ResourceNameRef& name,
855 const ConfigDescription& config,
856 const ResTable_map_entry* map) {
857 std::unique_ptr<Array> array = util::make_unique<Array>();
Adam Lesinski28cacf02015-11-23 14:22:47 -0800858 Source source;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700859 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800860 if (isMetaDataEntry(mapEntry)) {
861 if (array->items.empty()) {
862 mContext->getDiagnostics()->error(DiagMessage(mSource)
863 << "out-of-sequence meta data in array");
864 return {};
865 }
866 collectMetaData(mapEntry, array->items.back().get());
867 continue;
868 }
869
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700870 array->items.push_back(parseValue(name, config, &mapEntry.value, 0));
871 }
872 return array;
873}
874
875std::unique_ptr<Styleable> BinaryResourceParser::parseStyleable(const ResourceNameRef& name,
876 const ConfigDescription& config,
877 const ResTable_map_entry* map) {
878 std::unique_ptr<Styleable> styleable = util::make_unique<Styleable>();
879 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800880 if (isMetaDataEntry(mapEntry)) {
881 if (styleable->entries.empty()) {
882 mContext->getDiagnostics()->error(DiagMessage(mSource)
883 << "out-of-sequence meta data in styleable");
884 return {};
885 }
886 collectMetaData(mapEntry, &styleable->entries.back());
887 continue;
888 }
889
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700890 if (util::deviceToHost32(mapEntry.name.ident) == 0) {
891 // The map entry's key (attribute) is not set. This must be
892 // a symbol reference, so resolve it.
Adam Lesinski467f1712015-11-16 17:35:44 -0800893 Maybe<Reference> ref = getSymbol(&mapEntry.name.ident);
894 if (!ref) {
895 mContext->getDiagnostics()->error(DiagMessage(mSource)
896 << "unresolved styleable symbol");
897 return {};
898 }
899 styleable->entries.emplace_back(std::move(ref.value()));
900
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700901 } else {
902 // The map entry's key (attribute) is a regular reference.
903 styleable->entries.emplace_back(util::deviceToHost32(mapEntry.name.ident));
904 }
905 }
906 return styleable;
907}
908
909std::unique_ptr<Plural> BinaryResourceParser::parsePlural(const ResourceNameRef& name,
910 const ConfigDescription& config,
911 const ResTable_map_entry* map) {
912 std::unique_ptr<Plural> plural = util::make_unique<Plural>();
Adam Lesinski28cacf02015-11-23 14:22:47 -0800913 Item* lastEntry = nullptr;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700914 for (const ResTable_map& mapEntry : map) {
Adam Lesinski28cacf02015-11-23 14:22:47 -0800915 if (isMetaDataEntry(mapEntry)) {
916 if (!lastEntry) {
917 mContext->getDiagnostics()->error(DiagMessage(mSource)
918 << "out-of-sequence meta data in plural");
919 return {};
920 }
921 collectMetaData(mapEntry, lastEntry);
922 continue;
923 }
924
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700925 std::unique_ptr<Item> item = parseValue(name, config, &mapEntry.value, 0);
Adam Lesinski467f1712015-11-16 17:35:44 -0800926 if (!item) {
927 return {};
928 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700929
Adam Lesinski28cacf02015-11-23 14:22:47 -0800930 lastEntry = item.get();
931
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700932 switch (util::deviceToHost32(mapEntry.name.ident)) {
Adam Lesinskia5870652015-11-20 15:32:30 -0800933 case ResTable_map::ATTR_ZERO:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700934 plural->values[Plural::Zero] = std::move(item);
935 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800936 case ResTable_map::ATTR_ONE:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700937 plural->values[Plural::One] = std::move(item);
938 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800939 case ResTable_map::ATTR_TWO:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700940 plural->values[Plural::Two] = std::move(item);
941 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800942 case ResTable_map::ATTR_FEW:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700943 plural->values[Plural::Few] = std::move(item);
944 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800945 case ResTable_map::ATTR_MANY:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700946 plural->values[Plural::Many] = std::move(item);
947 break;
Adam Lesinskia5870652015-11-20 15:32:30 -0800948 case ResTable_map::ATTR_OTHER:
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700949 plural->values[Plural::Other] = std::move(item);
950 break;
951 }
952 }
953 return plural;
954}
955
956} // namespace aapt