blob: d27b62fd99fb26e2e8bcfeaadf8b7a2525bc1f5a [file] [log] [blame]
Adam Lesinski75f3a552015-06-03 14:54:23 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinski75f3a552015-06-03 14:54:23 -070017#include "XmlDom.h"
18#include "XmlPullParser.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080019#include "util/Util.h"
Adam Lesinski75f3a552015-06-03 14:54:23 -070020
21#include <cassert>
Adam Lesinski467f1712015-11-16 17:35:44 -080022#include <expat.h>
Adam Lesinski75f3a552015-06-03 14:54:23 -070023#include <memory>
24#include <stack>
25#include <string>
26#include <tuple>
27
28namespace aapt {
29namespace xml {
30
31constexpr char kXmlNamespaceSep = 1;
32
33struct Stack {
34 std::unique_ptr<xml::Node> root;
35 std::stack<xml::Node*> nodeStack;
36 std::u16string pendingComment;
37};
38
39/**
40 * Extracts the namespace and name of an expanded element or attribute name.
41 */
42static void splitName(const char* name, std::u16string* outNs, std::u16string* outName) {
43 const char* p = name;
44 while (*p != 0 && *p != kXmlNamespaceSep) {
45 p++;
46 }
47
48 if (*p == 0) {
49 outNs->clear();
50 *outName = util::utf8ToUtf16(name);
51 } else {
52 *outNs = util::utf8ToUtf16(StringPiece(name, (p - name)));
53 *outName = util::utf8ToUtf16(p + 1);
54 }
55}
56
57static void addToStack(Stack* stack, XML_Parser parser, std::unique_ptr<Node> node) {
58 node->lineNumber = XML_GetCurrentLineNumber(parser);
59 node->columnNumber = XML_GetCurrentColumnNumber(parser);
60
61 Node* thisNode = node.get();
62 if (!stack->nodeStack.empty()) {
63 stack->nodeStack.top()->addChild(std::move(node));
64 } else {
65 stack->root = std::move(node);
66 }
67
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068 if (!nodeCast<Text>(thisNode)) {
Adam Lesinski75f3a552015-06-03 14:54:23 -070069 stack->nodeStack.push(thisNode);
70 }
71}
72
73static void XMLCALL startNamespaceHandler(void* userData, const char* prefix, const char* uri) {
74 XML_Parser parser = reinterpret_cast<XML_Parser>(userData);
75 Stack* stack = reinterpret_cast<Stack*>(XML_GetUserData(parser));
76
77 std::unique_ptr<Namespace> ns = util::make_unique<Namespace>();
78 if (prefix) {
79 ns->namespacePrefix = util::utf8ToUtf16(prefix);
80 }
81
82 if (uri) {
83 ns->namespaceUri = util::utf8ToUtf16(uri);
84 }
85
86 addToStack(stack, parser, std::move(ns));
87}
88
89static void XMLCALL endNamespaceHandler(void* userData, const char* prefix) {
90 XML_Parser parser = reinterpret_cast<XML_Parser>(userData);
91 Stack* stack = reinterpret_cast<Stack*>(XML_GetUserData(parser));
92
93 assert(!stack->nodeStack.empty());
94 stack->nodeStack.pop();
95}
96
97static bool lessAttribute(const Attribute& lhs, const Attribute& rhs) {
98 return std::tie(lhs.namespaceUri, lhs.name, lhs.value) <
99 std::tie(rhs.namespaceUri, rhs.name, rhs.value);
100}
101
102static void XMLCALL startElementHandler(void* userData, const char* name, const char** attrs) {
103 XML_Parser parser = reinterpret_cast<XML_Parser>(userData);
104 Stack* stack = reinterpret_cast<Stack*>(XML_GetUserData(parser));
105
106 std::unique_ptr<Element> el = util::make_unique<Element>();
107 splitName(name, &el->namespaceUri, &el->name);
108
109 while (*attrs) {
110 Attribute attribute;
111 splitName(*attrs++, &attribute.namespaceUri, &attribute.name);
112 attribute.value = util::utf8ToUtf16(*attrs++);
113
114 // Insert in sorted order.
115 auto iter = std::lower_bound(el->attributes.begin(), el->attributes.end(), attribute,
116 lessAttribute);
117 el->attributes.insert(iter, std::move(attribute));
118 }
119
120 el->comment = std::move(stack->pendingComment);
121 addToStack(stack, parser, std::move(el));
122}
123
124static void XMLCALL endElementHandler(void* userData, const char* name) {
125 XML_Parser parser = reinterpret_cast<XML_Parser>(userData);
126 Stack* stack = reinterpret_cast<Stack*>(XML_GetUserData(parser));
127
128 assert(!stack->nodeStack.empty());
Adam Lesinskica5638f2015-10-21 14:42:43 -0700129 //stack->nodeStack.top()->comment = std::move(stack->pendingComment);
Adam Lesinski75f3a552015-06-03 14:54:23 -0700130 stack->nodeStack.pop();
131}
132
133static void XMLCALL characterDataHandler(void* userData, const char* s, int len) {
134 XML_Parser parser = reinterpret_cast<XML_Parser>(userData);
135 Stack* stack = reinterpret_cast<Stack*>(XML_GetUserData(parser));
136
137 if (!s || len <= 0) {
138 return;
139 }
140
141 // See if we can just append the text to a previous text node.
142 if (!stack->nodeStack.empty()) {
143 Node* currentParent = stack->nodeStack.top();
144 if (!currentParent->children.empty()) {
145 Node* lastChild = currentParent->children.back().get();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700146 if (Text* text = nodeCast<Text>(lastChild)) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700147 text->text += util::utf8ToUtf16(StringPiece(s, len));
148 return;
149 }
150 }
151 }
152
153 std::unique_ptr<Text> text = util::make_unique<Text>();
154 text->text = util::utf8ToUtf16(StringPiece(s, len));
155 addToStack(stack, parser, std::move(text));
156}
157
158static void XMLCALL commentDataHandler(void* userData, const char* comment) {
159 XML_Parser parser = reinterpret_cast<XML_Parser>(userData);
160 Stack* stack = reinterpret_cast<Stack*>(XML_GetUserData(parser));
161
162 if (!stack->pendingComment.empty()) {
163 stack->pendingComment += '\n';
164 }
165 stack->pendingComment += util::utf8ToUtf16(comment);
166}
167
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700168std::unique_ptr<XmlResource> inflate(std::istream* in, IDiagnostics* diag, const Source& source) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700169 Stack stack;
170
171 XML_Parser parser = XML_ParserCreateNS(nullptr, kXmlNamespaceSep);
172 XML_SetUserData(parser, &stack);
173 XML_UseParserAsHandlerArg(parser);
174 XML_SetElementHandler(parser, startElementHandler, endElementHandler);
175 XML_SetNamespaceDeclHandler(parser, startNamespaceHandler, endNamespaceHandler);
176 XML_SetCharacterDataHandler(parser, characterDataHandler);
177 XML_SetCommentHandler(parser, commentDataHandler);
178
179 char buffer[1024];
180 while (!in->eof()) {
181 in->read(buffer, sizeof(buffer) / sizeof(buffer[0]));
182 if (in->bad() && !in->eof()) {
183 stack.root = {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700184 diag->error(DiagMessage(source) << strerror(errno));
Adam Lesinski75f3a552015-06-03 14:54:23 -0700185 break;
186 }
187
188 if (XML_Parse(parser, buffer, in->gcount(), in->eof()) == XML_STATUS_ERROR) {
189 stack.root = {};
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700190 diag->error(DiagMessage(source.withLine(XML_GetCurrentLineNumber(parser)))
191 << XML_ErrorString(XML_GetErrorCode(parser)));
Adam Lesinski75f3a552015-06-03 14:54:23 -0700192 break;
193 }
194 }
195
196 XML_ParserFree(parser);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700197 if (stack.root) {
Adam Lesinskica5638f2015-10-21 14:42:43 -0700198 return util::make_unique<XmlResource>(ResourceFile{ {}, {}, source }, std::move(stack.root));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700199 }
200 return {};
Adam Lesinski75f3a552015-06-03 14:54:23 -0700201}
202
203static void copyAttributes(Element* el, android::ResXMLParser* parser) {
204 const size_t attrCount = parser->getAttributeCount();
205 if (attrCount > 0) {
206 el->attributes.reserve(attrCount);
207 for (size_t i = 0; i < attrCount; i++) {
208 Attribute attr;
209 size_t len;
210 const char16_t* str16 = parser->getAttributeNamespace(i, &len);
211 if (str16) {
212 attr.namespaceUri.assign(str16, len);
213 }
214
215 str16 = parser->getAttributeName(i, &len);
216 if (str16) {
217 attr.name.assign(str16, len);
218 }
219
220 str16 = parser->getAttributeStringValue(i, &len);
221 if (str16) {
222 attr.value.assign(str16, len);
223 }
224 el->attributes.push_back(std::move(attr));
225 }
226 }
227}
228
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700229std::unique_ptr<XmlResource> inflate(const void* data, size_t dataLen, IDiagnostics* diag,
230 const Source& source) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700231 std::unique_ptr<Node> root;
232 std::stack<Node*> nodeStack;
233
234 android::ResXMLTree tree;
235 if (tree.setTo(data, dataLen) != android::NO_ERROR) {
236 return {};
237 }
238
239 android::ResXMLParser::event_code_t code;
240 while ((code = tree.next()) != android::ResXMLParser::BAD_DOCUMENT &&
241 code != android::ResXMLParser::END_DOCUMENT) {
242 std::unique_ptr<Node> newNode;
243 switch (code) {
244 case android::ResXMLParser::START_NAMESPACE: {
245 std::unique_ptr<Namespace> node = util::make_unique<Namespace>();
246 size_t len;
247 const char16_t* str16 = tree.getNamespacePrefix(&len);
248 if (str16) {
249 node->namespacePrefix.assign(str16, len);
250 }
251
252 str16 = tree.getNamespaceUri(&len);
253 if (str16) {
254 node->namespaceUri.assign(str16, len);
255 }
256 newNode = std::move(node);
257 break;
258 }
259
260 case android::ResXMLParser::START_TAG: {
261 std::unique_ptr<Element> node = util::make_unique<Element>();
262 size_t len;
263 const char16_t* str16 = tree.getElementNamespace(&len);
264 if (str16) {
265 node->namespaceUri.assign(str16, len);
266 }
267
268 str16 = tree.getElementName(&len);
269 if (str16) {
270 node->name.assign(str16, len);
271 }
272
273 copyAttributes(node.get(), &tree);
274
275 newNode = std::move(node);
276 break;
277 }
278
279 case android::ResXMLParser::TEXT: {
280 std::unique_ptr<Text> node = util::make_unique<Text>();
281 size_t len;
282 const char16_t* str16 = tree.getText(&len);
283 if (str16) {
284 node->text.assign(str16, len);
285 }
286 newNode = std::move(node);
287 break;
288 }
289
290 case android::ResXMLParser::END_NAMESPACE:
291 case android::ResXMLParser::END_TAG:
292 assert(!nodeStack.empty());
293 nodeStack.pop();
294 break;
295
296 default:
297 assert(false);
298 break;
299 }
300
301 if (newNode) {
302 newNode->lineNumber = tree.getLineNumber();
303
304 Node* thisNode = newNode.get();
305 if (!root) {
306 assert(nodeStack.empty());
307 root = std::move(newNode);
308 } else {
309 assert(!nodeStack.empty());
310 nodeStack.top()->addChild(std::move(newNode));
311 }
312
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700313 if (!nodeCast<Text>(thisNode)) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700314 nodeStack.push(thisNode);
315 }
316 }
317 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700318 return util::make_unique<XmlResource>(ResourceFile{}, std::move(root));
Adam Lesinski75f3a552015-06-03 14:54:23 -0700319}
320
Adam Lesinski467f1712015-11-16 17:35:44 -0800321Element* findRootElement(XmlResource* doc) {
322 return findRootElement(doc->root.get());
323}
324
Adam Lesinskica5638f2015-10-21 14:42:43 -0700325Element* findRootElement(Node* node) {
326 if (!node) {
327 return nullptr;
328 }
329
330 Element* el = nullptr;
331 while ((el = nodeCast<Element>(node)) == nullptr) {
332 if (node->children.empty()) {
333 return nullptr;
334 }
335 // We are looking for the first element, and namespaces can only have one child.
336 node = node->children.front().get();
337 }
338 return el;
339}
340
Adam Lesinski75f3a552015-06-03 14:54:23 -0700341void Node::addChild(std::unique_ptr<Node> child) {
342 child->parent = this;
343 children.push_back(std::move(child));
344}
345
Adam Lesinski75f3a552015-06-03 14:54:23 -0700346Attribute* Element::findAttribute(const StringPiece16& ns, const StringPiece16& name) {
347 for (auto& attr : attributes) {
348 if (ns == attr.namespaceUri && name == attr.name) {
349 return &attr;
350 }
351 }
352 return nullptr;
353}
354
355Element* Element::findChild(const StringPiece16& ns, const StringPiece16& name) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700356 return findChildWithAttribute(ns, name, {}, {}, {});
Adam Lesinski75f3a552015-06-03 14:54:23 -0700357}
358
359Element* Element::findChildWithAttribute(const StringPiece16& ns, const StringPiece16& name,
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700360 const StringPiece16& attrNs, const StringPiece16& attrName,
361 const StringPiece16& attrValue) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700362 for (auto& childNode : children) {
363 Node* child = childNode.get();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700364 while (nodeCast<Namespace>(child)) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700365 if (child->children.empty()) {
366 break;
367 }
368 child = child->children[0].get();
369 }
370
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700371 if (Element* el = nodeCast<Element>(child)) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700372 if (ns == el->namespaceUri && name == el->name) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700373 if (attrNs.empty() && attrName.empty()) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700374 return el;
375 }
376
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700377 Attribute* attr = el->findAttribute(attrNs, attrName);
378 if (attr && attrValue == attr->value) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700379 return el;
380 }
381 }
382 }
383 }
384 return nullptr;
385}
386
387std::vector<Element*> Element::getChildElements() {
388 std::vector<Element*> elements;
389 for (auto& childNode : children) {
390 Node* child = childNode.get();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700391 while (nodeCast<Namespace>(child)) {
Adam Lesinski75f3a552015-06-03 14:54:23 -0700392 if (child->children.empty()) {
393 break;
394 }
395 child = child->children[0].get();
396 }
397
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700398 if (Element* el = nodeCast<Element>(child)) {
399 elements.push_back(el);
Adam Lesinski75f3a552015-06-03 14:54:23 -0700400 }
401 }
402 return elements;
403}
404
Adam Lesinski467f1712015-11-16 17:35:44 -0800405void PackageAwareVisitor::visit(Namespace* ns) {
406 bool added = false;
407 if (Maybe<ExtractedPackage> maybePackage = extractPackageFromNamespace(ns->namespaceUri)) {
408 ExtractedPackage& package = maybePackage.value();
409 mPackageDecls.push_back(PackageDecl{ ns->namespacePrefix, std::move(package) });
410 added = true;
411 }
412
413 Visitor::visit(ns);
414
415 if (added) {
416 mPackageDecls.pop_back();
417 }
418}
419
420Maybe<ExtractedPackage> PackageAwareVisitor::transformPackageAlias(
421 const StringPiece16& alias, const StringPiece16& localPackage) const {
422 if (alias.empty()) {
423 return ExtractedPackage{ localPackage.toString(), false /* private */ };
424 }
425
426 const auto rend = mPackageDecls.rend();
427 for (auto iter = mPackageDecls.rbegin(); iter != rend; ++iter) {
428 if (alias == iter->prefix) {
429 if (iter->package.package.empty()) {
430 return ExtractedPackage{ localPackage.toString(),
431 iter->package.privateNamespace };
432 }
433 return iter->package;
434 }
435 }
436 return {};
437}
438
Adam Lesinski75f3a552015-06-03 14:54:23 -0700439} // namespace xml
440} // namespace aapt