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