1 /*
2  * Copyright (C) 2016 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 "link/Linkers.h"
18 
19 #include <algorithm>
20 
21 #include "ResourceTable.h"
22 
23 namespace aapt {
24 
25 namespace {
26 
27 /**
28  * Visits each xml Node, removing URI references and nested namespaces.
29  */
30 class XmlVisitor : public xml::Visitor {
31  public:
XmlVisitor(bool keep_uris)32   explicit XmlVisitor(bool keep_uris) : keep_uris_(keep_uris) {}
33 
Visit(xml::Element * el)34   void Visit(xml::Element* el) override {
35     // Strip namespaces
36     for (auto& child : el->children) {
37       while (child && xml::NodeCast<xml::Namespace>(child.get())) {
38         if (child->children.empty()) {
39           child = {};
40         } else {
41           child = std::move(child->children.front());
42           child->parent = el;
43         }
44       }
45     }
46     el->children.erase(
47         std::remove_if(el->children.begin(), el->children.end(),
48                        [](const std::unique_ptr<xml::Node>& child) -> bool {
49                          return child == nullptr;
50                        }),
51         el->children.end());
52 
53     if (!keep_uris_) {
54       for (xml::Attribute& attr : el->attributes) {
55         attr.namespace_uri = std::string();
56       }
57       el->namespace_uri = std::string();
58     }
59     xml::Visitor::Visit(el);
60   }
61 
62  private:
63   DISALLOW_COPY_AND_ASSIGN(XmlVisitor);
64 
65   bool keep_uris_;
66 };
67 
68 }  // namespace
69 
Consume(IAaptContext * context,xml::XmlResource * resource)70 bool XmlNamespaceRemover::Consume(IAaptContext* context,
71                                   xml::XmlResource* resource) {
72   if (!resource->root) {
73     return false;
74   }
75   // Replace any root namespaces until the root is a non-namespace node
76   while (xml::NodeCast<xml::Namespace>(resource->root.get())) {
77     if (resource->root->children.empty()) {
78       break;
79     }
80     resource->root = std::move(resource->root->children.front());
81     resource->root->parent = nullptr;
82   }
83   XmlVisitor visitor(keep_uris_);
84   resource->root->Accept(&visitor);
85   return true;
86 }
87 
88 }  // namespace aapt
89