blob: cc457890ff6f22b5657ed32427b3d240341589b1 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -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
17#include "SdkConstants.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070018#include "flatten/ChunkWriter.h"
19#include "flatten/ResourceTypeExtensions.h"
20#include "flatten/XmlFlattener.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080021#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070022
23#include <androidfw/ResourceTypes.h>
Adam Lesinski803c7c82016-04-06 16:09:43 -070024#include <algorithm>
Adam Lesinski32852a52016-06-15 10:56:41 -070025#include <map>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070026#include <utils/misc.h>
Adam Lesinski467f1712015-11-16 17:35:44 -080027#include <vector>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070028
29using namespace android;
30
31namespace aapt {
32
33namespace {
34
35constexpr uint32_t kLowPriority = 0xffffffffu;
36
37struct XmlFlattenerVisitor : public xml::Visitor {
38 using xml::Visitor::visit;
39
40 BigBuffer* mBuffer;
41 XmlFlattenerOptions mOptions;
42 StringPool mPool;
43 std::map<uint8_t, StringPool> mPackagePools;
44
45 struct StringFlattenDest {
46 StringPool::Ref ref;
47 ResStringPool_ref* dest;
48 };
49 std::vector<StringFlattenDest> mStringRefs;
50
51 // Scratch vector to filter attributes. We avoid allocations
52 // making this a member.
53 std::vector<xml::Attribute*> mFilteredAttrs;
54
55
56 XmlFlattenerVisitor(BigBuffer* buffer, XmlFlattenerOptions options) :
57 mBuffer(buffer), mOptions(options) {
58 }
59
60 void addString(const StringPiece16& str, uint32_t priority, android::ResStringPool_ref* dest) {
61 if (!str.empty()) {
62 mStringRefs.push_back(StringFlattenDest{
63 mPool.makeRef(str, StringPool::Context{ priority }),
64 dest });
65 } else {
66 // The device doesn't think a string of size 0 is the same as null.
67 dest->index = util::deviceToHost32(-1);
68 }
69 }
70
71 void addString(const StringPool::Ref& ref, android::ResStringPool_ref* dest) {
72 mStringRefs.push_back(StringFlattenDest{ ref, dest });
73 }
74
75 void writeNamespace(xml::Namespace* node, uint16_t type) {
76 ChunkWriter writer(mBuffer);
77
78 ResXMLTree_node* flatNode = writer.startChunk<ResXMLTree_node>(type);
79 flatNode->lineNumber = util::hostToDevice32(node->lineNumber);
80 flatNode->comment.index = util::hostToDevice32(-1);
81
82 ResXMLTree_namespaceExt* flatNs = writer.nextBlock<ResXMLTree_namespaceExt>();
83 addString(node->namespacePrefix, kLowPriority, &flatNs->prefix);
84 addString(node->namespaceUri, kLowPriority, &flatNs->uri);
85
86 writer.finish();
87 }
88
89 void visit(xml::Namespace* node) override {
90 writeNamespace(node, android::RES_XML_START_NAMESPACE_TYPE);
91 xml::Visitor::visit(node);
92 writeNamespace(node, android::RES_XML_END_NAMESPACE_TYPE);
93 }
94
95 void visit(xml::Text* node) override {
96 if (util::trimWhitespace(node->text).empty()) {
97 // Skip whitespace only text nodes.
98 return;
99 }
100
101 ChunkWriter writer(mBuffer);
102 ResXMLTree_node* flatNode = writer.startChunk<ResXMLTree_node>(RES_XML_CDATA_TYPE);
103 flatNode->lineNumber = util::hostToDevice32(node->lineNumber);
104 flatNode->comment.index = util::hostToDevice32(-1);
105
106 ResXMLTree_cdataExt* flatText = writer.nextBlock<ResXMLTree_cdataExt>();
107 addString(node->text, kLowPriority, &flatText->data);
108
109 writer.finish();
110 }
111
112 void visit(xml::Element* node) override {
113 {
114 ChunkWriter startWriter(mBuffer);
115 ResXMLTree_node* flatNode = startWriter.startChunk<ResXMLTree_node>(
116 RES_XML_START_ELEMENT_TYPE);
117 flatNode->lineNumber = util::hostToDevice32(node->lineNumber);
118 flatNode->comment.index = util::hostToDevice32(-1);
119
120 ResXMLTree_attrExt* flatElem = startWriter.nextBlock<ResXMLTree_attrExt>();
121 addString(node->namespaceUri, kLowPriority, &flatElem->ns);
122 addString(node->name, kLowPriority, &flatElem->name);
123 flatElem->attributeStart = util::hostToDevice16(sizeof(*flatElem));
124 flatElem->attributeSize = util::hostToDevice16(sizeof(ResXMLTree_attribute));
125
126 writeAttributes(node, flatElem, &startWriter);
127
128 startWriter.finish();
129 }
130
131 xml::Visitor::visit(node);
132
133 {
134 ChunkWriter endWriter(mBuffer);
135 ResXMLTree_node* flatEndNode = endWriter.startChunk<ResXMLTree_node>(
136 RES_XML_END_ELEMENT_TYPE);
137 flatEndNode->lineNumber = util::hostToDevice32(node->lineNumber);
138 flatEndNode->comment.index = util::hostToDevice32(-1);
139
140 ResXMLTree_endElementExt* flatEndElem = endWriter.nextBlock<ResXMLTree_endElementExt>();
141 addString(node->namespaceUri, kLowPriority, &flatEndElem->ns);
142 addString(node->name, kLowPriority, &flatEndElem->name);
143
144 endWriter.finish();
145 }
146 }
147
148 static bool cmpXmlAttributeById(const xml::Attribute* a, const xml::Attribute* b) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800149 if (a->compiledAttribute && a->compiledAttribute.value().id) {
150 if (b->compiledAttribute && b->compiledAttribute.value().id) {
151 return a->compiledAttribute.value().id.value() < b->compiledAttribute.value().id.value();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152 }
153 return true;
154 } else if (!b->compiledAttribute) {
155 int diff = a->namespaceUri.compare(b->namespaceUri);
156 if (diff < 0) {
157 return true;
158 } else if (diff > 0) {
159 return false;
160 }
161 return a->name < b->name;
162 }
163 return false;
164 }
165
166 void writeAttributes(xml::Element* node, ResXMLTree_attrExt* flatElem, ChunkWriter* writer) {
167 mFilteredAttrs.clear();
168 mFilteredAttrs.reserve(node->attributes.size());
169
170 // Filter the attributes.
171 for (xml::Attribute& attr : node->attributes) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800172 if (mOptions.maxSdkLevel && attr.compiledAttribute && attr.compiledAttribute.value().id) {
173 size_t sdkLevel = findAttributeSdkLevel(attr.compiledAttribute.value().id.value());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700174 if (sdkLevel > mOptions.maxSdkLevel.value()) {
175 continue;
176 }
177 }
178 mFilteredAttrs.push_back(&attr);
179 }
180
181 if (mFilteredAttrs.empty()) {
182 return;
183 }
184
185 const ResourceId kIdAttr(0x010100d0);
186
187 std::sort(mFilteredAttrs.begin(), mFilteredAttrs.end(), cmpXmlAttributeById);
188
189 flatElem->attributeCount = util::hostToDevice16(mFilteredAttrs.size());
190
191 ResXMLTree_attribute* flatAttr = writer->nextBlock<ResXMLTree_attribute>(
192 mFilteredAttrs.size());
193 uint16_t attributeIndex = 1;
194 for (const xml::Attribute* xmlAttr : mFilteredAttrs) {
195 // Assign the indices for specific attributes.
Adam Lesinski64587af2016-02-18 18:33:06 -0800196 if (xmlAttr->compiledAttribute && xmlAttr->compiledAttribute.value().id &&
197 xmlAttr->compiledAttribute.value().id.value() == kIdAttr) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700198 flatElem->idIndex = util::hostToDevice16(attributeIndex);
199 } else if (xmlAttr->namespaceUri.empty()) {
200 if (xmlAttr->name == u"class") {
201 flatElem->classIndex = util::hostToDevice16(attributeIndex);
202 } else if (xmlAttr->name == u"style") {
203 flatElem->styleIndex = util::hostToDevice16(attributeIndex);
204 }
205 }
206 attributeIndex++;
207
208 // Add the namespaceUri to the list of StringRefs to encode.
209 addString(xmlAttr->namespaceUri, kLowPriority, &flatAttr->ns);
210
211 flatAttr->rawValue.index = util::hostToDevice32(-1);
212
Adam Lesinski64587af2016-02-18 18:33:06 -0800213 if (!xmlAttr->compiledAttribute || !xmlAttr->compiledAttribute.value().id) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700214 // The attribute has no associated ResourceID, so the string order doesn't matter.
215 addString(xmlAttr->name, kLowPriority, &flatAttr->name);
216 } else {
217 // Attribute names are stored without packages, but we use
218 // their StringPool index to lookup their resource IDs.
219 // This will cause collisions, so we can't dedupe
220 // attribute names from different packages. We use separate
221 // pools that we later combine.
222 //
223 // Lookup the StringPool for this package and make the reference there.
224 const xml::AaptAttribute& aaptAttr = xmlAttr->compiledAttribute.value();
225
Adam Lesinski64587af2016-02-18 18:33:06 -0800226 StringPool::Ref nameRef = mPackagePools[aaptAttr.id.value().packageId()].makeRef(
227 xmlAttr->name, StringPool::Context{ aaptAttr.id.value().id });
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700228
229 // Add it to the list of strings to flatten.
230 addString(nameRef, &flatAttr->name);
Adam Lesinski64587af2016-02-18 18:33:06 -0800231 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700232
Adam Lesinski64587af2016-02-18 18:33:06 -0800233 if (mOptions.keepRawValues || !xmlAttr->compiledValue) {
234 // Keep raw values if the value is not compiled or
235 // if we're building a static library (need symbols).
236 addString(xmlAttr->value, kLowPriority, &flatAttr->rawValue);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700237 }
238
239 if (xmlAttr->compiledValue) {
240 bool result = xmlAttr->compiledValue->flatten(&flatAttr->typedValue);
241 assert(result);
242 } else {
243 // Flatten as a regular string type.
244 flatAttr->typedValue.dataType = android::Res_value::TYPE_STRING;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700245 addString(xmlAttr->value, kLowPriority,
246 (ResStringPool_ref*) &flatAttr->typedValue.data);
247 }
248
249 flatAttr->typedValue.size = util::hostToDevice16(sizeof(flatAttr->typedValue));
250 flatAttr++;
251 }
252 }
253};
254
255} // namespace
256
257bool XmlFlattener::flatten(IAaptContext* context, xml::Node* node) {
258 BigBuffer nodeBuffer(1024);
259 XmlFlattenerVisitor visitor(&nodeBuffer, mOptions);
260 node->accept(&visitor);
261
262 // Merge the package pools into the main pool.
263 for (auto& packagePoolEntry : visitor.mPackagePools) {
264 visitor.mPool.merge(std::move(packagePoolEntry.second));
265 }
266
267 // Sort the string pool so that attribute resource IDs show up first.
268 visitor.mPool.sort([](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
269 return a.context.priority < b.context.priority;
270 });
271
272 // Now we flatten the string pool references into the correct places.
273 for (const auto& refEntry : visitor.mStringRefs) {
274 refEntry.dest->index = util::hostToDevice32(refEntry.ref.getIndex());
275 }
276
277 // Write the XML header.
278 ChunkWriter xmlHeaderWriter(mBuffer);
279 xmlHeaderWriter.startChunk<ResXMLTree_header>(RES_XML_TYPE);
280
281 // Flatten the StringPool.
282 StringPool::flattenUtf16(mBuffer, visitor.mPool);
283
284 {
285 // Write the array of resource IDs, indexed by StringPool order.
286 ChunkWriter resIdMapWriter(mBuffer);
287 resIdMapWriter.startChunk<ResChunk_header>(RES_XML_RESOURCE_MAP_TYPE);
288 for (const auto& str : visitor.mPool) {
289 ResourceId id = { str->context.priority };
290 if (id.id == kLowPriority || !id.isValid()) {
291 // When we see the first non-resource ID,
292 // we're done.
293 break;
294 }
295
296 *resIdMapWriter.nextBlock<uint32_t>() = id.id;
297 }
298 resIdMapWriter.finish();
299 }
300
301 // Move the nodeBuffer and append it to the out buffer.
302 mBuffer->appendBuffer(std::move(nodeBuffer));
303
304 // Finish the xml header.
305 xmlHeaderWriter.finish();
306 return true;
307}
308
Adam Lesinski467f1712015-11-16 17:35:44 -0800309bool XmlFlattener::consume(IAaptContext* context, xml::XmlResource* resource) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700310 if (!resource->root) {
311 return false;
312 }
313 return flatten(context, resource->root.get());
314}
315
316} // namespace aapt