• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 "format/binary/BinaryResourceParser.h"
18 
19 #include <algorithm>
20 #include <map>
21 #include <string>
22 
23 #include "android-base/logging.h"
24 #include "android-base/macros.h"
25 #include "android-base/stringprintf.h"
26 #include "androidfw/ResourceTypes.h"
27 #include "androidfw/TypeWrappers.h"
28 
29 #include "ResourceTable.h"
30 #include "ResourceUtils.h"
31 #include "ResourceValues.h"
32 #include "Source.h"
33 #include "ValueVisitor.h"
34 #include "format/binary/ResChunkPullParser.h"
35 #include "util/Util.h"
36 
37 using namespace android;
38 
39 using ::android::base::StringPrintf;
40 
41 namespace aapt {
42 
43 namespace {
44 
strcpy16_dtoh(const char16_t * src,size_t len)45 static std::u16string strcpy16_dtoh(const char16_t* src, size_t len) {
46   size_t utf16_len = strnlen16(src, len);
47   if (utf16_len == 0) {
48     return {};
49   }
50   std::u16string dst;
51   dst.resize(utf16_len);
52   for (size_t i = 0; i < utf16_len; i++) {
53     dst[i] = util::DeviceToHost16(src[i]);
54   }
55   return dst;
56 }
57 
58 // Visitor that converts a reference's resource ID to a resource name, given a mapping from
59 // resource ID to resource name.
60 class ReferenceIdToNameVisitor : public DescendingValueVisitor {
61  public:
62   using DescendingValueVisitor::Visit;
63 
ReferenceIdToNameVisitor(const std::map<ResourceId,ResourceName> * mapping)64   explicit ReferenceIdToNameVisitor(const std::map<ResourceId, ResourceName>* mapping)
65       : mapping_(mapping) {
66     CHECK(mapping_ != nullptr);
67   }
68 
Visit(Reference * reference)69   void Visit(Reference* reference) override {
70     if (!reference->id || !reference->id.value().is_valid()) {
71       return;
72     }
73 
74     ResourceId id = reference->id.value();
75     auto cache_iter = mapping_->find(id);
76     if (cache_iter != mapping_->end()) {
77       reference->name = cache_iter->second;
78     }
79   }
80 
81  private:
82   DISALLOW_COPY_AND_ASSIGN(ReferenceIdToNameVisitor);
83 
84   const std::map<ResourceId, ResourceName>* mapping_;
85 };
86 
87 }  // namespace
88 
BinaryResourceParser(IDiagnostics * diag,ResourceTable * table,const Source & source,const void * data,size_t len,io::IFileCollection * files)89 BinaryResourceParser::BinaryResourceParser(IDiagnostics* diag, ResourceTable* table,
90                                            const Source& source, const void* data, size_t len,
91                                            io::IFileCollection* files)
92     : diag_(diag), table_(table), source_(source), data_(data), data_len_(len), files_(files) {
93 }
94 
Parse()95 bool BinaryResourceParser::Parse() {
96   ResChunkPullParser parser(data_, data_len_);
97 
98   if (!ResChunkPullParser::IsGoodEvent(parser.Next())) {
99     diag_->Error(DiagMessage(source_) << "corrupt resources.arsc: " << parser.error());
100     return false;
101   }
102 
103   if (parser.chunk()->type != android::RES_TABLE_TYPE) {
104     diag_->Error(DiagMessage(source_) << StringPrintf("unknown chunk of type 0x%02x",
105                                                       static_cast<int>(parser.chunk()->type)));
106     return false;
107   }
108 
109   if (!ParseTable(parser.chunk())) {
110     return false;
111   }
112 
113   if (parser.Next() != ResChunkPullParser::Event::kEndDocument) {
114     if (parser.event() == ResChunkPullParser::Event::kBadDocument) {
115       diag_->Warn(DiagMessage(source_)
116                   << "invalid chunk trailing RES_TABLE_TYPE: " << parser.error());
117     } else {
118       diag_->Warn(DiagMessage(source_)
119                   << StringPrintf("unexpected chunk of type 0x%02x trailing RES_TABLE_TYPE",
120                                   static_cast<int>(parser.chunk()->type)));
121     }
122   }
123   return true;
124 }
125 
126 // Parses the resource table, which contains all the packages, types, and entries.
ParseTable(const ResChunk_header * chunk)127 bool BinaryResourceParser::ParseTable(const ResChunk_header* chunk) {
128   const ResTable_header* table_header = ConvertTo<ResTable_header>(chunk);
129   if (!table_header) {
130     diag_->Error(DiagMessage(source_) << "corrupt ResTable_header chunk");
131     return false;
132   }
133 
134   ResChunkPullParser parser(GetChunkData(&table_header->header),
135                             GetChunkDataLen(&table_header->header));
136   while (ResChunkPullParser::IsGoodEvent(parser.Next())) {
137     switch (util::DeviceToHost16(parser.chunk()->type)) {
138       case android::RES_STRING_POOL_TYPE:
139         if (value_pool_.getError() == NO_INIT) {
140           status_t err =
141               value_pool_.setTo(parser.chunk(), util::DeviceToHost32(parser.chunk()->size));
142           if (err != NO_ERROR) {
143             diag_->Error(DiagMessage(source_)
144                          << "corrupt string pool in ResTable: " << value_pool_.getError());
145             return false;
146           }
147 
148           // Reserve some space for the strings we are going to add.
149           table_->string_pool.HintWillAdd(value_pool_.size(), value_pool_.styleCount());
150         } else {
151           diag_->Warn(DiagMessage(source_) << "unexpected string pool in ResTable");
152         }
153         break;
154 
155       case android::RES_TABLE_PACKAGE_TYPE:
156         if (!ParsePackage(parser.chunk())) {
157           return false;
158         }
159         break;
160 
161       default:
162         diag_->Warn(DiagMessage(source_)
163                     << "unexpected chunk type "
164                     << static_cast<int>(util::DeviceToHost16(parser.chunk()->type)));
165         break;
166     }
167   }
168 
169   if (parser.event() == ResChunkPullParser::Event::kBadDocument) {
170     diag_->Error(DiagMessage(source_) << "corrupt resource table: " << parser.error());
171     return false;
172   }
173   return true;
174 }
175 
ParsePackage(const ResChunk_header * chunk)176 bool BinaryResourceParser::ParsePackage(const ResChunk_header* chunk) {
177   constexpr size_t kMinPackageSize =
178       sizeof(ResTable_package) - sizeof(ResTable_package::typeIdOffset);
179   const ResTable_package* package_header = ConvertTo<ResTable_package, kMinPackageSize>(chunk);
180   if (!package_header) {
181     diag_->Error(DiagMessage(source_) << "corrupt ResTable_package chunk");
182     return false;
183   }
184 
185   uint32_t package_id = util::DeviceToHost32(package_header->id);
186   if (package_id > std::numeric_limits<uint8_t>::max()) {
187     diag_->Error(DiagMessage(source_) << "package ID is too big (" << package_id << ")");
188     return false;
189   }
190 
191   // Extract the package name.
192   std::u16string package_name = strcpy16_dtoh((const char16_t*)package_header->name,
193                                               arraysize(package_header->name));
194 
195   ResourceTablePackage* package = table_->FindOrCreatePackage(util::Utf16ToUtf8(package_name));
196   if (!package) {
197     diag_->Error(DiagMessage(source_)
198                  << "incompatible package '" << package_name << "' with ID " << package_id);
199     return false;
200   }
201 
202   // There can be multiple packages in a table, so
203   // clear the type and key pool in case they were set from a previous package.
204   type_pool_.uninit();
205   key_pool_.uninit();
206 
207   ResChunkPullParser parser(GetChunkData(&package_header->header),
208                             GetChunkDataLen(&package_header->header));
209   while (ResChunkPullParser::IsGoodEvent(parser.Next())) {
210     switch (util::DeviceToHost16(parser.chunk()->type)) {
211       case android::RES_STRING_POOL_TYPE:
212         if (type_pool_.getError() == NO_INIT) {
213           status_t err =
214               type_pool_.setTo(parser.chunk(), util::DeviceToHost32(parser.chunk()->size));
215           if (err != NO_ERROR) {
216             diag_->Error(DiagMessage(source_) << "corrupt type string pool in "
217                                               << "ResTable_package: " << type_pool_.getError());
218             return false;
219           }
220         } else if (key_pool_.getError() == NO_INIT) {
221           status_t err =
222               key_pool_.setTo(parser.chunk(), util::DeviceToHost32(parser.chunk()->size));
223           if (err != NO_ERROR) {
224             diag_->Error(DiagMessage(source_) << "corrupt key string pool in "
225                                               << "ResTable_package: " << key_pool_.getError());
226             return false;
227           }
228         } else {
229           diag_->Warn(DiagMessage(source_) << "unexpected string pool");
230         }
231         break;
232 
233       case android::RES_TABLE_TYPE_SPEC_TYPE:
234         if (!ParseTypeSpec(package, parser.chunk(), package_id)) {
235           return false;
236         }
237         break;
238 
239       case android::RES_TABLE_TYPE_TYPE:
240         if (!ParseType(package, parser.chunk(), package_id)) {
241           return false;
242         }
243         break;
244 
245       case android::RES_TABLE_LIBRARY_TYPE:
246         if (!ParseLibrary(parser.chunk())) {
247           return false;
248         }
249         break;
250 
251       case android::RES_TABLE_OVERLAYABLE_TYPE:
252         if (!ParseOverlayable(parser.chunk())) {
253           return false;
254         }
255         break;
256 
257       case android::RES_TABLE_STAGED_ALIAS_TYPE:
258         if (!ParseStagedAliases(parser.chunk())) {
259           return false;
260         }
261         break;
262 
263       default:
264         diag_->Warn(DiagMessage(source_)
265                     << "unexpected chunk type "
266                     << static_cast<int>(util::DeviceToHost16(parser.chunk()->type)));
267         break;
268     }
269   }
270 
271   if (parser.event() == ResChunkPullParser::Event::kBadDocument) {
272     diag_->Error(DiagMessage(source_) << "corrupt ResTable_package: " << parser.error());
273     return false;
274   }
275 
276   // Now go through the table and change local resource ID references to
277   // symbolic references.
278   ReferenceIdToNameVisitor visitor(&id_index_);
279   VisitAllValuesInTable(table_, &visitor);
280   return true;
281 }
282 
ParseTypeSpec(const ResourceTablePackage * package,const ResChunk_header * chunk,uint8_t package_id)283 bool BinaryResourceParser::ParseTypeSpec(const ResourceTablePackage* package,
284                                          const ResChunk_header* chunk, uint8_t package_id) {
285   if (type_pool_.getError() != NO_ERROR) {
286     diag_->Error(DiagMessage(source_) << "missing type string pool");
287     return false;
288   }
289 
290   const ResTable_typeSpec* type_spec = ConvertTo<ResTable_typeSpec>(chunk);
291   if (!type_spec) {
292     diag_->Error(DiagMessage(source_) << "corrupt ResTable_typeSpec chunk");
293     return false;
294   }
295 
296   if (type_spec->id == 0) {
297     diag_->Error(DiagMessage(source_) << "ResTable_typeSpec has invalid id: " << type_spec->id);
298     return false;
299   }
300 
301   // The data portion of this chunk contains entry_count 32bit entries,
302   // each one representing a set of flags.
303   const size_t entry_count = dtohl(type_spec->entryCount);
304 
305   // There can only be 2^16 entries in a type, because that is the ID
306   // space for entries (EEEE) in the resource ID 0xPPTTEEEE.
307   if (entry_count > std::numeric_limits<uint16_t>::max()) {
308     diag_->Error(DiagMessage(source_)
309                  << "ResTable_typeSpec has too many entries (" << entry_count << ")");
310     return false;
311   }
312 
313   const size_t data_size = util::DeviceToHost32(type_spec->header.size) -
314                            util::DeviceToHost16(type_spec->header.headerSize);
315   if (entry_count * sizeof(uint32_t) > data_size) {
316     diag_->Error(DiagMessage(source_) << "ResTable_typeSpec too small to hold entries.");
317     return false;
318   }
319 
320   // Record the type_spec_flags for later. We don't know resource names yet, and we need those
321   // to mark resources as overlayable.
322   const uint32_t* type_spec_flags = reinterpret_cast<const uint32_t*>(
323       reinterpret_cast<uintptr_t>(type_spec) + util::DeviceToHost16(type_spec->header.headerSize));
324   for (size_t i = 0; i < entry_count; i++) {
325     ResourceId id(package_id, type_spec->id, static_cast<size_t>(i));
326     entry_type_spec_flags_[id] = util::DeviceToHost32(type_spec_flags[i]);
327   }
328   return true;
329 }
330 
ParseType(const ResourceTablePackage * package,const ResChunk_header * chunk,uint8_t package_id)331 bool BinaryResourceParser::ParseType(const ResourceTablePackage* package,
332                                      const ResChunk_header* chunk, uint8_t package_id) {
333   if (type_pool_.getError() != NO_ERROR) {
334     diag_->Error(DiagMessage(source_) << "missing type string pool");
335     return false;
336   }
337 
338   if (key_pool_.getError() != NO_ERROR) {
339     diag_->Error(DiagMessage(source_) << "missing key string pool");
340     return false;
341   }
342 
343   // Specify a manual size, because ResTable_type contains ResTable_config, which changes
344   // a lot and has its own code to handle variable size.
345   const ResTable_type* type = ConvertTo<ResTable_type, kResTableTypeMinSize>(chunk);
346   if (!type) {
347     diag_->Error(DiagMessage(source_) << "corrupt ResTable_type chunk");
348     return false;
349   }
350 
351   if (type->id == 0) {
352     diag_->Error(DiagMessage(source_) << "ResTable_type has invalid id: " << (int)type->id);
353     return false;
354   }
355 
356   ConfigDescription config;
357   config.copyFromDtoH(type->config);
358 
359   const std::string type_str = util::GetString(type_pool_, type->id - 1);
360   const ResourceType* parsed_type = ParseResourceType(type_str);
361   if (!parsed_type) {
362     diag_->Warn(DiagMessage(source_)
363                 << "invalid type name '" << type_str << "' for type with ID " << type->id);
364     return true;
365   }
366 
367   TypeVariant tv(type);
368   for (auto it = tv.beginEntries(); it != tv.endEntries(); ++it) {
369     const ResTable_entry* entry = *it;
370     if (!entry) {
371       continue;
372     }
373 
374     const ResourceName name(package->name, *parsed_type,
375                             util::GetString(key_pool_, util::DeviceToHost32(entry->key.index)));
376     const ResourceId res_id(package_id, type->id, static_cast<uint16_t>(it.index()));
377 
378     std::unique_ptr<Value> resource_value;
379     if (entry->flags & ResTable_entry::FLAG_COMPLEX) {
380       const ResTable_map_entry* mapEntry = static_cast<const ResTable_map_entry*>(entry);
381 
382       // TODO(adamlesinski): Check that the entry count is valid.
383       resource_value = ParseMapEntry(name, config, mapEntry);
384     } else {
385       const Res_value* value =
386           (const Res_value*)((const uint8_t*)entry + util::DeviceToHost32(entry->size));
387       resource_value = ParseValue(name, config, *value);
388     }
389 
390     if (!resource_value) {
391       diag_->Error(DiagMessage(source_) << "failed to parse value for resource " << name << " ("
392                                         << res_id << ") with configuration '" << config << "'");
393       return false;
394     }
395 
396     NewResourceBuilder res_builder(name);
397     res_builder.SetValue(std::move(resource_value), config)
398         .SetId(res_id, OnIdConflict::CREATE_ENTRY)
399         .SetAllowMangled(true);
400 
401     if (entry->flags & ResTable_entry::FLAG_PUBLIC) {
402       Visibility visibility{Visibility::Level::kPublic};
403 
404       auto spec_flags = entry_type_spec_flags_.find(res_id);
405       if (spec_flags != entry_type_spec_flags_.end() &&
406           spec_flags->second & ResTable_typeSpec::SPEC_STAGED_API) {
407         visibility.staged_api = true;
408       }
409 
410       res_builder.SetVisibility(visibility);
411       // Erase the ID from the map once processed, so that we don't mark the same symbol more than
412       // once.
413       entry_type_spec_flags_.erase(res_id);
414     }
415 
416     // Add this resource name->id mapping to the index so
417     // that we can resolve all ID references to name references.
418     auto cache_iter = id_index_.find(res_id);
419     if (cache_iter == id_index_.end()) {
420       id_index_.insert({res_id, name});
421     }
422 
423     if (!table_->AddResource(res_builder.Build(), diag_)) {
424       return false;
425     }
426   }
427   return true;
428 }
429 
ParseLibrary(const ResChunk_header * chunk)430 bool BinaryResourceParser::ParseLibrary(const ResChunk_header* chunk) {
431   DynamicRefTable dynamic_ref_table;
432   if (dynamic_ref_table.load(reinterpret_cast<const ResTable_lib_header*>(chunk)) != NO_ERROR) {
433     return false;
434   }
435 
436   const KeyedVector<String16, uint8_t>& entries = dynamic_ref_table.entries();
437   const size_t count = entries.size();
438   for (size_t i = 0; i < count; i++) {
439     table_->included_packages_[entries.valueAt(i)] =
440         util::Utf16ToUtf8(StringPiece16(entries.keyAt(i).string()));
441   }
442   return true;
443 }
444 
ParseOverlayable(const ResChunk_header * chunk)445 bool BinaryResourceParser::ParseOverlayable(const ResChunk_header* chunk) {
446   const ResTable_overlayable_header* header = ConvertTo<ResTable_overlayable_header>(chunk);
447   if (!header) {
448     diag_->Error(DiagMessage(source_) << "corrupt ResTable_category_header chunk");
449     return false;
450   }
451 
452   auto overlayable = std::make_shared<Overlayable>();
453   overlayable->name = util::Utf16ToUtf8(strcpy16_dtoh((const char16_t*)header->name,
454                                                       arraysize(header->name)));
455   overlayable->actor = util::Utf16ToUtf8(strcpy16_dtoh((const char16_t*)header->actor,
456                                                        arraysize(header->name)));
457 
458   ResChunkPullParser parser(GetChunkData(chunk),
459                             GetChunkDataLen(chunk));
460   while (ResChunkPullParser::IsGoodEvent(parser.Next())) {
461     if (util::DeviceToHost16(parser.chunk()->type) == android::RES_TABLE_OVERLAYABLE_POLICY_TYPE) {
462       const ResTable_overlayable_policy_header* policy_header =
463           ConvertTo<ResTable_overlayable_policy_header>(parser.chunk());
464 
465       const ResTable_ref* const ref_begin = reinterpret_cast<const ResTable_ref*>(
466           ((uint8_t *)policy_header) + util::DeviceToHost32(policy_header->header.headerSize));
467       const ResTable_ref* const ref_end = ref_begin
468           + util::DeviceToHost32(policy_header->entry_count);
469       for (auto ref_iter = ref_begin; ref_iter != ref_end; ++ref_iter) {
470         ResourceId res_id(util::DeviceToHost32(ref_iter->ident));
471         const auto iter = id_index_.find(res_id);
472 
473         // If the overlayable chunk comes before the type chunks, the resource ids and resource name
474         // pairing will not exist at this point.
475         if (iter == id_index_.cend()) {
476           diag_->Error(DiagMessage(source_) << "failed to find resource name for overlayable"
477                                             << " resource " << res_id);
478           return false;
479         }
480 
481         OverlayableItem overlayable_item(overlayable);
482         overlayable_item.policies = policy_header->policy_flags;
483         if (!table_->AddResource(NewResourceBuilder(iter->second)
484                                      .SetId(res_id, OnIdConflict::CREATE_ENTRY)
485                                      .SetOverlayable(std::move(overlayable_item))
486                                      .SetAllowMangled(true)
487                                      .Build(),
488                                  diag_)) {
489           return false;
490         }
491       }
492     }
493   }
494 
495   return true;
496 }
497 
ParseStagedAliases(const ResChunk_header * chunk)498 bool BinaryResourceParser::ParseStagedAliases(const ResChunk_header* chunk) {
499   auto header = ConvertTo<ResTable_staged_alias_header>(chunk);
500   if (!header) {
501     diag_->Error(DiagMessage(source_) << "corrupt ResTable_staged_alias_header chunk");
502     return false;
503   }
504 
505   const auto ref_begin = reinterpret_cast<const ResTable_staged_alias_entry*>(
506       ((uint8_t*)header) + util::DeviceToHost32(header->header.headerSize));
507   const auto ref_end = ref_begin + util::DeviceToHost32(header->count);
508   for (auto ref_iter = ref_begin; ref_iter != ref_end; ++ref_iter) {
509     const auto staged_id = ResourceId(util::DeviceToHost32(ref_iter->stagedResId));
510     const auto finalized_id = ResourceId(util::DeviceToHost32(ref_iter->finalizedResId));
511 
512     // If the staged alias chunk comes before the type chunks, the resource ids and resource name
513     // pairing will not exist at this point.
514     const auto iter = id_index_.find(finalized_id);
515     if (iter == id_index_.cend()) {
516       diag_->Error(DiagMessage(source_) << "failed to find resource name for finalized"
517                                         << " resource ID " << finalized_id);
518       return false;
519     }
520 
521     // Set the staged id of the finalized resource.
522     const auto& resource_name = iter->second;
523     const StagedId staged_id_def{.id = staged_id};
524     if (!table_->AddResource(NewResourceBuilder(resource_name)
525                                  .SetId(finalized_id, OnIdConflict::CREATE_ENTRY)
526                                  .SetStagedId(staged_id_def)
527                                  .SetAllowMangled(true)
528                                  .Build(),
529                              diag_)) {
530       return false;
531     }
532 
533     // Since a the finalized resource entry is cloned and added to the resource table under the
534     // staged resource id, remove the cloned resource entry from the table.
535     if (!table_->RemoveResource(resource_name, staged_id)) {
536       diag_->Error(DiagMessage(source_) << "failed to find resource entry for staged "
537                                         << " resource ID " << staged_id);
538       return false;
539     }
540   }
541   return true;
542 }
543 
ParseValue(const ResourceNameRef & name,const ConfigDescription & config,const android::Res_value & value)544 std::unique_ptr<Item> BinaryResourceParser::ParseValue(const ResourceNameRef& name,
545                                                        const ConfigDescription& config,
546                                                        const android::Res_value& value) {
547   std::unique_ptr<Item> item = ResourceUtils::ParseBinaryResValue(name.type, config, value_pool_,
548                                                                   value, &table_->string_pool);
549   if (files_ != nullptr) {
550     FileReference* file_ref = ValueCast<FileReference>(item.get());
551     if (file_ref != nullptr) {
552       file_ref->file = files_->FindFile(*file_ref->path);
553       if (file_ref->file == nullptr) {
554         diag_->Warn(DiagMessage() << "resource " << name << " for config '" << config
555                                   << "' is a file reference to '" << *file_ref->path
556                                   << "' but no such path exists");
557       }
558     }
559   }
560   return item;
561 }
562 
ParseMapEntry(const ResourceNameRef & name,const ConfigDescription & config,const ResTable_map_entry * map)563 std::unique_ptr<Value> BinaryResourceParser::ParseMapEntry(const ResourceNameRef& name,
564                                                            const ConfigDescription& config,
565                                                            const ResTable_map_entry* map) {
566   switch (name.type) {
567     case ResourceType::kStyle:
568       return ParseStyle(name, config, map);
569     case ResourceType::kAttrPrivate:
570       // fallthrough
571     case ResourceType::kAttr:
572       return ParseAttr(name, config, map);
573     case ResourceType::kArray:
574       return ParseArray(name, config, map);
575     case ResourceType::kPlurals:
576       return ParsePlural(name, config, map);
577     case ResourceType::kId:
578       // Special case: An ID is not a bag, but some apps have defined the auto-generated
579       // IDs that come from declaring an enum value in an attribute as an empty map...
580       // We can ignore the value here.
581       return util::make_unique<Id>();
582     default:
583       diag_->Error(DiagMessage() << "illegal map type '" << to_string(name.type) << "' ("
584                                  << (int)name.type << ")");
585       break;
586   }
587   return {};
588 }
589 
ParseStyle(const ResourceNameRef & name,const ConfigDescription & config,const ResTable_map_entry * map)590 std::unique_ptr<Style> BinaryResourceParser::ParseStyle(const ResourceNameRef& name,
591                                                         const ConfigDescription& config,
592                                                         const ResTable_map_entry* map) {
593   std::unique_ptr<Style> style = util::make_unique<Style>();
594   if (util::DeviceToHost32(map->parent.ident) != 0) {
595     // The parent is a regular reference to a resource.
596     style->parent = Reference(util::DeviceToHost32(map->parent.ident));
597   }
598 
599   for (const ResTable_map& map_entry : map) {
600     if (Res_INTERNALID(util::DeviceToHost32(map_entry.name.ident))) {
601       continue;
602     }
603 
604     Style::Entry style_entry;
605     style_entry.key = Reference(util::DeviceToHost32(map_entry.name.ident));
606     style_entry.value = ParseValue(name, config, map_entry.value);
607     if (!style_entry.value) {
608       return {};
609     }
610     style->entries.push_back(std::move(style_entry));
611   }
612   return style;
613 }
614 
ParseAttr(const ResourceNameRef & name,const ConfigDescription & config,const ResTable_map_entry * map)615 std::unique_ptr<Attribute> BinaryResourceParser::ParseAttr(const ResourceNameRef& name,
616                                                            const ConfigDescription& config,
617                                                            const ResTable_map_entry* map) {
618   std::unique_ptr<Attribute> attr = util::make_unique<Attribute>();
619   attr->SetWeak((util::DeviceToHost16(map->flags) & ResTable_entry::FLAG_WEAK) != 0);
620 
621   // First we must discover what type of attribute this is. Find the type mask.
622   auto type_mask_iter = std::find_if(begin(map), end(map), [](const ResTable_map& entry) -> bool {
623     return util::DeviceToHost32(entry.name.ident) == ResTable_map::ATTR_TYPE;
624   });
625 
626   if (type_mask_iter != end(map)) {
627     attr->type_mask = util::DeviceToHost32(type_mask_iter->value.data);
628   }
629 
630   for (const ResTable_map& map_entry : map) {
631     if (Res_INTERNALID(util::DeviceToHost32(map_entry.name.ident))) {
632       switch (util::DeviceToHost32(map_entry.name.ident)) {
633         case ResTable_map::ATTR_MIN:
634           attr->min_int = static_cast<int32_t>(map_entry.value.data);
635           break;
636         case ResTable_map::ATTR_MAX:
637           attr->max_int = static_cast<int32_t>(map_entry.value.data);
638           break;
639       }
640       continue;
641     }
642 
643     if (attr->type_mask & (ResTable_map::TYPE_ENUM | ResTable_map::TYPE_FLAGS)) {
644       Attribute::Symbol symbol;
645       symbol.value = util::DeviceToHost32(map_entry.value.data);
646       symbol.type = map_entry.value.dataType;
647       symbol.symbol = Reference(util::DeviceToHost32(map_entry.name.ident));
648       attr->symbols.push_back(std::move(symbol));
649     }
650   }
651 
652   // TODO(adamlesinski): Find i80n, attributes.
653   return attr;
654 }
655 
ParseArray(const ResourceNameRef & name,const ConfigDescription & config,const ResTable_map_entry * map)656 std::unique_ptr<Array> BinaryResourceParser::ParseArray(const ResourceNameRef& name,
657                                                         const ConfigDescription& config,
658                                                         const ResTable_map_entry* map) {
659   std::unique_ptr<Array> array = util::make_unique<Array>();
660   for (const ResTable_map& map_entry : map) {
661     array->elements.push_back(ParseValue(name, config, map_entry.value));
662   }
663   return array;
664 }
665 
ParsePlural(const ResourceNameRef & name,const ConfigDescription & config,const ResTable_map_entry * map)666 std::unique_ptr<Plural> BinaryResourceParser::ParsePlural(const ResourceNameRef& name,
667                                                           const ConfigDescription& config,
668                                                           const ResTable_map_entry* map) {
669   std::unique_ptr<Plural> plural = util::make_unique<Plural>();
670   for (const ResTable_map& map_entry : map) {
671     std::unique_ptr<Item> item = ParseValue(name, config, map_entry.value);
672     if (!item) {
673       return {};
674     }
675 
676     switch (util::DeviceToHost32(map_entry.name.ident)) {
677       case ResTable_map::ATTR_ZERO:
678         plural->values[Plural::Zero] = std::move(item);
679         break;
680       case ResTable_map::ATTR_ONE:
681         plural->values[Plural::One] = std::move(item);
682         break;
683       case ResTable_map::ATTR_TWO:
684         plural->values[Plural::Two] = std::move(item);
685         break;
686       case ResTable_map::ATTR_FEW:
687         plural->values[Plural::Few] = std::move(item);
688         break;
689       case ResTable_map::ATTR_MANY:
690         plural->values[Plural::Many] = std::move(item);
691         break;
692       case ResTable_map::ATTR_OTHER:
693         plural->values[Plural::Other] = std::move(item);
694         break;
695     }
696   }
697   return plural;
698 }
699 
700 }  // namespace aapt
701