Debian Codegraph @

tools/aapt2/ResourceParser.cpp

raw symbols SCIP
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 "ResourceParser.h"
18
19 #include <functional>
20 #include <limits>
21 #include <sstream>
22
23 #include <android-base/logging.h>
24 #include <idmap2/Policies.h>
25
26 #include "ResourceTable.h"
27 #include "ResourceUtils.h"
28 #include "ResourceValues.h"
29 #include "ValueVisitor.h"
30 #include "text/Utf8Iterator.h"
31 #include "util/ImmutableMap.h"
32
33 #include "util/Util.h"
34 #include "xml/XmlPullParser.h"
35
36 using ::aapt::ResourceUtils::StringBuilder;
37 using ::aapt::text::Utf8Iterator;
38 using ::android::ConfigDescription;
39 using ::android::StringPiece;
40
41 using android::idmap2::policy::kPolicyStringToFlag;
42
43 namespace aapt {
44 namespace {
45 constexpr const char* kPublicGroupTag = "public-group";
46 constexpr const char* kStagingPublicGroupTag = "staging-public-group";
47 constexpr const char* kStagingPublicGroupFinalTag = "staging-public-group-final";
48 } // namespace
49
50 constexpr const char* sXliffNamespaceUri = "urn:oasis:names:tc:xliff:document:1.2";
51
52 // Returns true if the element is <skip> or <eat-comment> and can be safely ignored.
53 static bool ShouldIgnoreElement(const StringPiece& ns, const StringPiece& name) {
54 return ns.empty() && (name == "skip" || name == "eat-comment");
55 }
56
57 static uint32_t ParseFormatTypeNoEnumsOrFlags(const StringPiece& piece) {
58 if (piece == "reference") {
59 return android::ResTable_map::TYPE_REFERENCE;
60 } else if (piece == "string") {
61 return android::ResTable_map::TYPE_STRING;
62 } else if (piece == "integer") {
63 return android::ResTable_map::TYPE_INTEGER;
64 } else if (piece == "boolean") {
65 return android::ResTable_map::TYPE_BOOLEAN;
66 } else if (piece == "color") {
67 return android::ResTable_map::TYPE_COLOR;
68 } else if (piece == "float") {
69 return android::ResTable_map::TYPE_FLOAT;
70 } else if (piece == "dimension") {
71 return android::ResTable_map::TYPE_DIMENSION;
72 } else if (piece == "fraction") {
73 return android::ResTable_map::TYPE_FRACTION;
74 }
75 return 0;
76 }
77
78 static uint32_t ParseFormatType(const StringPiece& piece) {
79 if (piece == "enum") {
80 return android::ResTable_map::TYPE_ENUM;
81 } else if (piece == "flags") {
82 return android::ResTable_map::TYPE_FLAGS;
83 }
84 return ParseFormatTypeNoEnumsOrFlags(piece);
85 }
86
87 static uint32_t ParseFormatAttribute(const StringPiece& str) {
88 uint32_t mask = 0;
89 for (const StringPiece& part : util::Tokenize(str, '|')) {
90 StringPiece trimmed_part = util::TrimWhitespace(part);
91 uint32_t type = ParseFormatType(trimmed_part);
92 if (type == 0) {
93 return 0;
94 }
95 mask |= type;
96 }
97 return mask;
98 }
99
100 // A parsed resource ready to be added to the ResourceTable.
101 struct ParsedResource {
102 ResourceName name;
103 ConfigDescription config;
104 std::string product;
105 Source source;
106
107 ResourceId id;
108 Visibility::Level visibility_level = Visibility::Level::kUndefined;
109 bool staged_api = false;
110 bool allow_new = false;
111 std::optional<OverlayableItem> overlayable_item;
112 std::optional<StagedId> staged_alias;
113
114 std::string comment;
115 std::unique_ptr<Value> value;
116 std::list<ParsedResource> child_resources;
117 };
118
119 // Recursively adds resources to the ResourceTable.
120 static bool AddResourcesToTable(ResourceTable* table, IDiagnostics* diag, ParsedResource* res) {
121 StringPiece trimmed_comment = util::TrimWhitespace(res->comment);
122 if (trimmed_comment.size() != res->comment.size()) {
123 // Only if there was a change do we re-assign.
124 res->comment = trimmed_comment.to_string();
125 }
126
127 NewResourceBuilder res_builder(res->name);
128 if (res->visibility_level != Visibility::Level::kUndefined) {
129 Visibility visibility;
130 visibility.level = res->visibility_level;
131 visibility.staged_api = res->staged_api;
132 visibility.source = res->source;
133 visibility.comment = res->comment;
134 res_builder.SetVisibility(visibility);
135 }
136
137 if (res->id.is_valid()) {
138 res_builder.SetId(res->id);
139 }
140
141 if (res->allow_new) {
142 AllowNew allow_new;
143 allow_new.source = res->source;
144 allow_new.comment = res->comment;
145 res_builder.SetAllowNew(allow_new);
146 }
147
148 if (res->overlayable_item) {
149 res_builder.SetOverlayable(res->overlayable_item.value());
150 }
151
152 if (res->value != nullptr) {
153 // Attach the comment, source and config to the value.
154 res->value->SetComment(std::move(res->comment));
155 res->value->SetSource(std::move(res->source));
156 res_builder.SetValue(std::move(res->value), res->config, res->product);
157 }
158
159 if (res->staged_alias) {
160 res_builder.SetStagedId(res->staged_alias.value());
161 }
162
163 bool error = false;
164 if (!res->name.entry.empty()) {
165 if (!table->AddResource(res_builder.Build(), diag)) {
166 return false;
167 }
168 }
169 for (ParsedResource& child : res->child_resources) {
170 error |= !AddResourcesToTable(table, diag, &child);
171 }
172 return !error;
173 }
174
175 // Convenient aliases for more readable function calls.
176 enum { kAllowRawString = true, kNoRawString = false };
177
178 ResourceParser::ResourceParser(IDiagnostics* diag, ResourceTable* table,
179 const Source& source,
180 const ConfigDescription& config,
181 const ResourceParserOptions& options)
182 : diag_(diag),
183 table_(table),
184 source_(source),
185 config_(config),
186 options_(options) {}
187
188 // Base class Node for representing the various Spans and UntranslatableSections of an XML string.
189 // This will be used to traverse and flatten the XML string into a single std::string, with all
190 // Span and Untranslatable data maintained in parallel, as indices into the string.
191 class Node {
192 public:
193 virtual ~Node() = default;
194
195 // Adds the given child node to this parent node's set of child nodes, moving ownership to the
196 // parent node as well.
197 // Returns a pointer to the child node that was added as a convenience.
198 template <typename T>
199 T* AddChild(std::unique_ptr<T> node) {
200 T* raw_ptr = node.get();
201 children.push_back(std::move(node));
202 return raw_ptr;
203 }
204
205 virtual void Build(StringBuilder* builder) const {
206 for (const auto& child : children) {
207 child->Build(builder);
208 }
209 }
210
211 std::vector<std::unique_ptr<Node>> children;
212 };
213
214 // A chunk of text in the XML string. This lives between other tags, such as XLIFF tags and Spans.
215 class SegmentNode : public Node {
216 public:
217 std::string data;
218
219 void Build(StringBuilder* builder) const override {
220 builder->AppendText(data);
221 }
222 };
223
224 // A tag that will be encoded into the final flattened string. Tags like <b> or <i>.
225 class SpanNode : public Node {
226 public:
227 std::string name;
228
229 void Build(StringBuilder* builder) const override {
230 StringBuilder::SpanHandle span_handle = builder->StartSpan(name);
231 Node::Build(builder);
232 builder->EndSpan(span_handle);
233 }
234 };
235
236 // An XLIFF 'g' tag, which marks a section of the string as untranslatable.
237 class UntranslatableNode : public Node {
238 public:
239 void Build(StringBuilder* builder) const override {
240 StringBuilder::UntranslatableHandle handle = builder->StartUntranslatable();
241 Node::Build(builder);
242 builder->EndUntranslatable(handle);
243 }
244 };
245
246 // Build a string from XML that converts nested elements into Span objects.
247 bool ResourceParser::FlattenXmlSubtree(
248 xml::XmlPullParser* parser, std::string* out_raw_string, StyleString* out_style_string,
249 std::vector<UntranslatableSection>* out_untranslatable_sections) {
250 std::string raw_string;
251 std::string current_text;
252
253 // The first occurrence of a <xliff:g> tag. Nested <xliff:g> tags are illegal.
254 std::optional<size_t> untranslatable_start_depth;
255
256 Node root;
257 std::vector<Node*> node_stack;
258 node_stack.push_back(&root);
259
260 bool saw_span_node = false;
261 SegmentNode* first_segment = nullptr;
262 SegmentNode* last_segment = nullptr;
263
264 size_t depth = 1;
265 while (depth > 0 && xml::XmlPullParser::IsGoodEvent(parser->Next())) {
266 const xml::XmlPullParser::Event event = parser->event();
267
268 // First take care of any SegmentNodes that should be created.
269 if (event == xml::XmlPullParser::Event::kStartElement
270 || event == xml::XmlPullParser::Event::kEndElement) {
271 if (!current_text.empty()) {
272 auto segment_node = util::make_unique<SegmentNode>();
273 segment_node->data = std::move(current_text);
274
275 last_segment = node_stack.back()->AddChild(std::move(segment_node));
276 if (first_segment == nullptr) {
277 first_segment = last_segment;
278 }
279 current_text = {};
280 }
281 }
282
283 switch (event) {
284 case xml::XmlPullParser::Event::kText: {
285 current_text += parser->text();
286 raw_string += parser->text();
287 } break;
288
289 case xml::XmlPullParser::Event::kStartElement: {
290 if (parser->element_namespace().empty()) {
291 // This is an HTML tag which we encode as a span. Add it to the span stack.
292 std::unique_ptr<SpanNode> span_node = util::make_unique<SpanNode>();
293 span_node->name = parser->element_name();
294 const auto end_attr_iter = parser->end_attributes();
295 for (auto attr_iter = parser->begin_attributes(); attr_iter != end_attr_iter;
296 ++attr_iter) {
297 span_node->name += ";";
298 span_node->name += attr_iter->name;
299 span_node->name += "=";
300 span_node->name += attr_iter->value;
301 }
302
303 node_stack.push_back(node_stack.back()->AddChild(std::move(span_node)));
304 saw_span_node = true;
305 } else if (parser->element_namespace() == sXliffNamespaceUri) {
306 // This is an XLIFF tag, which is not encoded as a span.
307 if (parser->element_name() == "g") {
308 // Check that an 'untranslatable' tag is not already being processed. Nested
309 // <xliff:g> tags are illegal.
310 if (untranslatable_start_depth) {
311 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
312 << "illegal nested XLIFF 'g' tag");
313 return false;
314 } else {
315 // Mark the beginning of an 'untranslatable' section.
316 untranslatable_start_depth = depth;
317 node_stack.push_back(
318 node_stack.back()->AddChild(util::make_unique<UntranslatableNode>()));
319 }
320 } else {
321 // Ignore unknown XLIFF tags, but don't warn.
322 node_stack.push_back(node_stack.back()->AddChild(util::make_unique<Node>()));
323 }
324 } else {
325 // Besides XLIFF, any other namespaced tag is unsupported and ignored.
326 diag_->Warn(DiagMessage(source_.WithLine(parser->line_number()))
327 << "ignoring element '" << parser->element_name()
328 << "' with unknown namespace '" << parser->element_namespace() << "'");
329 node_stack.push_back(node_stack.back()->AddChild(util::make_unique<Node>()));
330 }
331
332 // Enter one level inside the element.
333 depth++;
334 } break;
335
336 case xml::XmlPullParser::Event::kEndElement: {
337 // Return one level from within the element.
338 depth--;
339 if (depth == 0) {
340 break;
341 }
342
343 node_stack.pop_back();
344 if (untranslatable_start_depth == depth) {
345 // This is the end of an untranslatable section.
346 untranslatable_start_depth = {};
347 }
348 } break;
349
350 default:
351 // ignore.
352 break;
353 }
354 }
355
356 // Validity check to make sure we processed all the nodes.
357 CHECK(node_stack.size() == 1u);
358 CHECK(node_stack.back() == &root);
359
360 if (!saw_span_node) {
361 // If there were no spans, we must treat this string a little differently (according to AAPT).
362 // Find and strip the leading whitespace from the first segment, and the trailing whitespace
363 // from the last segment.
364 if (first_segment != nullptr) {
365 // Trim leading whitespace.
366 StringPiece trimmed = util::TrimLeadingWhitespace(first_segment->data);
367 if (trimmed.size() != first_segment->data.size()) {
368 first_segment->data = trimmed.to_string();
369 }
370 }
371
372 if (last_segment != nullptr) {
373 // Trim trailing whitespace.
374 StringPiece trimmed = util::TrimTrailingWhitespace(last_segment->data);
375 if (trimmed.size() != last_segment->data.size()) {
376 last_segment->data = trimmed.to_string();
377 }
378 }
379 }
380
381 // Have the XML structure flatten itself into the StringBuilder. The StringBuilder will take
382 // care of recording the correctly adjusted Spans and UntranslatableSections.
383 StringBuilder builder;
384 root.Build(&builder);
385 if (!builder) {
386 diag_->Error(DiagMessage(source_.WithLine(parser->line_number())) << builder.GetError());
387 return false;
388 }
389
390 ResourceUtils::FlattenedXmlString flattened_string = builder.GetFlattenedString();
391 *out_raw_string = std::move(raw_string);
392 *out_untranslatable_sections = std::move(flattened_string.untranslatable_sections);
393 out_style_string->str = std::move(flattened_string.text);
394 out_style_string->spans = std::move(flattened_string.spans);
395 return true;
396 }
397
398 bool ResourceParser::Parse(xml::XmlPullParser* parser) {
399 bool error = false;
400 const size_t depth = parser->depth();
401 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
402 if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
403 // Skip comments and text.
404 continue;
405 }
406
407 if (!parser->element_namespace().empty() || parser->element_name() != "resources") {
408 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
409 << "root element must be <resources>");
410 return false;
411 }
412
413 error |= !ParseResources(parser);
414 break;
415 };
416
417 if (parser->event() == xml::XmlPullParser::Event::kBadDocument) {
418 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
419 << "xml parser error: " << parser->error());
420 return false;
421 }
422 return !error;
423 }
424
425 bool ResourceParser::ParseResources(xml::XmlPullParser* parser) {
426 std::set<ResourceName> stripped_resources;
427
428 bool error = false;
429 std::string comment;
430 const size_t depth = parser->depth();
431 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
432 const xml::XmlPullParser::Event event = parser->event();
433 if (event == xml::XmlPullParser::Event::kComment) {
434 comment = parser->comment();
435 continue;
436 }
437
438 if (event == xml::XmlPullParser::Event::kText) {
439 if (!util::TrimWhitespace(parser->text()).empty()) {
440 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
441 << "plain text not allowed here");
442 error = true;
443 }
444 continue;
445 }
446
447 CHECK(event == xml::XmlPullParser::Event::kStartElement);
448
449 if (!parser->element_namespace().empty()) {
450 // Skip unknown namespace.
451 continue;
452 }
453
454 std::string element_name = parser->element_name();
455 if (element_name == "skip" || element_name == "eat-comment") {
456 comment = "";
457 continue;
458 }
459
460 ParsedResource parsed_resource;
461 parsed_resource.config = config_;
462 parsed_resource.source = source_.WithLine(parser->line_number());
463 parsed_resource.comment = std::move(comment);
464 comment.clear();
465 if (options_.visibility) {
466 parsed_resource.visibility_level = options_.visibility.value();
467 }
468
469 // Extract the product name if it exists.
470 if (std::optional<StringPiece> maybe_product = xml::FindNonEmptyAttribute(parser, "product")) {
471 parsed_resource.product = maybe_product.value().to_string();
472 }
473
474 // Parse the resource regardless of product.
475 if (!ParseResource(parser, &parsed_resource)) {
476 error = true;
477 continue;
478 }
479
480 if (!AddResourcesToTable(table_, diag_, &parsed_resource)) {
481 error = true;
482 }
483 }
484
485 // Check that we included at least one variant of each stripped resource.
486 for (const ResourceName& stripped_resource : stripped_resources) {
487 if (!table_->FindResource(stripped_resource)) {
488 // Failed to find the resource.
489 diag_->Error(DiagMessage(source_) << "resource '" << stripped_resource
490 << "' was filtered out but no product variant remains");
491 error = true;
492 }
493 }
494
495 return !error;
496 }
497
498 bool ResourceParser::ParseResource(xml::XmlPullParser* parser,
499 ParsedResource* out_resource) {
500 struct ItemTypeFormat {
501 ResourceType type;
502 uint32_t format;
503 };
504
505 using BagParseFunc = std::function<bool(ResourceParser*, xml::XmlPullParser*,
506 ParsedResource*)>;
507
508 static const auto elToItemMap = ImmutableMap<std::string, ItemTypeFormat>::CreatePreSorted({
509 {"bool", {ResourceType::kBool, android::ResTable_map::TYPE_BOOLEAN}},
510 {"color", {ResourceType::kColor, android::ResTable_map::TYPE_COLOR}},
511 {"configVarying", {ResourceType::kConfigVarying, android::ResTable_map::TYPE_ANY}},
512 {"dimen",
513 {ResourceType::kDimen,
514 android::ResTable_map::TYPE_FLOAT | android::ResTable_map::TYPE_FRACTION |
515 android::ResTable_map::TYPE_DIMENSION}},
516 {"drawable", {ResourceType::kDrawable, android::ResTable_map::TYPE_COLOR}},
517 {"fraction",
518 {ResourceType::kFraction,
519 android::ResTable_map::TYPE_FLOAT | android::ResTable_map::TYPE_FRACTION |
520 android::ResTable_map::TYPE_DIMENSION}},
521 {"integer", {ResourceType::kInteger, android::ResTable_map::TYPE_INTEGER}},
522 {"string", {ResourceType::kString, android::ResTable_map::TYPE_STRING}},
523 });
524
525 static const auto elToBagMap = ImmutableMap<std::string, BagParseFunc>::CreatePreSorted({
526 {"add-resource", std::mem_fn(&ResourceParser::ParseAddResource)},
527 {"array", std::mem_fn(&ResourceParser::ParseArray)},
528 {"attr", std::mem_fn(&ResourceParser::ParseAttr)},
529 {"configVarying",
530 std::bind(&ResourceParser::ParseStyle, std::placeholders::_1, ResourceType::kConfigVarying,
531 std::placeholders::_2, std::placeholders::_3)},
532 {"declare-styleable", std::mem_fn(&ResourceParser::ParseDeclareStyleable)},
533 {"integer-array", std::mem_fn(&ResourceParser::ParseIntegerArray)},
534 {"java-symbol", std::mem_fn(&ResourceParser::ParseSymbol)},
535 {"overlayable", std::mem_fn(&ResourceParser::ParseOverlayable)},
536 {"plurals", std::mem_fn(&ResourceParser::ParsePlural)},
537 {"public", std::mem_fn(&ResourceParser::ParsePublic)},
538 {"public-group", std::mem_fn(&ResourceParser::ParsePublicGroup)},
539 {"staging-public-group", std::mem_fn(&ResourceParser::ParseStagingPublicGroup)},
540 {"staging-public-group-final", std::mem_fn(&ResourceParser::ParseStagingPublicGroupFinal)},
541 {"string-array", std::mem_fn(&ResourceParser::ParseStringArray)},
542 {"style", std::bind(&ResourceParser::ParseStyle, std::placeholders::_1, ResourceType::kStyle,
543 std::placeholders::_2, std::placeholders::_3)},
544 {"symbol", std::mem_fn(&ResourceParser::ParseSymbol)},
545 });
546
547 std::string resource_type = parser->element_name();
548
549 // The value format accepted for this resource.
550 uint32_t resource_format = 0u;
551
552 bool can_be_item = true;
553 bool can_be_bag = true;
554 if (resource_type == "item") {
555 can_be_bag = false;
556
557 // The default format for <item> is any. If a format attribute is present, that one will
558 // override the default.
559 resource_format = android::ResTable_map::TYPE_ANY;
560
561 // Items have their type encoded in the type attribute.
562 if (std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type")) {
563 resource_type = maybe_type.value().to_string();
564 } else {
565 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
566 << "<item> must have a 'type' attribute");
567 return false;
568 }
569
570 if (std::optional<StringPiece> maybe_format = xml::FindNonEmptyAttribute(parser, "format")) {
571 // An explicit format for this resource was specified. The resource will
572 // retain its type in its name, but the accepted value for this type is
573 // overridden.
574 resource_format = ParseFormatTypeNoEnumsOrFlags(maybe_format.value());
575 if (!resource_format) {
576 diag_->Error(DiagMessage(out_resource->source)
577 << "'" << maybe_format.value()
578 << "' is an invalid format");
579 return false;
580 }
581 }
582 } else if (resource_type == "bag") {
583 can_be_item = false;
584
585 // Bags have their type encoded in the type attribute.
586 if (std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type")) {
587 resource_type = maybe_type.value().to_string();
588 } else {
589 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
590 << "<bag> must have a 'type' attribute");
591 return false;
592 }
593 }
594
595 // Get the name of the resource. This will be checked later, because not all
596 // XML elements require a name.
597 std::optional<StringPiece> maybe_name = xml::FindNonEmptyAttribute(parser, "name");
598
599 if (resource_type == "id") {
600 if (!maybe_name) {
601 diag_->Error(DiagMessage(out_resource->source)
602 << "<" << parser->element_name()
603 << "> missing 'name' attribute");
604 return false;
605 }
606
607 out_resource->name.type =
608 ResourceNamedTypeWithDefaultName(ResourceType::kId).ToResourceNamedType();
609 out_resource->name.entry = maybe_name.value().to_string();
610
611 // Ids either represent a unique resource id or reference another resource id
612 auto item = ParseItem(parser, out_resource, resource_format);
613 if (!item) {
614 return false;
615 }
616
617 String* empty = ValueCast<String>(out_resource->value.get());
618 if (empty && *empty->value == "") {
619 // If no inner element exists, represent a unique identifier
620 out_resource->value = util::make_unique<Id>();
621 } else {
622 Reference* ref = ValueCast<Reference>(out_resource->value.get());
623 if (ref && !ref->name && !ref->id) {
624 // A null reference also means there is no inner element when ids are in the form:
625 // <id name="name"/>
626 out_resource->value = util::make_unique<Id>();
627 } else if (!ref || ref->name.value().type.type != ResourceType::kId) {
628 // If an inner element exists, the inner element must be a reference to another resource id
629 diag_->Error(DiagMessage(out_resource->source)
630 << "<" << parser->element_name()
631 << "> inner element must either be a resource reference or empty");
632 return false;
633 }
634 }
635
636 return true;
637 } else if (resource_type == "macro") {
638 if (!maybe_name) {
639 diag_->Error(DiagMessage(out_resource->source)
640 << "<" << parser->element_name() << "> missing 'name' attribute");
641 return false;
642 }
643
644 out_resource->name.type =
645 ResourceNamedTypeWithDefaultName(ResourceType::kMacro).ToResourceNamedType();
646 out_resource->name.entry = maybe_name.value().to_string();
647 return ParseMacro(parser, out_resource);
648 }
649
650 if (can_be_item) {
651 const auto item_iter = elToItemMap.find(resource_type);
652 if (item_iter != elToItemMap.end()) {
653 // This is an item, record its type and format and start parsing.
654
655 if (!maybe_name) {
656 diag_->Error(DiagMessage(out_resource->source)
657 << "<" << parser->element_name() << "> missing 'name' attribute");
658 return false;
659 }
660
661 out_resource->name.type =
662 ResourceNamedTypeWithDefaultName(item_iter->second.type).ToResourceNamedType();
663 out_resource->name.entry = maybe_name.value().to_string();
664
665 // Only use the implied format of the type when there is no explicit format.
666 if (resource_format == 0u) {
667 resource_format = item_iter->second.format;
668 }
669
670 if (!ParseItem(parser, out_resource, resource_format)) {
671 return false;
672 }
673 return true;
674 }
675 }
676
677 // This might be a bag or something.
678 if (can_be_bag) {
679 const auto bag_iter = elToBagMap.find(resource_type);
680 if (bag_iter != elToBagMap.end()) {
681 // Ensure we have a name (unless this is a <public-group> or <overlayable>).
682 if (resource_type != kPublicGroupTag && resource_type != kStagingPublicGroupTag &&
683 resource_type != kStagingPublicGroupFinalTag && resource_type != "overlayable") {
684 if (!maybe_name) {
685 diag_->Error(DiagMessage(out_resource->source)
686 << "<" << parser->element_name() << "> missing 'name' attribute");
687 return false;
688 }
689
690 out_resource->name.entry = maybe_name.value().to_string();
691 }
692
693 // Call the associated parse method. The type will be filled in by the
694 // parse func.
695 if (!bag_iter->second(this, parser, out_resource)) {
696 return false;
697 }
698 return true;
699 }
700 }
701
702 if (can_be_item) {
703 // Try parsing the elementName (or type) as a resource. These shall only be
704 // resources like 'layout' or 'xml' and they can only be references.
705 std::optional<ResourceNamedTypeRef> parsed_type = ParseResourceNamedType(resource_type);
706 if (parsed_type) {
707 if (!maybe_name) {
708 diag_->Error(DiagMessage(out_resource->source)
709 << "<" << parser->element_name()
710 << "> missing 'name' attribute");
711 return false;
712 }
713
714 out_resource->name.type = parsed_type->ToResourceNamedType();
715 out_resource->name.entry = maybe_name.value().to_string();
716 out_resource->value = ParseXml(parser, android::ResTable_map::TYPE_REFERENCE, kNoRawString);
717 if (!out_resource->value) {
718 diag_->Error(DiagMessage(out_resource->source)
719 << "invalid value for type '" << *parsed_type << "'. Expected a reference");
720 return false;
721 }
722 return true;
723 }
724 }
725
726 // If the resource type was not recognized, write the error and return false.
727 diag_->Error(DiagMessage(out_resource->source)
728 << "unknown resource type '" << resource_type << "'");
729 return false;
730 }
731
732 bool ResourceParser::ParseItem(xml::XmlPullParser* parser,
733 ParsedResource* out_resource,
734 const uint32_t format) {
735 if (format == android::ResTable_map::TYPE_STRING) {
736 return ParseString(parser, out_resource);
737 }
738
739 out_resource->value = ParseXml(parser, format, kNoRawString);
740 if (!out_resource->value) {
741 diag_->Error(DiagMessage(out_resource->source) << "invalid "
742 << out_resource->name.type);
743 return false;
744 }
745 return true;
746 }
747
748 std::optional<FlattenedXmlSubTree> ResourceParser::CreateFlattenSubTree(
749 xml::XmlPullParser* parser) {
750 const size_t begin_xml_line = parser->line_number();
751
752 std::string raw_value;
753 StyleString style_string;
754 std::vector<UntranslatableSection> untranslatable_sections;
755 if (!FlattenXmlSubtree(parser, &raw_value, &style_string, &untranslatable_sections)) {
756 return {};
757 }
758
759 return FlattenedXmlSubTree{.raw_value = raw_value,
760 .style_string = style_string,
761 .untranslatable_sections = untranslatable_sections,
762 .namespace_resolver = parser,
763 .source = source_.WithLine(begin_xml_line)};
764 }
765
766 /**
767 * Reads the entire XML subtree and attempts to parse it as some Item,
768 * with typeMask denoting which items it can be. If allowRawValue is
769 * true, a RawString is returned if the XML couldn't be parsed as
770 * an Item. If allowRawValue is false, nullptr is returned in this
771 * case.
772 */
773 std::unique_ptr<Item> ResourceParser::ParseXml(xml::XmlPullParser* parser, const uint32_t type_mask,
774 const bool allow_raw_value) {
775 auto sub_tree = CreateFlattenSubTree(parser);
776 if (!sub_tree.has_value()) {
777 return {};
778 }
779 return ParseXml(sub_tree.value(), type_mask, allow_raw_value, *table_, config_, *diag_);
780 }
781
782 std::unique_ptr<Item> ResourceParser::ParseXml(const FlattenedXmlSubTree& xmlsub_tree,
783 const uint32_t type_mask, const bool allow_raw_value,
784 ResourceTable& table,
785 const android::ConfigDescription& config,
786 IDiagnostics& diag) {
787 if (!xmlsub_tree.style_string.spans.empty()) {
788 // This can only be a StyledString.
789 std::unique_ptr<StyledString> styled_string =
790 util::make_unique<StyledString>(table.string_pool.MakeRef(
791 xmlsub_tree.style_string,
792 StringPool::Context(StringPool::Context::kNormalPriority, config)));
793 styled_string->untranslatable_sections = xmlsub_tree.untranslatable_sections;
794 return std::move(styled_string);
795 }
796
797 auto on_create_reference = [&](const ResourceName& name) {
798 // name.package can be empty here, as it will assume the package name of the
799 // table.
800 auto id = util::make_unique<Id>();
801 id->SetSource(xmlsub_tree.source);
802 return table.AddResource(NewResourceBuilder(name).SetValue(std::move(id)).Build(), &diag);
803 };
804
805 // Process the raw value.
806 std::unique_ptr<Item> processed_item = ResourceUtils::TryParseItemForAttribute(
807 xmlsub_tree.raw_value, type_mask, on_create_reference);
808 if (processed_item) {
809 // Fix up the reference.
810 if (auto ref = ValueCast<Reference>(processed_item.get())) {
811 ref->allow_raw = allow_raw_value;
812 ResolvePackage(xmlsub_tree.namespace_resolver, ref);
813 }
814 return processed_item;
815 }
816
817 // Try making a regular string.
818 if (type_mask & android::ResTable_map::TYPE_STRING) {
819 // Use the trimmed, escaped string.
820 std::unique_ptr<String> string = util::make_unique<String>(
821 table.string_pool.MakeRef(xmlsub_tree.style_string.str, StringPool::Context(config)));
822 string->untranslatable_sections = xmlsub_tree.untranslatable_sections;
823 return std::move(string);
824 }
825
826 if (allow_raw_value) {
827 // We can't parse this so return a RawString if we are allowed.
828 return util::make_unique<RawString>(table.string_pool.MakeRef(
829 util::TrimWhitespace(xmlsub_tree.raw_value), StringPool::Context(config)));
830 } else if (util::TrimWhitespace(xmlsub_tree.raw_value).empty()) {
831 // If the text is empty, and the value is not allowed to be a string, encode it as a @null.
832 return ResourceUtils::MakeNull();
833 }
834 return {};
835 }
836
837 bool ResourceParser::ParseString(xml::XmlPullParser* parser,
838 ParsedResource* out_resource) {
839 bool formatted = true;
840 if (std::optional<StringPiece> formatted_attr = xml::FindAttribute(parser, "formatted")) {
841 std::optional<bool> maybe_formatted = ResourceUtils::ParseBool(formatted_attr.value());
842 if (!maybe_formatted) {
843 diag_->Error(DiagMessage(out_resource->source)
844 << "invalid value for 'formatted'. Must be a boolean");
845 return false;
846 }
847 formatted = maybe_formatted.value();
848 }
849
850 bool translatable = options_.translatable;
851 if (std::optional<StringPiece> translatable_attr = xml::FindAttribute(parser, "translatable")) {
852 std::optional<bool> maybe_translatable = ResourceUtils::ParseBool(translatable_attr.value());
853 if (!maybe_translatable) {
854 diag_->Error(DiagMessage(out_resource->source)
855 << "invalid value for 'translatable'. Must be a boolean");
856 return false;
857 }
858 translatable = maybe_translatable.value();
859 }
860
861 out_resource->value =
862 ParseXml(parser, android::ResTable_map::TYPE_STRING, kNoRawString);
863 if (!out_resource->value) {
864 diag_->Error(DiagMessage(out_resource->source) << "not a valid string");
865 return false;
866 }
867
868 if (String* string_value = ValueCast<String>(out_resource->value.get())) {
869 string_value->SetTranslatable(translatable);
870
871 if (formatted && translatable) {
872 if (!util::VerifyJavaStringFormat(*string_value->value)) {
873 DiagMessage msg(out_resource->source);
874 msg << "multiple substitutions specified in non-positional format; "
875 "did you mean to add the formatted=\"false\" attribute?";
876 if (options_.error_on_positional_arguments) {
877 diag_->Error(msg);
878 return false;
879 }
880
881 diag_->Warn(msg);
882 }
883 }
884
885 } else if (StyledString* string_value = ValueCast<StyledString>(out_resource->value.get())) {
886 string_value->SetTranslatable(translatable);
887 }
888 return true;
889 }
890
891 bool ResourceParser::ParseMacro(xml::XmlPullParser* parser, ParsedResource* out_resource) {
892 auto sub_tree = CreateFlattenSubTree(parser);
893 if (!sub_tree) {
894 return false;
895 }
896
897 if (out_resource->config != ConfigDescription::DefaultConfig()) {
898 diag_->Error(DiagMessage(out_resource->source)
899 << "<macro> tags cannot be declared in configurations other than the default "
900 "configuration'");
901 return false;
902 }
903
904 auto macro = std::make_unique<Macro>();
905 macro->raw_value = std::move(sub_tree->raw_value);
906 macro->style_string = std::move(sub_tree->style_string);
907 macro->untranslatable_sections = std::move(sub_tree->untranslatable_sections);
908
909 for (const auto& decl : parser->package_decls()) {
910 macro->alias_namespaces.emplace_back(
911 Macro::Namespace{.alias = decl.prefix,
912 .package_name = decl.package.package,
913 .is_private = decl.package.private_namespace});
914 }
915
916 out_resource->value = std::move(macro);
917 return true;
918 }
919
920 bool ResourceParser::ParsePublic(xml::XmlPullParser* parser, ParsedResource* out_resource) {
921 if (options_.visibility) {
922 diag_->Error(DiagMessage(out_resource->source)
923 << "<public> tag not allowed with --visibility flag");
924 return false;
925 }
926
927 if (out_resource->config != ConfigDescription::DefaultConfig()) {
928 diag_->Warn(DiagMessage(out_resource->source)
929 << "ignoring configuration '" << out_resource->config << "' for <public> tag");
930 }
931
932 std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type");
933 if (!maybe_type) {
934 diag_->Error(DiagMessage(out_resource->source)
935 << "<public> must have a 'type' attribute");
936 return false;
937 }
938
939 std::optional<ResourceNamedTypeRef> parsed_type = ParseResourceNamedType(maybe_type.value());
940 if (!parsed_type) {
941 diag_->Error(DiagMessage(out_resource->source) << "invalid resource type '"
942 << maybe_type.value()
943 << "' in <public>");
944 return false;
945 }
946
947 out_resource->name.type = parsed_type->ToResourceNamedType();
948
949 if (std::optional<StringPiece> maybe_id_str = xml::FindNonEmptyAttribute(parser, "id")) {
950 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(maybe_id_str.value());
951 if (!maybe_id) {
952 diag_->Error(DiagMessage(out_resource->source)
953 << "invalid resource ID '" << maybe_id_str.value() << "' in <public>");
954 return false;
955 }
956 out_resource->id = maybe_id.value();
957 }
958
959 if (parsed_type->type == ResourceType::kId) {
960 // An ID marked as public is also the definition of an ID.
961 out_resource->value = util::make_unique<Id>();
962 }
963
964 out_resource->visibility_level = Visibility::Level::kPublic;
965 return true;
966 }
967
968 template <typename Func>
969 bool static ParseGroupImpl(xml::XmlPullParser* parser, ParsedResource* out_resource,
970 const char* tag_name, IDiagnostics* diag, Func&& func) {
971 if (out_resource->config != ConfigDescription::DefaultConfig()) {
972 diag->Warn(DiagMessage(out_resource->source)
973 << "ignoring configuration '" << out_resource->config << "' for <" << tag_name
974 << "> tag");
975 }
976
977 std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type");
978 if (!maybe_type) {
979 diag->Error(DiagMessage(out_resource->source)
980 << "<" << tag_name << "> must have a 'type' attribute");
981 return false;
982 }
983
984 std::optional<ResourceNamedTypeRef> parsed_type = ParseResourceNamedType(maybe_type.value());
985 if (!parsed_type) {
986 diag->Error(DiagMessage(out_resource->source)
987 << "invalid resource type '" << maybe_type.value() << "' in <" << tag_name << ">");
988 return false;
989 }
990
991 std::optional<StringPiece> maybe_id_str = xml::FindNonEmptyAttribute(parser, "first-id");
992 if (!maybe_id_str) {
993 diag->Error(DiagMessage(out_resource->source)
994 << "<" << tag_name << "> must have a 'first-id' attribute");
995 return false;
996 }
997
998 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(maybe_id_str.value());
999 if (!maybe_id) {
1000 diag->Error(DiagMessage(out_resource->source)
1001 << "invalid resource ID '" << maybe_id_str.value() << "' in <" << tag_name << ">");
1002 return false;
1003 }
1004
1005 std::string comment;
1006 ResourceId next_id = maybe_id.value();
1007 bool error = false;
1008 const size_t depth = parser->depth();
1009 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
1010 if (parser->event() == xml::XmlPullParser::Event::kComment) {
1011 comment = util::TrimWhitespace(parser->comment()).to_string();
1012 continue;
1013 } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
1014 // Skip text.
1015 continue;
1016 }
1017
1018 const Source item_source = out_resource->source.WithLine(parser->line_number());
1019 const std::string& element_namespace = parser->element_namespace();
1020 const std::string& element_name = parser->element_name();
1021 if (element_namespace.empty() && element_name == "public") {
1022 auto maybe_name = xml::FindNonEmptyAttribute(parser, "name");
1023 if (!maybe_name) {
1024 diag->Error(DiagMessage(item_source) << "<public> must have a 'name' attribute");
1025 error = true;
1026 continue;
1027 }
1028
1029 if (xml::FindNonEmptyAttribute(parser, "id")) {
1030 diag->Error(DiagMessage(item_source) << "'id' is ignored within <" << tag_name << ">");
1031 error = true;
1032 continue;
1033 }
1034
1035 if (xml::FindNonEmptyAttribute(parser, "type")) {
1036 diag->Error(DiagMessage(item_source) << "'type' is ignored within <" << tag_name << ">");
1037 error = true;
1038 continue;
1039 }
1040
1041 if (maybe_name.value().substr(0, std::strlen("removed_")) == "removed_") {
1042 // Skip resources that have been removed from the framework, but leave a hole so that
1043 // other staged resources don't shift and break apps previously compiled against them
1044 next_id.id++;
1045 continue;
1046 }
1047
1048 ParsedResource& entry_res = out_resource->child_resources.emplace_back(ParsedResource{
1049 .name = ResourceName{{}, *parsed_type, maybe_name.value().to_string()},
1050 .source = item_source,
1051 .comment = std::move(comment),
1052 });
1053 comment.clear();
1054
1055 // Execute group specific code.
1056 func(entry_res, next_id);
1057
1058 next_id.id++;
1059 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1060 diag->Error(DiagMessage(item_source) << ":" << element_name << ">");
1061 error = true;
1062 }
1063 }
1064 return !error;
1065 }
1066
1067 bool ResourceParser::ParseStagingPublicGroup(xml::XmlPullParser* parser,
1068 ParsedResource* out_resource) {
1069 return ParseGroupImpl(parser, out_resource, kStagingPublicGroupTag, diag_,
1070 [](ParsedResource& parsed_entry, ResourceId id) {
1071 parsed_entry.id = id;
1072 parsed_entry.staged_api = true;
1073 parsed_entry.visibility_level = Visibility::Level::kPublic;
1074 });
1075 }
1076
1077 bool ResourceParser::ParseStagingPublicGroupFinal(xml::XmlPullParser* parser,
1078 ParsedResource* out_resource) {
1079 return ParseGroupImpl(parser, out_resource, kStagingPublicGroupFinalTag, diag_,
1080 [](ParsedResource& parsed_entry, ResourceId id) {
1081 parsed_entry.staged_alias = StagedId{id, parsed_entry.source};
1082 });
1083 }
1084
1085 bool ResourceParser::ParsePublicGroup(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1086 if (options_.visibility) {
1087 diag_->Error(DiagMessage(out_resource->source)
1088 << "<" << kPublicGroupTag << "> tag not allowed with --visibility flag");
1089 return false;
1090 }
1091
1092 return ParseGroupImpl(parser, out_resource, kPublicGroupTag, diag_,
1093 [](ParsedResource& parsed_entry, ResourceId id) {
1094 parsed_entry.id = id;
1095 parsed_entry.visibility_level = Visibility::Level::kPublic;
1096 });
1097 }
1098
1099 bool ResourceParser::ParseSymbolImpl(xml::XmlPullParser* parser,
1100 ParsedResource* out_resource) {
1101 std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type");
1102 if (!maybe_type) {
1103 diag_->Error(DiagMessage(out_resource->source)
1104 << "<" << parser->element_name()
1105 << "> must have a 'type' attribute");
1106 return false;
1107 }
1108
1109 std::optional<ResourceNamedTypeRef> parsed_type = ParseResourceNamedType(maybe_type.value());
1110 if (!parsed_type) {
1111 diag_->Error(DiagMessage(out_resource->source)
1112 << "invalid resource type '" << maybe_type.value() << "' in <"
1113 << parser->element_name() << ">");
1114 return false;
1115 }
1116
1117 out_resource->name.type = parsed_type->ToResourceNamedType();
1118 return true;
1119 }
1120
1121 bool ResourceParser::ParseSymbol(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1122 if (options_.visibility) {
1123 diag_->Error(DiagMessage(out_resource->source)
1124 << "<java-symbol> and <symbol> tags not allowed with --visibility flag");
1125 return false;
1126 }
1127 if (out_resource->config != ConfigDescription::DefaultConfig()) {
1128 diag_->Warn(DiagMessage(out_resource->source)
1129 << "ignoring configuration '" << out_resource->config << "' for <"
1130 << parser->element_name() << "> tag");
1131 }
1132
1133 if (!ParseSymbolImpl(parser, out_resource)) {
1134 return false;
1135 }
1136
1137 out_resource->visibility_level = Visibility::Level::kPrivate;
1138 return true;
1139 }
1140
1141 bool ResourceParser::ParseOverlayable(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1142 if (out_resource->config != ConfigDescription::DefaultConfig()) {
1143 diag_->Warn(DiagMessage(out_resource->source)
1144 << "ignoring configuration '" << out_resource->config
1145 << "' for <overlayable> tag");
1146 }
1147
1148 std::optional<StringPiece> overlayable_name = xml::FindNonEmptyAttribute(parser, "name");
1149 if (!overlayable_name) {
1150 diag_->Error(DiagMessage(out_resource->source)
1151 << "<overlayable> tag must have a 'name' attribute");
1152 return false;
1153 }
1154
1155 const std::string kActorUriScheme =
1156 android::base::StringPrintf("%s://", Overlayable::kActorScheme);
1157 std::optional<StringPiece> overlayable_actor = xml::FindNonEmptyAttribute(parser, "actor");
1158 if (overlayable_actor && !util::StartsWith(overlayable_actor.value(), kActorUriScheme)) {
1159 diag_->Error(DiagMessage(out_resource->source)
1160 << "specified <overlayable> tag 'actor' attribute must use the scheme '"
1161 << Overlayable::kActorScheme << "'");
1162 return false;
1163 }
1164
1165 // Create a overlayable entry grouping that represents this <overlayable>
1166 auto overlayable = std::make_shared<Overlayable>(
1167 overlayable_name.value(), (overlayable_actor) ? overlayable_actor.value() : "",
1168 source_);
1169
1170 bool error = false;
1171 std::string comment;
1172 PolicyFlags current_policies = PolicyFlags::NONE;
1173 const size_t start_depth = parser->depth();
1174 while (xml::XmlPullParser::IsGoodEvent(parser->Next())) {
1175 xml::XmlPullParser::Event event = parser->event();
1176 if (event == xml::XmlPullParser::Event::kEndElement && parser->depth() == start_depth) {
1177 // Break the loop when exiting the <overlayable>
1178 break;
1179 } else if (event == xml::XmlPullParser::Event::kEndElement
1180 && parser->depth() == start_depth + 1) {
1181 // Clear the current policies when exiting the <policy> tags
1182 current_policies = PolicyFlags::NONE;
1183 continue;
1184 } else if (event == xml::XmlPullParser::Event::kComment) {
1185 // Retrieve the comment of individual <item> tags
1186 comment = parser->comment();
1187 continue;
1188 } else if (event != xml::XmlPullParser::Event::kStartElement) {
1189 // Skip to the start of the next element
1190 continue;
1191 }
1192
1193 const Source element_source = source_.WithLine(parser->line_number());
1194 const std::string& element_name = parser->element_name();
1195 const std::string& element_namespace = parser->element_namespace();
1196 if (element_namespace.empty() && element_name == "item") {
1197 if (current_policies == PolicyFlags::NONE) {
1198 diag_->Error(DiagMessage(element_source)
1199 << "<item> within an <overlayable> must be inside a <policy> block");
1200 error = true;
1201 continue;
1202 }
1203
1204 // Items specify the name and type of resource that should be overlayable
1205 std::optional<StringPiece> item_name = xml::FindNonEmptyAttribute(parser, "name");
1206 if (!item_name) {
1207 diag_->Error(DiagMessage(element_source)
1208 << "<item> within an <overlayable> must have a 'name' attribute");
1209 error = true;
1210 continue;
1211 }
1212
1213 std::optional<StringPiece> item_type = xml::FindNonEmptyAttribute(parser, "type");
1214 if (!item_type) {
1215 diag_->Error(DiagMessage(element_source)
1216 << "<item> within an <overlayable> must have a 'type' attribute");
1217 error = true;
1218 continue;
1219 }
1220
1221 std::optional<ResourceNamedTypeRef> type = ParseResourceNamedType(item_type.value());
1222 if (!type) {
1223 diag_->Error(DiagMessage(element_source)
1224 << "invalid resource type '" << item_type.value()
1225 << "' in <item> within an <overlayable>");
1226 error = true;
1227 continue;
1228 }
1229
1230 OverlayableItem overlayable_item(overlayable);
1231 overlayable_item.policies = current_policies;
1232 overlayable_item.comment = comment;
1233 overlayable_item.source = element_source;
1234
1235 ParsedResource child_resource{};
1236 child_resource.name.type = type->ToResourceNamedType();
1237 child_resource.name.entry = item_name.value().to_string();
1238 child_resource.overlayable_item = overlayable_item;
1239 out_resource->child_resources.push_back(std::move(child_resource));
1240
1241 } else if (element_namespace.empty() && element_name == "policy") {
1242 if (current_policies != PolicyFlags::NONE) {
1243 // If the policy list is not empty, then we are currently inside a policy element
1244 diag_->Error(DiagMessage(element_source) << "<policy> blocks cannot be recursively nested");
1245 error = true;
1246 break;
1247 } else if (std::optional<StringPiece> maybe_type =
1248 xml::FindNonEmptyAttribute(parser, "type")) {
1249 // Parse the polices separated by vertical bar characters to allow for specifying multiple
1250 // policies. Items within the policy tag will have the specified policy.
1251 for (const StringPiece& part : util::Tokenize(maybe_type.value(), '|')) {
1252 StringPiece trimmed_part = util::TrimWhitespace(part);
1253 const auto policy = std::find_if(kPolicyStringToFlag.begin(),
1254 kPolicyStringToFlag.end(),
1255 [trimmed_part](const auto& it) {
1256 return trimmed_part == it.first;
1257 });
1258 if (policy == kPolicyStringToFlag.end()) {
1259 diag_->Error(DiagMessage(element_source)
1260 << "<policy> has unsupported type '" << trimmed_part << "'");
1261 error = true;
1262 continue;
1263 }
1264
1265 current_policies |= policy->second;
1266 }
1267 } else {
1268 diag_->Error(DiagMessage(element_source)
1269 << "<policy> must have a 'type' attribute");
1270 error = true;
1271 continue;
1272 }
1273 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1274 diag_->Error(DiagMessage(element_source) << "invalid element <" << element_name << "> "
1275 << " in <overlayable>");
1276 error = true;
1277 break;
1278 }
1279
1280 comment.clear();
1281 }
1282
1283 return !error;
1284 }
1285
1286 bool ResourceParser::ParseAddResource(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1287 if (ParseSymbolImpl(parser, out_resource)) {
1288 out_resource->visibility_level = Visibility::Level::kUndefined;
1289 out_resource->allow_new = true;
1290 return true;
1291 }
1292 return false;
1293 }
1294
1295 bool ResourceParser::ParseAttr(xml::XmlPullParser* parser,
1296 ParsedResource* out_resource) {
1297 return ParseAttrImpl(parser, out_resource, false);
1298 }
1299
1300 bool ResourceParser::ParseAttrImpl(xml::XmlPullParser* parser,
1301 ParsedResource* out_resource, bool weak) {
1302 out_resource->name.type =
1303 ResourceNamedTypeWithDefaultName(ResourceType::kAttr).ToResourceNamedType();
1304
1305 // Attributes only end up in default configuration.
1306 if (out_resource->config != ConfigDescription::DefaultConfig()) {
1307 diag_->Warn(DiagMessage(out_resource->source)
1308 << "ignoring configuration '" << out_resource->config
1309 << "' for attribute " << out_resource->name);
1310 out_resource->config = ConfigDescription::DefaultConfig();
1311 }
1312
1313 uint32_t type_mask = 0;
1314
1315 std::optional<StringPiece> maybe_format = xml::FindAttribute(parser, "format");
1316 if (maybe_format) {
1317 type_mask = ParseFormatAttribute(maybe_format.value());
1318 if (type_mask == 0) {
1319 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1320 << "invalid attribute format '" << maybe_format.value() << "'");
1321 return false;
1322 }
1323 }
1324
1325 std::optional<int32_t> maybe_min, maybe_max;
1326
1327 if (std::optional<StringPiece> maybe_min_str = xml::FindAttribute(parser, "min")) {
1328 StringPiece min_str = util::TrimWhitespace(maybe_min_str.value());
1329 if (!min_str.empty()) {
1330 std::u16string min_str16 = util::Utf8ToUtf16(min_str);
1331 android::Res_value value;
1332 if (android::ResTable::stringToInt(min_str16.data(), min_str16.size(), &value)) {
1333 maybe_min = static_cast<int32_t>(value.data);
1334 }
1335 }
1336
1337 if (!maybe_min) {
1338 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1339 << "invalid 'min' value '" << min_str << "'");
1340 return false;
1341 }
1342 }
1343
1344 if (std::optional<StringPiece> maybe_max_str = xml::FindAttribute(parser, "max")) {
1345 StringPiece max_str = util::TrimWhitespace(maybe_max_str.value());
1346 if (!max_str.empty()) {
1347 std::u16string max_str16 = util::Utf8ToUtf16(max_str);
1348 android::Res_value value;
1349 if (android::ResTable::stringToInt(max_str16.data(), max_str16.size(), &value)) {
1350 maybe_max = static_cast<int32_t>(value.data);
1351 }
1352 }
1353
1354 if (!maybe_max) {
1355 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1356 << "invalid 'max' value '" << max_str << "'");
1357 return false;
1358 }
1359 }
1360
1361 if ((maybe_min || maybe_max) &&
1362 (type_mask & android::ResTable_map::TYPE_INTEGER) == 0) {
1363 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1364 << "'min' and 'max' can only be used when format='integer'");
1365 return false;
1366 }
1367
1368 struct SymbolComparator {
1369 bool operator()(const Attribute::Symbol& a, const Attribute::Symbol& b) const {
1370 return a.symbol.name.value() < b.symbol.name.value();
1371 }
1372 };
1373
1374 std::set<Attribute::Symbol, SymbolComparator> items;
1375
1376 std::string comment;
1377 bool error = false;
1378 const size_t depth = parser->depth();
1379 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
1380 if (parser->event() == xml::XmlPullParser::Event::kComment) {
1381 comment = util::TrimWhitespace(parser->comment()).to_string();
1382 continue;
1383 } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
1384 // Skip text.
1385 continue;
1386 }
1387
1388 const Source item_source = source_.WithLine(parser->line_number());
1389 const std::string& element_namespace = parser->element_namespace();
1390 const std::string& element_name = parser->element_name();
1391 if (element_namespace.empty() && (element_name == "flag" || element_name == "enum")) {
1392 if (element_name == "enum") {
1393 if (type_mask & android::ResTable_map::TYPE_FLAGS) {
1394 diag_->Error(DiagMessage(item_source)
1395 << "can not define an <enum>; already defined a <flag>");
1396 error = true;
1397 continue;
1398 }
1399 type_mask |= android::ResTable_map::TYPE_ENUM;
1400
1401 } else if (element_name == "flag") {
1402 if (type_mask & android::ResTable_map::TYPE_ENUM) {
1403 diag_->Error(DiagMessage(item_source)
1404 << "can not define a <flag>; already defined an <enum>");
1405 error = true;
1406 continue;
1407 }
1408 type_mask |= android::ResTable_map::TYPE_FLAGS;
1409 }
1410
1411 if (std::optional<Attribute::Symbol> s = ParseEnumOrFlagItem(parser, element_name)) {
1412 Attribute::Symbol& symbol = s.value();
1413 ParsedResource child_resource;
1414 child_resource.name = symbol.symbol.name.value();
1415 child_resource.source = item_source;
1416 child_resource.value = util::make_unique<Id>();
1417 if (options_.visibility) {
1418 child_resource.visibility_level = options_.visibility.value();
1419 }
1420 out_resource->child_resources.push_back(std::move(child_resource));
1421
1422 symbol.symbol.SetComment(std::move(comment));
1423 symbol.symbol.SetSource(item_source);
1424
1425 auto insert_result = items.insert(std::move(symbol));
1426 if (!insert_result.second) {
1427 const Attribute::Symbol& existing_symbol = *insert_result.first;
1428 diag_->Error(DiagMessage(item_source)
1429 << "duplicate symbol '"
1430 << existing_symbol.symbol.name.value().entry << "'");
1431
1432 diag_->Note(DiagMessage(existing_symbol.symbol.GetSource())
1433 << "first defined here");
1434 error = true;
1435 }
1436 } else {
1437 error = true;
1438 }
1439 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1440 diag_->Error(DiagMessage(item_source) << ":" << element_name << ">");
1441 error = true;
1442 }
1443
1444 comment = {};
1445 }
1446
1447 if (error) {
1448 return false;
1449 }
1450
1451 std::unique_ptr<Attribute> attr = util::make_unique<Attribute>(
1452 type_mask ? type_mask : uint32_t{android::ResTable_map::TYPE_ANY});
1453 attr->SetWeak(weak);
1454 attr->symbols = std::vector<Attribute::Symbol>(items.begin(), items.end());
1455 attr->min_int = maybe_min.value_or(std::numeric_limits<int32_t>::min());
1456 attr->max_int = maybe_max.value_or(std::numeric_limits<int32_t>::max());
1457 out_resource->value = std::move(attr);
1458 return true;
1459 }
1460
1461 std::optional<Attribute::Symbol> ResourceParser::ParseEnumOrFlagItem(xml::XmlPullParser* parser,
1462 const StringPiece& tag) {
1463 const Source source = source_.WithLine(parser->line_number());
1464
1465 std::optional<StringPiece> maybe_name = xml::FindNonEmptyAttribute(parser, "name");
1466 if (!maybe_name) {
1467 diag_->Error(DiagMessage(source) << "no attribute 'name' found for tag <"
1468 << tag << ">");
1469 return {};
1470 }
1471
1472 std::optional<StringPiece> maybe_value = xml::FindNonEmptyAttribute(parser, "value");
1473 if (!maybe_value) {
1474 diag_->Error(DiagMessage(source) << "no attribute 'value' found for tag <"
1475 << tag << ">");
1476 return {};
1477 }
1478
1479 std::u16string value16 = util::Utf8ToUtf16(maybe_value.value());
1480 android::Res_value val;
1481 if (!android::ResTable::stringToInt(value16.data(), value16.size(), &val)) {
1482 diag_->Error(DiagMessage(source) << "invalid value '" << maybe_value.value()
1483 << "' for <" << tag
1484 << ">; must be an integer");
1485 return {};
1486 }
1487
1488 return Attribute::Symbol{
1489 Reference(ResourceNameRef({}, ResourceNamedTypeWithDefaultName(ResourceType::kId),
1490 maybe_name.value())),
1491 val.data, val.dataType};
1492 }
1493
1494 bool ResourceParser::ParseStyleItem(xml::XmlPullParser* parser, Style* style) {
1495 const Source source = source_.WithLine(parser->line_number());
1496
1497 std::optional<StringPiece> maybe_name = xml::FindNonEmptyAttribute(parser, "name");
1498 if (!maybe_name) {
1499 diag_->Error(DiagMessage(source) << "<item> must have a 'name' attribute");
1500 return false;
1501 }
1502
1503 std::optional<Reference> maybe_key = ResourceUtils::ParseXmlAttributeName(maybe_name.value());
1504 if (!maybe_key) {
1505 diag_->Error(DiagMessage(source) << "invalid attribute name '" << maybe_name.value() << "'");
1506 return false;
1507 }
1508
1509 ResolvePackage(parser, &maybe_key.value());
1510 maybe_key.value().SetSource(source);
1511
1512 std::unique_ptr<Item> value = ParseXml(parser, 0, kAllowRawString);
1513 if (!value) {
1514 diag_->Error(DiagMessage(source) << "could not parse style item");
1515 return false;
1516 }
1517
1518 style->entries.push_back(Style::Entry{std::move(maybe_key.value()), std::move(value)});
1519 return true;
1520 }
1521
1522 bool ResourceParser::ParseStyle(const ResourceType type, xml::XmlPullParser* parser,
1523 ParsedResource* out_resource) {
1524 out_resource->name.type = ResourceNamedTypeWithDefaultName(type).ToResourceNamedType();
1525
1526 std::unique_ptr<Style> style = util::make_unique<Style>();
1527
1528 std::optional<StringPiece> maybe_parent = xml::FindAttribute(parser, "parent");
1529 if (maybe_parent) {
1530 // If the parent is empty, we don't have a parent, but we also don't infer either.
1531 if (!maybe_parent.value().empty()) {
1532 std::string err_str;
1533 style->parent = ResourceUtils::ParseStyleParentReference(maybe_parent.value(), &err_str);
1534 if (!style->parent) {
1535 diag_->Error(DiagMessage(out_resource->source) << err_str);
1536 return false;
1537 }
1538
1539 // Transform the namespace prefix to the actual package name, and mark the reference as
1540 // private if appropriate.
1541 ResolvePackage(parser, &style->parent.value());
1542 }
1543
1544 } else {
1545 // No parent was specified, so try inferring it from the style name.
1546 std::string style_name = out_resource->name.entry;
1547 size_t pos = style_name.find_last_of(u'.');
1548 if (pos != std::string::npos) {
1549 style->parent_inferred = true;
1550 style->parent = Reference(ResourceName(
1551 {}, ResourceNamedTypeWithDefaultName(ResourceType::kStyle), style_name.substr(0, pos)));
1552 }
1553 }
1554
1555 bool error = false;
1556 const size_t depth = parser->depth();
1557 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
1558 if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
1559 // Skip text and comments.
1560 continue;
1561 }
1562
1563 const std::string& element_namespace = parser->element_namespace();
1564 const std::string& element_name = parser->element_name();
1565 if (element_namespace == "" && element_name == "item") {
1566 error |= !ParseStyleItem(parser, style.get());
1567
1568 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1569 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1570 << ":" << element_name << ">");
1571 error = true;
1572 }
1573 }
1574
1575 if (error) {
1576 return false;
1577 }
1578
1579 out_resource->value = std::move(style);
1580 return true;
1581 }
1582
1583 bool ResourceParser::ParseArray(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1584 uint32_t resource_format = android::ResTable_map::TYPE_ANY;
1585 if (std::optional<StringPiece> format_attr = xml::FindNonEmptyAttribute(parser, "format")) {
1586 resource_format = ParseFormatTypeNoEnumsOrFlags(format_attr.value());
1587 if (resource_format == 0u) {
1588 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1589 << "'" << format_attr.value() << "' is an invalid format");
1590 return false;
1591 }
1592 }
1593 return ParseArrayImpl(parser, out_resource, resource_format);
1594 }
1595
1596 bool ResourceParser::ParseIntegerArray(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1597 return ParseArrayImpl(parser, out_resource, android::ResTable_map::TYPE_INTEGER);
1598 }
1599
1600 bool ResourceParser::ParseStringArray(xml::XmlPullParser* parser, ParsedResource* out_resource) {
1601 return ParseArrayImpl(parser, out_resource, android::ResTable_map::TYPE_STRING);
1602 }
1603
1604 bool ResourceParser::ParseArrayImpl(xml::XmlPullParser* parser,
1605 ParsedResource* out_resource,
1606 const uint32_t typeMask) {
1607 out_resource->name.type =
1608 ResourceNamedTypeWithDefaultName(ResourceType::kArray).ToResourceNamedType();
1609
1610 std::unique_ptr<Array> array = util::make_unique<Array>();
1611
1612 bool translatable = options_.translatable;
1613 if (std::optional<StringPiece> translatable_attr = xml::FindAttribute(parser, "translatable")) {
1614 std::optional<bool> maybe_translatable = ResourceUtils::ParseBool(translatable_attr.value());
1615 if (!maybe_translatable) {
1616 diag_->Error(DiagMessage(out_resource->source)
1617 << "invalid value for 'translatable'. Must be a boolean");
1618 return false;
1619 }
1620 translatable = maybe_translatable.value();
1621 }
1622 array->SetTranslatable(translatable);
1623
1624 bool error = false;
1625 const size_t depth = parser->depth();
1626 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
1627 if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
1628 // Skip text and comments.
1629 continue;
1630 }
1631
1632 const Source item_source = source_.WithLine(parser->line_number());
1633 const std::string& element_namespace = parser->element_namespace();
1634 const std::string& element_name = parser->element_name();
1635 if (element_namespace.empty() && element_name == "item") {
1636 std::unique_ptr<Item> item = ParseXml(parser, typeMask, kNoRawString);
1637 if (!item) {
1638 diag_->Error(DiagMessage(item_source) << "could not parse array item");
1639 error = true;
1640 continue;
1641 }
1642 item->SetSource(item_source);
1643 array->elements.emplace_back(std::move(item));
1644
1645 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1646 diag_->Error(DiagMessage(source_.WithLine(parser->line_number()))
1647 << "unknown tag <" << element_namespace << ":"
1648 << element_name << ">");
1649 error = true;
1650 }
1651 }
1652
1653 if (error) {
1654 return false;
1655 }
1656
1657 out_resource->value = std::move(array);
1658 return true;
1659 }
1660
1661 bool ResourceParser::ParsePlural(xml::XmlPullParser* parser,
1662 ParsedResource* out_resource) {
1663 out_resource->name.type =
1664 ResourceNamedTypeWithDefaultName(ResourceType::kPlurals).ToResourceNamedType();
1665
1666 std::unique_ptr<Plural> plural = util::make_unique<Plural>();
1667
1668 bool error = false;
1669 const size_t depth = parser->depth();
1670 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
1671 if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
1672 // Skip text and comments.
1673 continue;
1674 }
1675
1676 const Source item_source = source_.WithLine(parser->line_number());
1677 const std::string& element_namespace = parser->element_namespace();
1678 const std::string& element_name = parser->element_name();
1679 if (element_namespace.empty() && element_name == "item") {
1680 std::optional<StringPiece> maybe_quantity = xml::FindNonEmptyAttribute(parser, "quantity");
1681 if (!maybe_quantity) {
1682 diag_->Error(DiagMessage(item_source)
1683 << "<item> in <plurals> requires attribute "
1684 << "'quantity'");
1685 error = true;
1686 continue;
1687 }
1688
1689 StringPiece trimmed_quantity =
1690 util::TrimWhitespace(maybe_quantity.value());
1691 size_t index = 0;
1692 if (trimmed_quantity == "zero") {
1693 index = Plural::Zero;
1694 } else if (trimmed_quantity == "one") {
1695 index = Plural::One;
1696 } else if (trimmed_quantity == "two") {
1697 index = Plural::Two;
1698 } else if (trimmed_quantity == "few") {
1699 index = Plural::Few;
1700 } else if (trimmed_quantity == "many") {
1701 index = Plural::Many;
1702 } else if (trimmed_quantity == "other") {
1703 index = Plural::Other;
1704 } else {
1705 diag_->Error(DiagMessage(item_source)
1706 << "<item> in <plural> has invalid value '"
1707 << trimmed_quantity << "' for attribute 'quantity'");
1708 error = true;
1709 continue;
1710 }
1711
1712 if (plural->values[index]) {
1713 diag_->Error(DiagMessage(item_source) << "duplicate quantity '"
1714 << trimmed_quantity << "'");
1715 error = true;
1716 continue;
1717 }
1718
1719 if (!(plural->values[index] = ParseXml(
1720 parser, android::ResTable_map::TYPE_STRING, kNoRawString))) {
1721 error = true;
1722 continue;
1723 }
1724
1725 plural->values[index]->SetSource(item_source);
1726
1727 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1728 diag_->Error(DiagMessage(item_source) << "unknown tag <"
1729 << element_namespace << ":"
1730 << element_name << ">");
1731 error = true;
1732 }
1733 }
1734
1735 if (error) {
1736 return false;
1737 }
1738
1739 out_resource->value = std::move(plural);
1740 return true;
1741 }
1742
1743 bool ResourceParser::ParseDeclareStyleable(xml::XmlPullParser* parser,
1744 ParsedResource* out_resource) {
1745 out_resource->name.type =
1746 ResourceNamedTypeWithDefaultName(ResourceType::kStyleable).ToResourceNamedType();
1747
1748 if (!options_.preserve_visibility_of_styleables) {
1749 // This was added in change Idd21b5de4d20be06c6f8c8eb5a22ccd68afc4927 to mimic aapt1, but no one
1750 // knows exactly what for.
1751 //
1752 // FWIW, styleables only appear in generated R classes. For custom views these should always be
1753 // package-private (to be used only by the view class); themes are a different story.
1754 out_resource->visibility_level = Visibility::Level::kPublic;
1755 }
1756
1757 // Declare-styleable only ends up in default config;
1758 if (out_resource->config != ConfigDescription::DefaultConfig()) {
1759 diag_->Warn(DiagMessage(out_resource->source)
1760 << "ignoring configuration '" << out_resource->config
1761 << "' for styleable " << out_resource->name.entry);
1762 out_resource->config = ConfigDescription::DefaultConfig();
1763 }
1764
1765 std::unique_ptr<Styleable> styleable = util::make_unique<Styleable>();
1766
1767 std::string comment;
1768 bool error = false;
1769 const size_t depth = parser->depth();
1770 while (xml::XmlPullParser::NextChildNode(parser, depth)) {
1771 if (parser->event() == xml::XmlPullParser::Event::kComment) {
1772 comment = util::TrimWhitespace(parser->comment()).to_string();
1773 continue;
1774 } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) {
1775 // Ignore text.
1776 continue;
1777 }
1778
1779 const Source item_source = source_.WithLine(parser->line_number());
1780 const std::string& element_namespace = parser->element_namespace();
1781 const std::string& element_name = parser->element_name();
1782 if (element_namespace.empty() && element_name == "attr") {
1783 std::optional<StringPiece> maybe_name = xml::FindNonEmptyAttribute(parser, "name");
1784 if (!maybe_name) {
1785 diag_->Error(DiagMessage(item_source) << "<attr> tag must have a 'name' attribute");
1786 error = true;
1787 continue;
1788 }
1789
1790 // If this is a declaration, the package name may be in the name. Separate
1791 // these out.
1792 // Eg. <attr name="android:text" />
1793 std::optional<Reference> maybe_ref = ResourceUtils::ParseXmlAttributeName(maybe_name.value());
1794 if (!maybe_ref) {
1795 diag_->Error(DiagMessage(item_source) << "<attr> tag has invalid name '"
1796 << maybe_name.value() << "'");
1797 error = true;
1798 continue;
1799 }
1800
1801 Reference& child_ref = maybe_ref.value();
1802 xml::ResolvePackage(parser, &child_ref);
1803
1804 // Create the ParsedResource that will add the attribute to the table.
1805 ParsedResource child_resource;
1806 child_resource.name = child_ref.name.value();
1807 child_resource.source = item_source;
1808 child_resource.comment = std::move(comment);
1809 comment.clear();
1810 if (options_.visibility) {
1811 child_resource.visibility_level = options_.visibility.value();
1812 }
1813
1814 if (!ParseAttrImpl(parser, &child_resource, true)) {
1815 error = true;
1816 continue;
1817 }
1818
1819 // Create the reference to this attribute.
1820 child_ref.SetComment(child_resource.comment);
1821 child_ref.SetSource(item_source);
1822 styleable->entries.push_back(std::move(child_ref));
1823
1824 // Do not add referenced attributes that do not define a format to the table.
1825 CHECK(child_resource.value != nullptr);
1826 Attribute* attr = ValueCast<Attribute>(child_resource.value.get());
1827
1828 CHECK(attr != nullptr);
1829 if (attr->type_mask != android::ResTable_map::TYPE_ANY) {
1830 out_resource->child_resources.push_back(std::move(child_resource));
1831 }
1832
1833 } else if (!ShouldIgnoreElement(element_namespace, element_name)) {
1834 diag_->Error(DiagMessage(item_source) << "unknown tag <"
1835 << element_namespace << ":"
1836 << element_name << ">");
1837 error = true;
1838 }
1839
1840 comment = {};
1841 }
1842
1843 if (error) {
1844 return false;
1845 }
1846
1847 out_resource->value = std::move(styleable);
1848 return true;
1849 }
1850
1851 } // namespace aapt