xref: /aosp_15_r20/frameworks/base/tools/aapt2/xml/XmlPullParser.h (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
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 #ifndef AAPT_XML_PULL_PARSER_H
18 #define AAPT_XML_PULL_PARSER_H
19 
20 #include <expat.h>
21 
22 #include <optional>
23 #include <ostream>
24 #include <queue>
25 #include <stack>
26 #include <string>
27 #include <vector>
28 
29 #include "Resource.h"
30 #include "android-base/macros.h"
31 #include "androidfw/Streams.h"
32 #include "androidfw/StringPiece.h"
33 #include "process/IResourceTableConsumer.h"
34 #include "xml/XmlUtil.h"
35 
36 namespace aapt {
37 namespace xml {
38 
39 class XmlPullParser : public IPackageDeclStack {
40  public:
41   enum class Event {
42     kBadDocument,
43     kStartDocument,
44     kEndDocument,
45 
46     kStartNamespace,
47     kEndNamespace,
48     kStartElement,
49     kEndElement,
50     kText,
51     kComment,
52     kCdataStart,
53     kCdataEnd,
54   };
55 
56   /**
57    * Skips to the next direct descendant node of the given start_depth,
58    * skipping namespace nodes.
59    *
60    * When NextChildNode() returns true, you can expect Comments, Text, and
61    * StartElement events.
62    */
63   static bool NextChildNode(XmlPullParser* parser, size_t start_depth);
64   static bool SkipCurrentElement(XmlPullParser* parser);
65   static bool IsGoodEvent(Event event);
66 
67   explicit XmlPullParser(android::InputStream* in);
68   ~XmlPullParser();
69 
70   /**
71    * Returns the current event that is being processed.
72    */
73   Event event() const;
74 
75   const std::string& error() const;
76 
77   /**
78    * Note, unlike XmlPullParser, the first call to next() will return
79    * StartElement of the first element.
80    */
81   Event Next();
82 
83   //
84   // These are available for all nodes.
85   //
86 
87   const std::string& comment() const;
88   size_t line_number() const;
89   size_t depth() const;
90 
91   /**
92    * Returns the character data for a Text event.
93    */
94   const std::string& text() const;
95 
96   //
97   // Namespace prefix and URI are available for StartNamespace and EndNamespace.
98   //
99 
100   const std::string& namespace_prefix() const;
101   const std::string& namespace_uri() const;
102 
103   //
104   // These are available for StartElement and EndElement.
105   //
106 
107   const std::string& element_namespace() const;
108   const std::string& element_name() const;
109 
110   /*
111    * Uses the current stack of namespaces to resolve the package. Eg:
112    * xmlns:app = "http://schemas.android.com/apk/res/com.android.app"
113    * ...
114    * android:text="@app:string/message"
115    *
116    * In this case, 'app' will be converted to 'com.android.app'.
117    *
118    * If xmlns:app="http://schemas.android.com/apk/res-auto", then
119    * 'package' will be set to 'defaultPackage'.
120    */
121   std::optional<ExtractedPackage> TransformPackageAlias(android::StringPiece alias) const override;
122 
123   struct PackageDecl {
124     std::string prefix;
125     ExtractedPackage package;
126   };
127 
128   const std::vector<PackageDecl>& package_decls() const;
129 
130   //
131   // Remaining methods are for retrieving information about attributes
132   // associated with a StartElement.
133   //
134   // Attributes must be in sorted order (according to the less than operator
135   // of struct Attribute).
136   //
137 
138   struct Attribute {
139     std::string namespace_uri;
140     std::string name;
141     std::string value;
142 
143     int compare(const Attribute& rhs) const;
144     bool operator<(const Attribute& rhs) const;
145     bool operator==(const Attribute& rhs) const;
146     bool operator!=(const Attribute& rhs) const;
147   };
148 
149   using const_iterator = std::vector<Attribute>::const_iterator;
150 
151   const_iterator begin_attributes() const;
152   const_iterator end_attributes() const;
153   size_t attribute_count() const;
154   const_iterator FindAttribute(android::StringPiece namespace_uri, android::StringPiece name) const;
155 
156  private:
157   DISALLOW_COPY_AND_ASSIGN(XmlPullParser);
158 
159   static void XMLCALL StartNamespaceHandler(void* user_data, const char* prefix,
160                                             const char* uri);
161   static void XMLCALL StartElementHandler(void* user_data, const char* name,
162                                           const char** attrs);
163   static void XMLCALL CharacterDataHandler(void* user_data, const char* s,
164                                            int len);
165   static void XMLCALL EndElementHandler(void* user_data, const char* name);
166   static void XMLCALL EndNamespaceHandler(void* user_data, const char* prefix);
167   static void XMLCALL CommentDataHandler(void* user_data, const char* comment);
168   static void XMLCALL StartCdataSectionHandler(void* user_data);
169   static void XMLCALL EndCdataSectionHandler(void* user_data);
170 
171   struct EventData {
172     Event event;
173     size_t line_number;
174     size_t depth;
175     std::string data1;
176     std::string data2;
177     std::vector<Attribute> attributes;
178   };
179 
180   android::InputStream* in_;
181   XML_Parser parser_;
182   std::queue<EventData> event_queue_;
183   std::string error_;
184   const std::string empty_;
185   size_t depth_;
186   std::stack<std::string> namespace_uris_;
187   std::vector<PackageDecl> package_aliases_;
188 };
189 
190 /**
191  * Finds the attribute in the current element within the global namespace.
192  */
193 std::optional<android::StringPiece> FindAttribute(const XmlPullParser* parser,
194                                                   android::StringPiece name);
195 
196 /**
197  * Finds the attribute in the current element within the given namespace.
198  */
199 std::optional<android::StringPiece> FindAttribute(const XmlPullParser* parser,
200                                                   android::StringPiece namespace_uri,
201                                                   android::StringPiece name);
202 
203 /**
204  * Finds the attribute in the current element within the global namespace. The
205  * attribute's value
206  * must not be the empty string.
207  */
208 std::optional<android::StringPiece> FindNonEmptyAttribute(const XmlPullParser* parser,
209                                                           android::StringPiece name);
210 
211 //
212 // Implementation
213 //
214 
215 inline ::std::ostream& operator<<(::std::ostream& out,
216                                   XmlPullParser::Event event) {
217   switch (event) {
218     case XmlPullParser::Event::kBadDocument:
219       return out << "BadDocument";
220     case XmlPullParser::Event::kStartDocument:
221       return out << "StartDocument";
222     case XmlPullParser::Event::kEndDocument:
223       return out << "EndDocument";
224     case XmlPullParser::Event::kStartNamespace:
225       return out << "StartNamespace";
226     case XmlPullParser::Event::kEndNamespace:
227       return out << "EndNamespace";
228     case XmlPullParser::Event::kStartElement:
229       return out << "StartElement";
230     case XmlPullParser::Event::kEndElement:
231       return out << "EndElement";
232     case XmlPullParser::Event::kText:
233       return out << "Text";
234     case XmlPullParser::Event::kComment:
235       return out << "Comment";
236     case XmlPullParser::Event::kCdataStart:
237       return out << "CdataStart";
238     case XmlPullParser::Event::kCdataEnd:
239       return out << "CdataEnd";
240   }
241   return out;
242 }
243 
NextChildNode(XmlPullParser * parser,size_t start_depth)244 inline bool XmlPullParser::NextChildNode(XmlPullParser* parser, size_t start_depth) {
245   Event event;
246 
247   // First get back to the start depth.
248   while (IsGoodEvent(event = parser->Next()) && parser->depth() > start_depth + 1) {
249   }
250 
251   // Now look for the first good node.
252   while ((event != Event::kEndElement || parser->depth() > start_depth) && IsGoodEvent(event)) {
253     switch (event) {
254       case Event::kText:
255       case Event::kComment:
256       case Event::kStartElement:
257       case Event::kCdataStart:
258       case Event::kCdataEnd:
259         return true;
260       default:
261         break;
262     }
263     event = parser->Next();
264   }
265   return false;
266 }
267 
SkipCurrentElement(XmlPullParser * parser)268 inline bool XmlPullParser::SkipCurrentElement(XmlPullParser* parser) {
269   int depth = 1;
270   while (depth > 0) {
271     switch (parser->Next()) {
272       case Event::kEndDocument:
273         return true;
274       case Event::kBadDocument:
275         return false;
276       case Event::kStartElement:
277         depth++;
278         break;
279       case Event::kEndElement:
280         depth--;
281         break;
282       default:
283         break;
284     }
285   }
286   return true;
287 }
288 
IsGoodEvent(XmlPullParser::Event event)289 inline bool XmlPullParser::IsGoodEvent(XmlPullParser::Event event) {
290   return event != Event::kBadDocument && event != Event::kEndDocument;
291 }
292 
compare(const Attribute & rhs)293 inline int XmlPullParser::Attribute::compare(const Attribute& rhs) const {
294   int cmp = namespace_uri.compare(rhs.namespace_uri);
295   if (cmp != 0) return cmp;
296   return name.compare(rhs.name);
297 }
298 
299 inline bool XmlPullParser::Attribute::operator<(const Attribute& rhs) const {
300   return compare(rhs) < 0;
301 }
302 
303 inline bool XmlPullParser::Attribute::operator==(const Attribute& rhs) const {
304   return compare(rhs) == 0;
305 }
306 
307 inline bool XmlPullParser::Attribute::operator!=(const Attribute& rhs) const {
308   return compare(rhs) != 0;
309 }
310 
311 }  // namespace xml
312 }  // namespace aapt
313 
314 #endif  // AAPT_XML_PULL_PARSER_H
315