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 "ResourceValues.h"
18 
19 #include <algorithm>
20 #include <cinttypes>
21 #include <limits>
22 #include <set>
23 #include <sstream>
24 
25 #include "android-base/stringprintf.h"
26 #include "androidfw/ResourceTypes.h"
27 
28 #include "Resource.h"
29 #include "ResourceUtils.h"
30 #include "ValueVisitor.h"
31 #include "util/Util.h"
32 
33 using ::aapt::text::Printer;
34 using ::android::StringPiece;
35 using ::android::base::StringPrintf;
36 
37 namespace aapt {
38 
PrettyPrint(Printer * printer) const39 void Value::PrettyPrint(Printer* printer) const {
40   std::ostringstream str_stream;
41   Print(&str_stream);
42   printer->Print(str_stream.str());
43 }
44 
operator <<(std::ostream & out,const Value & value)45 std::ostream& operator<<(std::ostream& out, const Value& value) {
46   value.Print(&out);
47   return out;
48 }
49 
Transform(ValueTransformer & transformer) const50 std::unique_ptr<Value> Value::Transform(ValueTransformer& transformer) const {
51   return std::unique_ptr<Value>(this->TransformValueImpl(transformer));
52 }
53 
Transform(ValueTransformer & transformer) const54 std::unique_ptr<Item> Item::Transform(ValueTransformer& transformer) const {
55   return std::unique_ptr<Item>(this->TransformItemImpl(transformer));
56 }
57 
58 template <typename Derived>
Accept(ValueVisitor * visitor)59 void BaseValue<Derived>::Accept(ValueVisitor* visitor) {
60   visitor->Visit(static_cast<Derived*>(this));
61 }
62 
63 template <typename Derived>
Accept(ConstValueVisitor * visitor) const64 void BaseValue<Derived>::Accept(ConstValueVisitor* visitor) const {
65   visitor->Visit(static_cast<const Derived*>(this));
66 }
67 
68 template <typename Derived>
Accept(ValueVisitor * visitor)69 void BaseItem<Derived>::Accept(ValueVisitor* visitor) {
70   visitor->Visit(static_cast<Derived*>(this));
71 }
72 
73 template <typename Derived>
Accept(ConstValueVisitor * visitor) const74 void BaseItem<Derived>::Accept(ConstValueVisitor* visitor) const {
75   visitor->Visit(static_cast<const Derived*>(this));
76 }
77 
RawString(const android::StringPool::Ref & ref)78 RawString::RawString(const android::StringPool::Ref& ref) : value(ref) {
79 }
80 
Equals(const Value * value) const81 bool RawString::Equals(const Value* value) const {
82   const RawString* other = ValueCast<RawString>(value);
83   if (!other) {
84     return false;
85   }
86   return *this->value == *other->value;
87 }
88 
Flatten(android::Res_value * out_value) const89 bool RawString::Flatten(android::Res_value* out_value) const {
90   out_value->dataType = android::Res_value::TYPE_STRING;
91   out_value->data = android::util::HostToDevice32(static_cast<uint32_t>(value.index()));
92   return true;
93 }
94 
Print(std::ostream * out) const95 void RawString::Print(std::ostream* out) const {
96   *out << "(raw string) " << *value;
97 }
98 
Reference()99 Reference::Reference() : reference_type(Type::kResource) {}
100 
Reference(const ResourceNameRef & n,Type t)101 Reference::Reference(const ResourceNameRef& n, Type t)
102     : name(n.ToResourceName()), reference_type(t) {}
103 
Reference(const ResourceId & i,Type type)104 Reference::Reference(const ResourceId& i, Type type)
105     : id(i), reference_type(type) {}
106 
Reference(const ResourceNameRef & n,const ResourceId & i)107 Reference::Reference(const ResourceNameRef& n, const ResourceId& i)
108     : name(n.ToResourceName()), id(i), reference_type(Type::kResource) {}
109 
Equals(const Value * value) const110 bool Reference::Equals(const Value* value) const {
111   const Reference* other = ValueCast<Reference>(value);
112   if (!other) {
113     return false;
114   }
115   return reference_type == other->reference_type && private_reference == other->private_reference &&
116          id == other->id && name == other->name && type_flags == other->type_flags;
117 }
118 
Flatten(android::Res_value * out_value) const119 bool Reference::Flatten(android::Res_value* out_value) const {
120   if (name && name.value().type.type == ResourceType::kMacro) {
121     return false;
122   }
123 
124   const ResourceId resid = id.value_or(ResourceId(0));
125   const bool dynamic = resid.is_valid() && is_dynamic;
126 
127   if (reference_type == Reference::Type::kResource) {
128     if (dynamic) {
129       out_value->dataType = android::Res_value::TYPE_DYNAMIC_REFERENCE;
130     } else {
131       out_value->dataType = android::Res_value::TYPE_REFERENCE;
132     }
133   } else {
134     if (dynamic) {
135       out_value->dataType = android::Res_value::TYPE_DYNAMIC_ATTRIBUTE;
136     } else {
137       out_value->dataType = android::Res_value::TYPE_ATTRIBUTE;
138     }
139   }
140   out_value->data = android::util::HostToDevice32(resid.id);
141   return true;
142 }
143 
Print(std::ostream * out) const144 void Reference::Print(std::ostream* out) const {
145   if (reference_type == Type::kResource) {
146     *out << "(reference) @";
147     if (!name && !id) {
148       *out << "null";
149       return;
150     }
151   } else {
152     *out << "(attr-reference) ?";
153   }
154 
155   if (private_reference) {
156     *out << "*";
157   }
158 
159   if (name) {
160     *out << name.value();
161   }
162 
163   if (id && id.value().is_valid()) {
164     if (name) {
165       *out << " ";
166     }
167     *out << id.value();
168   }
169 }
170 
PrettyPrintReferenceImpl(const Reference & ref,bool print_package,Printer * printer)171 static void PrettyPrintReferenceImpl(const Reference& ref, bool print_package, Printer* printer) {
172   switch (ref.reference_type) {
173     case Reference::Type::kResource:
174       printer->Print("@");
175       break;
176 
177     case Reference::Type::kAttribute:
178       printer->Print("?");
179       break;
180   }
181 
182   if (!ref.name && !ref.id) {
183     printer->Print("null");
184     return;
185   }
186 
187   if (ref.private_reference) {
188     printer->Print("*");
189   }
190 
191   if (ref.name) {
192     const ResourceName& name = ref.name.value();
193     if (print_package) {
194       printer->Print(name.to_string());
195     } else {
196       printer->Print(name.type.to_string());
197       printer->Print("/");
198       printer->Print(name.entry);
199     }
200   } else if (ref.id && ref.id.value().is_valid()) {
201     printer->Print(ref.id.value().to_string());
202   }
203 }
204 
PrettyPrint(Printer * printer) const205 void Reference::PrettyPrint(Printer* printer) const {
206   PrettyPrintReferenceImpl(*this, true /*print_package*/, printer);
207 }
208 
PrettyPrint(StringPiece package,Printer * printer) const209 void Reference::PrettyPrint(StringPiece package, Printer* printer) const {
210   const bool print_package = name ? package != name.value().package : true;
211   PrettyPrintReferenceImpl(*this, print_package, printer);
212 }
213 
Equals(const Value * value) const214 bool Id::Equals(const Value* value) const {
215   return ValueCast<Id>(value) != nullptr;
216 }
217 
Flatten(android::Res_value * out) const218 bool Id::Flatten(android::Res_value* out) const {
219   out->dataType = android::Res_value::TYPE_INT_BOOLEAN;
220   out->data = android::util::HostToDevice32(0);
221   return true;
222 }
223 
Print(std::ostream * out) const224 void Id::Print(std::ostream* out) const {
225   *out << "(id)";
226 }
227 
String(const android::StringPool::Ref & ref)228 String::String(const android::StringPool::Ref& ref) : value(ref) {
229 }
230 
Equals(const Value * value) const231 bool String::Equals(const Value* value) const {
232   const String* other = ValueCast<String>(value);
233   if (!other) {
234     return false;
235   }
236 
237   if (this->value != other->value) {
238     return false;
239   }
240 
241   if (untranslatable_sections.size() != other->untranslatable_sections.size()) {
242     return false;
243   }
244 
245   auto other_iter = other->untranslatable_sections.begin();
246   for (const UntranslatableSection& this_section : untranslatable_sections) {
247     if (this_section != *other_iter) {
248       return false;
249     }
250     ++other_iter;
251   }
252   return true;
253 }
254 
Flatten(android::Res_value * out_value) const255 bool String::Flatten(android::Res_value* out_value) const {
256   // Verify that our StringPool index is within encode-able limits.
257   if (value.index() > std::numeric_limits<uint32_t>::max()) {
258     return false;
259   }
260 
261   out_value->dataType = android::Res_value::TYPE_STRING;
262   out_value->data = android::util::HostToDevice32(static_cast<uint32_t>(value.index()));
263   return true;
264 }
265 
Print(std::ostream * out) const266 void String::Print(std::ostream* out) const {
267   *out << "(string) \"" << *value << "\"";
268 }
269 
PrettyPrint(Printer * printer) const270 void String::PrettyPrint(Printer* printer) const {
271   printer->Print("\"");
272   printer->Print(*value);
273   printer->Print("\"");
274 }
275 
StyledString(const android::StringPool::StyleRef & ref)276 StyledString::StyledString(const android::StringPool::StyleRef& ref) : value(ref) {
277 }
278 
Equals(const Value * value) const279 bool StyledString::Equals(const Value* value) const {
280   const StyledString* other = ValueCast<StyledString>(value);
281   if (!other) {
282     return false;
283   }
284 
285   if (this->value != other->value) {
286     return false;
287   }
288 
289   if (untranslatable_sections.size() != other->untranslatable_sections.size()) {
290     return false;
291   }
292 
293   auto other_iter = other->untranslatable_sections.begin();
294   for (const UntranslatableSection& this_section : untranslatable_sections) {
295     if (this_section != *other_iter) {
296       return false;
297     }
298     ++other_iter;
299   }
300   return true;
301 }
302 
Flatten(android::Res_value * out_value) const303 bool StyledString::Flatten(android::Res_value* out_value) const {
304   if (value.index() > std::numeric_limits<uint32_t>::max()) {
305     return false;
306   }
307 
308   out_value->dataType = android::Res_value::TYPE_STRING;
309   out_value->data = android::util::HostToDevice32(static_cast<uint32_t>(value.index()));
310   return true;
311 }
312 
Print(std::ostream * out) const313 void StyledString::Print(std::ostream* out) const {
314   *out << "(styled string) \"" << value->value << "\"";
315   for (const android::StringPool::Span& span : value->spans) {
316     *out << " " << *span.name << ":" << span.first_char << "," << span.last_char;
317   }
318 }
319 
FileReference(const android::StringPool::Ref & _path)320 FileReference::FileReference(const android::StringPool::Ref& _path) : path(_path) {
321 }
322 
Equals(const Value * value) const323 bool FileReference::Equals(const Value* value) const {
324   const FileReference* other = ValueCast<FileReference>(value);
325   if (!other) {
326     return false;
327   }
328   return path == other->path;
329 }
330 
Flatten(android::Res_value * out_value) const331 bool FileReference::Flatten(android::Res_value* out_value) const {
332   if (path.index() > std::numeric_limits<uint32_t>::max()) {
333     return false;
334   }
335 
336   out_value->dataType = android::Res_value::TYPE_STRING;
337   out_value->data = android::util::HostToDevice32(static_cast<uint32_t>(path.index()));
338   return true;
339 }
340 
Print(std::ostream * out) const341 void FileReference::Print(std::ostream* out) const {
342   *out << "(file) " << *path;
343   switch (type) {
344     case ResourceFile::Type::kBinaryXml:
345       *out << " type=XML";
346       break;
347     case ResourceFile::Type::kProtoXml:
348       *out << " type=protoXML";
349       break;
350     case ResourceFile::Type::kPng:
351       *out << " type=PNG";
352       break;
353     default:
354       break;
355   }
356 }
357 
BinaryPrimitive(const android::Res_value & val)358 BinaryPrimitive::BinaryPrimitive(const android::Res_value& val) : value(val) {
359 }
360 
BinaryPrimitive(uint8_t dataType,uint32_t data)361 BinaryPrimitive::BinaryPrimitive(uint8_t dataType, uint32_t data) {
362   value.dataType = dataType;
363   value.data = data;
364 }
365 
Equals(const Value * value) const366 bool BinaryPrimitive::Equals(const Value* value) const {
367   const BinaryPrimitive* other = ValueCast<BinaryPrimitive>(value);
368   if (!other) {
369     return false;
370   }
371   return this->value.dataType == other->value.dataType &&
372          this->value.data == other->value.data;
373 }
374 
Flatten(::android::Res_value * out_value) const375 bool BinaryPrimitive::Flatten(::android::Res_value* out_value) const {
376   out_value->dataType = value.dataType;
377   out_value->data = android::util::HostToDevice32(value.data);
378   return true;
379 }
380 
Print(std::ostream * out) const381 void BinaryPrimitive::Print(std::ostream* out) const {
382   *out << StringPrintf("(primitive) type=0x%02x data=0x%08x", value.dataType, value.data);
383 }
384 
ComplexToString(uint32_t complex_value,bool fraction)385 static std::string ComplexToString(uint32_t complex_value, bool fraction) {
386   using ::android::Res_value;
387 
388   constexpr std::array<int, 4> kRadixShifts = {{23, 16, 8, 0}};
389 
390   // Determine the radix that was used.
391   const uint32_t radix =
392       (complex_value >> Res_value::COMPLEX_RADIX_SHIFT) & Res_value::COMPLEX_RADIX_MASK;
393   const uint64_t mantissa = uint64_t{(complex_value >> Res_value::COMPLEX_MANTISSA_SHIFT) &
394                                      Res_value::COMPLEX_MANTISSA_MASK}
395                             << kRadixShifts[radix];
396   const float value = mantissa * (1.0f / (1 << 23));
397 
398   std::string str = StringPrintf("%f", value);
399 
400   const int unit_type =
401       (complex_value >> Res_value::COMPLEX_UNIT_SHIFT) & Res_value::COMPLEX_UNIT_MASK;
402   if (fraction) {
403     switch (unit_type) {
404       case Res_value::COMPLEX_UNIT_FRACTION:
405         str += "%";
406         break;
407       case Res_value::COMPLEX_UNIT_FRACTION_PARENT:
408         str += "%p";
409         break;
410       default:
411         str += "???";
412         break;
413     }
414   } else {
415     switch (unit_type) {
416       case Res_value::COMPLEX_UNIT_PX:
417         str += "px";
418         break;
419       case Res_value::COMPLEX_UNIT_DIP:
420         str += "dp";
421         break;
422       case Res_value::COMPLEX_UNIT_SP:
423         str += "sp";
424         break;
425       case Res_value::COMPLEX_UNIT_PT:
426         str += "pt";
427         break;
428       case Res_value::COMPLEX_UNIT_IN:
429         str += "in";
430         break;
431       case Res_value::COMPLEX_UNIT_MM:
432         str += "mm";
433         break;
434       default:
435         str += "???";
436         break;
437     }
438   }
439   return str;
440 }
441 
PrettyPrint(Printer * printer) const442 void BinaryPrimitive::PrettyPrint(Printer* printer) const {
443   using ::android::Res_value;
444   switch (value.dataType) {
445     case Res_value::TYPE_NULL:
446       if (value.data == Res_value::DATA_NULL_EMPTY) {
447         printer->Print("@empty");
448       } else {
449         printer->Print("@null");
450       }
451       break;
452 
453     case Res_value::TYPE_INT_DEC:
454       printer->Print(StringPrintf("%" PRIi32, static_cast<int32_t>(value.data)));
455       break;
456 
457     case Res_value::TYPE_INT_HEX:
458       printer->Print(StringPrintf("0x%08x", value.data));
459       break;
460 
461     case Res_value::TYPE_INT_BOOLEAN:
462       printer->Print(value.data != 0 ? "true" : "false");
463       break;
464 
465     case Res_value::TYPE_INT_COLOR_ARGB8:
466     case Res_value::TYPE_INT_COLOR_RGB8:
467     case Res_value::TYPE_INT_COLOR_ARGB4:
468     case Res_value::TYPE_INT_COLOR_RGB4:
469       printer->Print(StringPrintf("#%08x", value.data));
470       break;
471 
472     case Res_value::TYPE_FLOAT:
473       printer->Print(StringPrintf("%g", *reinterpret_cast<const float*>(&value.data)));
474       break;
475 
476     case Res_value::TYPE_DIMENSION:
477       printer->Print(ComplexToString(value.data, false /*fraction*/));
478       break;
479 
480     case Res_value::TYPE_FRACTION:
481       printer->Print(ComplexToString(value.data, true /*fraction*/));
482       break;
483 
484     default:
485       printer->Print(StringPrintf("(unknown 0x%02x) 0x%08x", value.dataType, value.data));
486       break;
487   }
488 }
489 
Attribute(uint32_t t)490 Attribute::Attribute(uint32_t t)
491     : type_mask(t),
492       min_int(std::numeric_limits<int32_t>::min()),
493       max_int(std::numeric_limits<int32_t>::max()) {
494 }
495 
operator <<(std::ostream & out,const Attribute::Symbol & s)496 std::ostream& operator<<(std::ostream& out, const Attribute::Symbol& s) {
497   if (s.symbol.name) {
498     out << s.symbol.name.value().entry;
499   } else {
500     out << "???";
501   }
502   return out << "=" << s.value;
503 }
504 
505 template <typename T>
add_pointer(T & val)506 constexpr T* add_pointer(T& val) {
507   return &val;
508 }
509 
Equals(const Value * value) const510 bool Attribute::Equals(const Value* value) const {
511   const Attribute* other = ValueCast<Attribute>(value);
512   if (!other) {
513     return false;
514   }
515 
516   if (symbols.size() != other->symbols.size()) {
517     return false;
518   }
519 
520   if (type_mask != other->type_mask || min_int != other->min_int || max_int != other->max_int) {
521     return false;
522   }
523 
524   std::vector<const Symbol*> sorted_a;
525   std::transform(symbols.begin(), symbols.end(), std::back_inserter(sorted_a),
526                  add_pointer<const Symbol>);
527   std::sort(sorted_a.begin(), sorted_a.end(), [](const Symbol* a, const Symbol* b) -> bool {
528     return a->symbol.name < b->symbol.name;
529   });
530 
531   std::vector<const Symbol*> sorted_b;
532   std::transform(other->symbols.begin(), other->symbols.end(), std::back_inserter(sorted_b),
533                  add_pointer<const Symbol>);
534   std::sort(sorted_b.begin(), sorted_b.end(), [](const Symbol* a, const Symbol* b) -> bool {
535     return a->symbol.name < b->symbol.name;
536   });
537 
538   return std::equal(sorted_a.begin(), sorted_a.end(), sorted_b.begin(),
539                     [](const Symbol* a, const Symbol* b) -> bool {
540                       return a->symbol.Equals(&b->symbol) && a->value == b->value;
541                     });
542 }
543 
IsCompatibleWith(const Attribute & attr) const544 bool Attribute::IsCompatibleWith(const Attribute& attr) const {
545   // If the high bits are set on any of these attribute type masks, then they are incompatible.
546   // We don't check that flags and enums are identical.
547   if ((type_mask & ~android::ResTable_map::TYPE_ANY) != 0 ||
548       (attr.type_mask & ~android::ResTable_map::TYPE_ANY) != 0) {
549     return false;
550   }
551 
552   // Every attribute accepts a reference.
553   uint32_t this_type_mask = type_mask | android::ResTable_map::TYPE_REFERENCE;
554   uint32_t that_type_mask = attr.type_mask | android::ResTable_map::TYPE_REFERENCE;
555   return this_type_mask == that_type_mask;
556 }
557 
MaskString(uint32_t type_mask)558 std::string Attribute::MaskString(uint32_t type_mask) {
559   if (type_mask == android::ResTable_map::TYPE_ANY) {
560     return "any";
561   }
562 
563   std::ostringstream out;
564   bool set = false;
565   if ((type_mask & android::ResTable_map::TYPE_REFERENCE) != 0) {
566     if (!set) {
567       set = true;
568     } else {
569       out << "|";
570     }
571     out << "reference";
572   }
573 
574   if ((type_mask & android::ResTable_map::TYPE_STRING) != 0) {
575     if (!set) {
576       set = true;
577     } else {
578       out << "|";
579     }
580     out << "string";
581   }
582 
583   if ((type_mask & android::ResTable_map::TYPE_INTEGER) != 0) {
584     if (!set) {
585       set = true;
586     } else {
587       out << "|";
588     }
589     out << "integer";
590   }
591 
592   if ((type_mask & android::ResTable_map::TYPE_BOOLEAN) != 0) {
593     if (!set) {
594       set = true;
595     } else {
596       out << "|";
597     }
598     out << "boolean";
599   }
600 
601   if ((type_mask & android::ResTable_map::TYPE_COLOR) != 0) {
602     if (!set) {
603       set = true;
604     } else {
605       out << "|";
606     }
607     out << "color";
608   }
609 
610   if ((type_mask & android::ResTable_map::TYPE_FLOAT) != 0) {
611     if (!set) {
612       set = true;
613     } else {
614       out << "|";
615     }
616     out << "float";
617   }
618 
619   if ((type_mask & android::ResTable_map::TYPE_DIMENSION) != 0) {
620     if (!set) {
621       set = true;
622     } else {
623       out << "|";
624     }
625     out << "dimension";
626   }
627 
628   if ((type_mask & android::ResTable_map::TYPE_FRACTION) != 0) {
629     if (!set) {
630       set = true;
631     } else {
632       out << "|";
633     }
634     out << "fraction";
635   }
636 
637   if ((type_mask & android::ResTable_map::TYPE_ENUM) != 0) {
638     if (!set) {
639       set = true;
640     } else {
641       out << "|";
642     }
643     out << "enum";
644   }
645 
646   if ((type_mask & android::ResTable_map::TYPE_FLAGS) != 0) {
647     if (!set) {
648       set = true;
649     } else {
650       out << "|";
651     }
652     out << "flags";
653   }
654   return out.str();
655 }
656 
MaskString() const657 std::string Attribute::MaskString() const {
658   return MaskString(type_mask);
659 }
660 
Print(std::ostream * out) const661 void Attribute::Print(std::ostream* out) const {
662   *out << "(attr) " << MaskString();
663 
664   if (!symbols.empty()) {
665     *out << " [" << util::Joiner(symbols, ", ") << "]";
666   }
667 
668   if (min_int != std::numeric_limits<int32_t>::min()) {
669     *out << " min=" << min_int;
670   }
671 
672   if (max_int != std::numeric_limits<int32_t>::max()) {
673     *out << " max=" << max_int;
674   }
675 
676   if (IsWeak()) {
677     *out << " [weak]";
678   }
679 }
680 
BuildAttributeMismatchMessage(const Attribute & attr,const Item & value,android::DiagMessage * out_msg)681 static void BuildAttributeMismatchMessage(const Attribute& attr, const Item& value,
682                                           android::DiagMessage* out_msg) {
683   *out_msg << "expected";
684   if (attr.type_mask & android::ResTable_map::TYPE_BOOLEAN) {
685     *out_msg << " boolean";
686   }
687 
688   if (attr.type_mask & android::ResTable_map::TYPE_COLOR) {
689     *out_msg << " color";
690   }
691 
692   if (attr.type_mask & android::ResTable_map::TYPE_DIMENSION) {
693     *out_msg << " dimension";
694   }
695 
696   if (attr.type_mask & android::ResTable_map::TYPE_ENUM) {
697     *out_msg << " enum";
698   }
699 
700   if (attr.type_mask & android::ResTable_map::TYPE_FLAGS) {
701     *out_msg << " flags";
702   }
703 
704   if (attr.type_mask & android::ResTable_map::TYPE_FLOAT) {
705     *out_msg << " float";
706   }
707 
708   if (attr.type_mask & android::ResTable_map::TYPE_FRACTION) {
709     *out_msg << " fraction";
710   }
711 
712   if (attr.type_mask & android::ResTable_map::TYPE_INTEGER) {
713     *out_msg << " integer";
714   }
715 
716   if (attr.type_mask & android::ResTable_map::TYPE_REFERENCE) {
717     *out_msg << " reference";
718   }
719 
720   if (attr.type_mask & android::ResTable_map::TYPE_STRING) {
721     *out_msg << " string";
722   }
723 
724   *out_msg << " but got " << value;
725 }
726 
Matches(const Item & item,android::DiagMessage * out_msg) const727 bool Attribute::Matches(const Item& item, android::DiagMessage* out_msg) const {
728   constexpr const uint32_t TYPE_ENUM = android::ResTable_map::TYPE_ENUM;
729   constexpr const uint32_t TYPE_FLAGS = android::ResTable_map::TYPE_FLAGS;
730   constexpr const uint32_t TYPE_INTEGER = android::ResTable_map::TYPE_INTEGER;
731   constexpr const uint32_t TYPE_REFERENCE = android::ResTable_map::TYPE_REFERENCE;
732 
733   android::Res_value val = {};
734   item.Flatten(&val);
735 
736   const uint32_t flattened_data = android::util::DeviceToHost32(val.data);
737 
738   // Always allow references.
739   const uint32_t actual_type = ResourceUtils::AndroidTypeToAttributeTypeMask(val.dataType);
740 
741   // Only one type must match between the actual and expected.
742   if ((actual_type & (type_mask | TYPE_REFERENCE)) == 0) {
743     if (out_msg) {
744       BuildAttributeMismatchMessage(*this, item, out_msg);
745     }
746     return false;
747   }
748 
749   // Enums and flags are encoded as integers, so check them first before doing any range checks.
750   if ((type_mask & TYPE_ENUM) != 0 && (actual_type & TYPE_ENUM) != 0) {
751     for (const Symbol& s : symbols) {
752       if (flattened_data == s.value) {
753         return true;
754       }
755     }
756 
757     // If the attribute accepts integers, we can't fail here.
758     if ((type_mask & TYPE_INTEGER) == 0) {
759       if (out_msg) {
760         *out_msg << item << " is not a valid enum";
761       }
762       return false;
763     }
764   }
765 
766   if ((type_mask & TYPE_FLAGS) != 0 && (actual_type & TYPE_FLAGS) != 0) {
767     uint32_t mask = 0u;
768     for (const Symbol& s : symbols) {
769       mask |= s.value;
770     }
771 
772     // Check if the flattened data is covered by the flag bit mask.
773     // If the attribute accepts integers, we can't fail here.
774     if ((mask & flattened_data) == flattened_data) {
775       return true;
776     } else if ((type_mask & TYPE_INTEGER) == 0) {
777       if (out_msg) {
778         *out_msg << item << " is not a valid flag";
779       }
780       return false;
781     }
782   }
783 
784   // Finally check the integer range of the value.
785   if ((type_mask & TYPE_INTEGER) != 0 && (actual_type & TYPE_INTEGER) != 0) {
786     if (static_cast<int32_t>(flattened_data) < min_int) {
787       if (out_msg) {
788         *out_msg << item << " is less than minimum integer " << min_int;
789       }
790       return false;
791     } else if (static_cast<int32_t>(flattened_data) > max_int) {
792       if (out_msg) {
793         *out_msg << item << " is greater than maximum integer " << max_int;
794       }
795       return false;
796     }
797   }
798   return true;
799 }
800 
operator <<(std::ostream & out,const Style::Entry & entry)801 std::ostream& operator<<(std::ostream& out, const Style::Entry& entry) {
802   if (entry.key.name) {
803     out << entry.key.name.value();
804   } else if (entry.key.id) {
805     out << entry.key.id.value();
806   } else {
807     out << "???";
808   }
809   out << " = " << entry.value;
810   return out;
811 }
812 
813 template <typename T>
ToPointerVec(std::vector<T> & src)814 std::vector<T*> ToPointerVec(std::vector<T>& src) {
815   std::vector<T*> dst;
816   dst.reserve(src.size());
817   for (T& in : src) {
818     dst.push_back(&in);
819   }
820   return dst;
821 }
822 
823 template <typename T>
ToPointerVec(const std::vector<T> & src)824 std::vector<const T*> ToPointerVec(const std::vector<T>& src) {
825   std::vector<const T*> dst;
826   dst.reserve(src.size());
827   for (const T& in : src) {
828     dst.push_back(&in);
829   }
830   return dst;
831 }
832 
KeyNameComparator(const Style::Entry * a,const Style::Entry * b)833 static bool KeyNameComparator(const Style::Entry* a, const Style::Entry* b) {
834   return a->key.name < b->key.name;
835 }
836 
Equals(const Value * value) const837 bool Style::Equals(const Value* value) const {
838   const Style* other = ValueCast<Style>(value);
839   if (!other) {
840     return false;
841   }
842 
843   if (bool(parent) != bool(other->parent) ||
844       (parent && other->parent && !parent.value().Equals(&other->parent.value()))) {
845     return false;
846   }
847 
848   if (entries.size() != other->entries.size()) {
849     return false;
850   }
851 
852   std::vector<const Entry*> sorted_a = ToPointerVec(entries);
853   std::sort(sorted_a.begin(), sorted_a.end(), KeyNameComparator);
854 
855   std::vector<const Entry*> sorted_b = ToPointerVec(other->entries);
856   std::sort(sorted_b.begin(), sorted_b.end(), KeyNameComparator);
857 
858   return std::equal(sorted_a.begin(), sorted_a.end(), sorted_b.begin(),
859                     [](const Entry* a, const Entry* b) -> bool {
860                       return a->key.Equals(&b->key) && a->value->Equals(b->value.get());
861                     });
862 }
863 
Print(std::ostream * out) const864 void Style::Print(std::ostream* out) const {
865   *out << "(style) ";
866   if (parent && parent.value().name) {
867     const Reference& parent_ref = parent.value();
868     if (parent_ref.private_reference) {
869       *out << "*";
870     }
871     *out << parent_ref.name.value();
872   }
873   *out << " [" << util::Joiner(entries, ", ") << "]";
874 }
875 
CloneEntry(const Style::Entry & entry,android::StringPool * pool)876 Style::Entry CloneEntry(const Style::Entry& entry, android::StringPool* pool) {
877   Style::Entry cloned_entry{entry.key};
878   if (entry.value != nullptr) {
879     CloningValueTransformer cloner(pool);
880     cloned_entry.value = entry.value->Transform(cloner);
881   }
882   return cloned_entry;
883 }
884 
MergeWith(Style * other,android::StringPool * pool)885 void Style::MergeWith(Style* other, android::StringPool* pool) {
886   if (other->parent) {
887     parent = other->parent;
888   }
889 
890   // We can't assume that the entries are sorted alphabetically since they're supposed to be
891   // sorted by Resource Id. Not all Resource Ids may be set though, so we can't sort and merge
892   // them keying off that.
893   //
894   // Instead, sort the entries of each Style by their name in a separate structure. Then merge
895   // those.
896 
897   std::vector<Entry*> this_sorted = ToPointerVec(entries);
898   std::sort(this_sorted.begin(), this_sorted.end(), KeyNameComparator);
899 
900   std::vector<Entry*> other_sorted = ToPointerVec(other->entries);
901   std::sort(other_sorted.begin(), other_sorted.end(), KeyNameComparator);
902 
903   auto this_iter = this_sorted.begin();
904   const auto this_end = this_sorted.end();
905 
906   auto other_iter = other_sorted.begin();
907   const auto other_end = other_sorted.end();
908 
909   std::vector<Entry> merged_entries;
910   while (this_iter != this_end) {
911     if (other_iter != other_end) {
912       if ((*this_iter)->key.name < (*other_iter)->key.name) {
913         merged_entries.push_back(std::move(**this_iter));
914         ++this_iter;
915       } else {
916         // The other overrides.
917         merged_entries.push_back(CloneEntry(**other_iter, pool));
918         if ((*this_iter)->key.name == (*other_iter)->key.name) {
919           ++this_iter;
920         }
921         ++other_iter;
922       }
923     } else {
924       merged_entries.push_back(std::move(**this_iter));
925       ++this_iter;
926     }
927   }
928 
929   while (other_iter != other_end) {
930     merged_entries.push_back(CloneEntry(**other_iter, pool));
931     ++other_iter;
932   }
933 
934   entries = std::move(merged_entries);
935 }
936 
Equals(const Value * value) const937 bool Array::Equals(const Value* value) const {
938   const Array* other = ValueCast<Array>(value);
939   if (!other) {
940     return false;
941   }
942 
943   if (elements.size() != other->elements.size()) {
944     return false;
945   }
946 
947   return std::equal(elements.begin(), elements.end(), other->elements.begin(),
948                     [](const std::unique_ptr<Item>& a, const std::unique_ptr<Item>& b) -> bool {
949                       return a->Equals(b.get());
950                     });
951 }
952 
Print(std::ostream * out) const953 void Array::Print(std::ostream* out) const {
954   *out << "(array) [" << util::Joiner(elements, ", ") << "]";
955 }
956 
Equals(const Value * value) const957 bool Plural::Equals(const Value* value) const {
958   const Plural* other = ValueCast<Plural>(value);
959   if (!other) {
960     return false;
961   }
962 
963   auto one_iter = values.begin();
964   auto one_end_iter = values.end();
965   auto two_iter = other->values.begin();
966   for (; one_iter != one_end_iter; ++one_iter, ++two_iter) {
967     const std::unique_ptr<Item>& a = *one_iter;
968     const std::unique_ptr<Item>& b = *two_iter;
969     if (a != nullptr && b != nullptr) {
970       if (!a->Equals(b.get())) {
971         return false;
972       }
973     } else if (a != b) {
974       return false;
975     }
976   }
977   return true;
978 }
979 
Print(std::ostream * out) const980 void Plural::Print(std::ostream* out) const {
981   *out << "(plural)";
982   if (values[Zero]) {
983     *out << " zero=" << *values[Zero];
984   }
985 
986   if (values[One]) {
987     *out << " one=" << *values[One];
988   }
989 
990   if (values[Two]) {
991     *out << " two=" << *values[Two];
992   }
993 
994   if (values[Few]) {
995     *out << " few=" << *values[Few];
996   }
997 
998   if (values[Many]) {
999     *out << " many=" << *values[Many];
1000   }
1001 
1002   if (values[Other]) {
1003     *out << " other=" << *values[Other];
1004   }
1005 }
1006 
Equals(const Value * value) const1007 bool Styleable::Equals(const Value* value) const {
1008   const Styleable* other = ValueCast<Styleable>(value);
1009   if (!other) {
1010     return false;
1011   }
1012 
1013   if (entries.size() != other->entries.size()) {
1014     return false;
1015   }
1016 
1017   return std::equal(entries.begin(), entries.end(), other->entries.begin(),
1018                     [](const Reference& a, const Reference& b) -> bool {
1019                       return a.Equals(&b);
1020                     });
1021 }
1022 
Print(std::ostream * out) const1023 void Styleable::Print(std::ostream* out) const {
1024   *out << "(styleable) "
1025        << " [" << util::Joiner(entries, ", ") << "]";
1026 }
1027 
Equals(const Value * value) const1028 bool Macro::Equals(const Value* value) const {
1029   const Macro* other = ValueCast<Macro>(value);
1030   if (!other) {
1031     return false;
1032   }
1033   return other->raw_value == raw_value && other->style_string.spans == style_string.spans &&
1034          other->style_string.str == style_string.str &&
1035          other->untranslatable_sections == untranslatable_sections &&
1036          other->alias_namespaces == alias_namespaces;
1037 }
1038 
Print(std::ostream * out) const1039 void Macro::Print(std::ostream* out) const {
1040   *out << "(macro) ";
1041 }
1042 
operator <(const Reference & a,const Reference & b)1043 bool operator<(const Reference& a, const Reference& b) {
1044   int cmp = a.name.value_or(ResourceName{}).compare(b.name.value_or(ResourceName{}));
1045   if (cmp != 0) return cmp < 0;
1046   return a.id < b.id;
1047 }
1048 
operator ==(const Reference & a,const Reference & b)1049 bool operator==(const Reference& a, const Reference& b) {
1050   return a.name == b.name && a.id == b.id;
1051 }
1052 
operator !=(const Reference & a,const Reference & b)1053 bool operator!=(const Reference& a, const Reference& b) {
1054   return a.name != b.name || a.id != b.id;
1055 }
1056 
1057 struct NameOnlyComparator {
operator ()aapt::NameOnlyComparator1058   bool operator()(const Reference& a, const Reference& b) const {
1059     return a.name < b.name;
1060   }
1061 };
1062 
MergeWith(Styleable * other)1063 void Styleable::MergeWith(Styleable* other) {
1064   // Compare only names, because some References may already have their IDs
1065   // assigned (framework IDs that don't change).
1066   std::set<Reference, NameOnlyComparator> references;
1067   references.insert(entries.begin(), entries.end());
1068   references.insert(other->entries.begin(), other->entries.end());
1069   entries.clear();
1070   entries.reserve(references.size());
1071   entries.insert(entries.end(), references.begin(), references.end());
1072 }
1073 
1074 template <typename T>
CopyValueFields(std::unique_ptr<T> new_value,const T * value)1075 std::unique_ptr<T> CopyValueFields(std::unique_ptr<T> new_value, const T* value) {
1076   new_value->SetSource(value->GetSource());
1077   new_value->SetComment(value->GetComment());
1078   return new_value;
1079 }
1080 
CloningValueTransformer(android::StringPool * new_pool)1081 CloningValueTransformer::CloningValueTransformer(android::StringPool* new_pool)
1082     : ValueTransformer(new_pool) {
1083 }
1084 
TransformDerived(const Reference * value)1085 std::unique_ptr<Reference> CloningValueTransformer::TransformDerived(const Reference* value) {
1086   return std::make_unique<Reference>(*value);
1087 }
1088 
TransformDerived(const Id * value)1089 std::unique_ptr<Id> CloningValueTransformer::TransformDerived(const Id* value) {
1090   return std::make_unique<Id>(*value);
1091 }
1092 
TransformDerived(const RawString * value)1093 std::unique_ptr<RawString> CloningValueTransformer::TransformDerived(const RawString* value) {
1094   auto new_value = std::make_unique<RawString>(pool_->MakeRef(value->value));
1095   return CopyValueFields(std::move(new_value), value);
1096 }
1097 
TransformDerived(const String * value)1098 std::unique_ptr<String> CloningValueTransformer::TransformDerived(const String* value) {
1099   auto new_value = std::make_unique<String>(pool_->MakeRef(value->value));
1100   new_value->untranslatable_sections = value->untranslatable_sections;
1101   return CopyValueFields(std::move(new_value), value);
1102 }
1103 
TransformDerived(const StyledString * value)1104 std::unique_ptr<StyledString> CloningValueTransformer::TransformDerived(const StyledString* value) {
1105   auto new_value = std::make_unique<StyledString>(pool_->MakeRef(value->value));
1106   new_value->untranslatable_sections = value->untranslatable_sections;
1107   return CopyValueFields(std::move(new_value), value);
1108 }
1109 
TransformDerived(const FileReference * value)1110 std::unique_ptr<FileReference> CloningValueTransformer::TransformDerived(
1111     const FileReference* value) {
1112   auto new_value = std::make_unique<FileReference>(pool_->MakeRef(value->path));
1113   new_value->file = value->file;
1114   new_value->type = value->type;
1115   return CopyValueFields(std::move(new_value), value);
1116 }
1117 
TransformDerived(const BinaryPrimitive * value)1118 std::unique_ptr<BinaryPrimitive> CloningValueTransformer::TransformDerived(
1119     const BinaryPrimitive* value) {
1120   return std::make_unique<BinaryPrimitive>(*value);
1121 }
1122 
TransformDerived(const Attribute * value)1123 std::unique_ptr<Attribute> CloningValueTransformer::TransformDerived(const Attribute* value) {
1124   auto new_value = std::make_unique<Attribute>();
1125   new_value->type_mask = value->type_mask;
1126   new_value->min_int = value->min_int;
1127   new_value->max_int = value->max_int;
1128   for (const Attribute::Symbol& s : value->symbols) {
1129     new_value->symbols.emplace_back(Attribute::Symbol{
1130         .symbol = *s.symbol.Transform(*this),
1131         .value = s.value,
1132         .type = s.type,
1133     });
1134   }
1135   return CopyValueFields(std::move(new_value), value);
1136 }
1137 
TransformDerived(const Style * value)1138 std::unique_ptr<Style> CloningValueTransformer::TransformDerived(const Style* value) {
1139   auto new_value = std::make_unique<Style>();
1140   new_value->parent = value->parent;
1141   new_value->parent_inferred = value->parent_inferred;
1142   for (auto& entry : value->entries) {
1143     new_value->entries.push_back(Style::Entry{entry.key, entry.value->Transform(*this)});
1144   }
1145   return CopyValueFields(std::move(new_value), value);
1146 }
1147 
TransformDerived(const Array * value)1148 std::unique_ptr<Array> CloningValueTransformer::TransformDerived(const Array* value) {
1149   auto new_value = std::make_unique<Array>();
1150   for (auto& item : value->elements) {
1151     new_value->elements.emplace_back(item->Transform(*this));
1152   }
1153   return CopyValueFields(std::move(new_value), value);
1154 }
1155 
TransformDerived(const Plural * value)1156 std::unique_ptr<Plural> CloningValueTransformer::TransformDerived(const Plural* value) {
1157   auto new_value = std::make_unique<Plural>();
1158   const size_t count = value->values.size();
1159   for (size_t i = 0; i < count; i++) {
1160     if (value->values[i]) {
1161       new_value->values[i] = value->values[i]->Transform(*this);
1162     }
1163   }
1164   return CopyValueFields(std::move(new_value), value);
1165 }
1166 
TransformDerived(const Styleable * value)1167 std::unique_ptr<Styleable> CloningValueTransformer::TransformDerived(const Styleable* value) {
1168   auto new_value = std::make_unique<Styleable>();
1169   for (const Reference& s : value->entries) {
1170     new_value->entries.emplace_back(*s.Transform(*this));
1171   }
1172   return CopyValueFields(std::move(new_value), value);
1173 }
1174 
TransformDerived(const Macro * value)1175 std::unique_ptr<Macro> CloningValueTransformer::TransformDerived(const Macro* value) {
1176   auto new_value = std::make_unique<Macro>(*value);
1177   return CopyValueFields(std::move(new_value), value);
1178 }
1179 
1180 }  // namespace aapt
1181