blob: bf31bc137fa88cb9dba0de074d1e7d17190bd969 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6
7#include "XMLNode.h"
8#include "ResourceTable.h"
Bjorn Bringertfb903a42013-03-18 21:17:26 +00009#include "pseudolocalize.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011#include <utils/ByteOrder.h>
12#include <errno.h>
13#include <string.h>
14
15#ifndef HAVE_MS_C_RUNTIME
16#define O_BINARY 0
17#endif
18
Andreas Gampe2412f842014-09-30 20:55:57 -070019// SSIZE: mingw does not have signed size_t == ssize_t.
20// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
Elliott Hughesb12f2412015-04-03 12:56:45 -070021#if !defined(_WIN32)
Andreas Gampe2412f842014-09-30 20:55:57 -070022# define SSIZE(x) x
23# define STATUST(x) x
24#else
25# define SSIZE(x) (signed size_t)x
26# define STATUST(x) (status_t)x
27#endif
28
29// Set to true for noisy debug output.
30static const bool kIsDebug = false;
31// Set to true for noisy debug output of parsing.
32static const bool kIsDebugParse = false;
33
34#if PRINT_STRING_METRICS
35static const bool kPrintStringMetrics = true;
36#else
37static const bool kPrintStringMetrics = false;
38#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
40const char* const RESOURCES_ROOT_NAMESPACE = "http://schemas.android.com/apk/res/";
41const char* const RESOURCES_ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android";
Xavier Ducrohetd9fe8012012-02-23 16:59:27 -080042const char* const RESOURCES_AUTO_PACKAGE_NAMESPACE = "http://schemas.android.com/apk/res-auto";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043const char* const RESOURCES_ROOT_PRV_NAMESPACE = "http://schemas.android.com/apk/prv/res/";
44
45const char* const XLIFF_XMLNS = "urn:oasis:names:tc:xliff:document:1.2";
46const char* const ALLOWED_XLIFF_ELEMENTS[] = {
47 "bpt",
48 "ept",
49 "it",
50 "ph",
51 "g",
52 "bx",
53 "ex",
54 "x"
55 };
56
57bool isWhitespace(const char16_t* str)
58{
59 while (*str != 0 && *str < 128 && isspace(*str)) {
60 str++;
61 }
62 return *str == 0;
63}
64
65static const String16 RESOURCES_PREFIX(RESOURCES_ROOT_NAMESPACE);
inazaruke3489092011-05-22 15:09:06 -070066static const String16 RESOURCES_PREFIX_AUTO_PACKAGE(RESOURCES_AUTO_PACKAGE_NAMESPACE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067static const String16 RESOURCES_PRV_PREFIX(RESOURCES_ROOT_PRV_NAMESPACE);
Xavier Ducrohetf8aea992012-02-02 17:18:18 -080068static const String16 RESOURCES_TOOLS_NAMESPACE("http://schemas.android.com/tools");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
inazaruke3489092011-05-22 15:09:06 -070070String16 getNamespaceResourcePackage(String16 appPackage, String16 namespaceUri, bool* outIsPublic)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071{
72 //printf("%s starts with %s?\n", String8(namespaceUri).string(),
73 // String8(RESOURCES_PREFIX).string());
74 size_t prefixSize;
75 bool isPublic = true;
inazaruke3489092011-05-22 15:09:06 -070076 if(namespaceUri.startsWith(RESOURCES_PREFIX_AUTO_PACKAGE)) {
Andreas Gampe2412f842014-09-30 20:55:57 -070077 if (kIsDebug) {
78 printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(),
79 String8(appPackage).string());
80 }
inazaruke3489092011-05-22 15:09:06 -070081 isPublic = true;
82 return appPackage;
83 } else if (namespaceUri.startsWith(RESOURCES_PREFIX)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 prefixSize = RESOURCES_PREFIX.size();
85 } else if (namespaceUri.startsWith(RESOURCES_PRV_PREFIX)) {
86 isPublic = false;
87 prefixSize = RESOURCES_PRV_PREFIX.size();
88 } else {
89 if (outIsPublic) *outIsPublic = isPublic; // = true
90 return String16();
91 }
92
93 //printf("YES!\n");
94 //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).string());
95 if (outIsPublic) *outIsPublic = isPublic;
96 return String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize);
97}
98
Kenny Root15fe2cb2010-05-28 15:44:32 -070099status_t hasSubstitutionErrors(const char* fileName,
100 ResXMLTree* inXml,
101 String16 str16)
102{
103 const char16_t* str = str16.string();
104 const char16_t* p = str;
105 const char16_t* end = str + str16.size();
106
107 bool nonpositional = false;
108 int argCount = 0;
109
110 while (p < end) {
111 /*
112 * Look for the start of a Java-style substitution sequence.
113 */
114 if (*p == '%' && p + 1 < end) {
115 p++;
116
117 // A literal percent sign represented by %%
118 if (*p == '%') {
119 p++;
120 continue;
121 }
122
123 argCount++;
124
125 if (*p >= '0' && *p <= '9') {
126 do {
127 p++;
128 } while (*p >= '0' && *p <= '9');
129 if (*p != '$') {
130 // This must be a size specification instead of position.
131 nonpositional = true;
132 }
133 } else if (*p == '<') {
134 // Reusing last argument; bad idea since it can be re-arranged.
135 nonpositional = true;
136 p++;
137
138 // Optionally '$' can be specified at the end.
139 if (p < end && *p == '$') {
140 p++;
141 }
142 } else {
143 nonpositional = true;
144 }
145
146 // Ignore flags and widths
147 while (p < end && (*p == '-' ||
148 *p == '#' ||
149 *p == '+' ||
150 *p == ' ' ||
151 *p == ',' ||
152 *p == '(' ||
153 (*p >= '0' && *p <= '9'))) {
154 p++;
155 }
156
157 /*
158 * This is a shortcut to detect strings that are going to Time.format()
159 * instead of String.format()
160 *
161 * Comparison of String.format() and Time.format() args:
162 *
163 * String: ABC E GH ST X abcdefgh nost x
164 * Time: DEFGHKMS W Za d hkm s w yz
165 *
166 * Therefore we know it's definitely Time if we have:
167 * DFKMWZkmwyz
168 */
169 if (p < end) {
170 switch (*p) {
171 case 'D':
172 case 'F':
173 case 'K':
174 case 'M':
175 case 'W':
176 case 'Z':
177 case 'k':
178 case 'm':
179 case 'w':
180 case 'y':
181 case 'z':
182 return NO_ERROR;
183 }
184 }
185 }
186
187 p++;
188 }
189
190 /*
191 * If we have more than one substitution in this string and any of them
192 * are not in positional form, give the user an error.
193 */
194 if (argCount > 1 && nonpositional) {
195 SourcePos(String8(fileName), inXml->getLineNumber()).error(
196 "Multiple substitutions specified in non-positional format; "
Eric Fischer98ee11d2010-08-13 14:49:55 -0700197 "did you mean to add the formatted=\"false\" attribute?\n");
Kenny Root15fe2cb2010-05-28 15:44:32 -0700198 return NOT_ENOUGH_DATA;
199 }
200
201 return NO_ERROR;
202}
203
Andreas Gampe2412f842014-09-30 20:55:57 -0700204status_t parseStyledString(Bundle* /* bundle */,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 const char* fileName,
206 ResXMLTree* inXml,
207 const String16& endTag,
208 String16* outString,
209 Vector<StringPool::entry_style_span>* outSpans,
Kenny Root15fe2cb2010-05-28 15:44:32 -0700210 bool isFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700211 PseudolocalizationMethod pseudolocalize)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212{
213 Vector<StringPool::entry_style_span> spanStack;
214 String16 curString;
215 String16 rawString;
Igor Viarheichykcbb1e672015-05-14 18:47:00 -0700216 Pseudolocalizer pseudo(pseudolocalize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 const char* errorMsg;
218 int xliffDepth = 0;
219 bool firstTime = true;
220
221 size_t len;
222 ResXMLTree::event_code_t code;
Igor Viarheichykcbb1e672015-05-14 18:47:00 -0700223 curString.append(pseudo.start());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 while ((code=inXml->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 if (code == ResXMLTree::TEXT) {
226 String16 text(inXml->getText(&len));
227 if (firstTime && text.size() > 0) {
228 firstTime = false;
229 if (text.string()[0] == '@') {
230 // If this is a resource reference, don't do the pseudoloc.
Anton Krumina2ef5c02014-03-12 14:46:44 -0700231 pseudolocalize = NO_PSEUDOLOCALIZATION;
Igor Viarheichykcbb1e672015-05-14 18:47:00 -0700232 pseudo.setMethod(pseudolocalize);
233 curString = String16();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 }
235 }
Anton Krumina2ef5c02014-03-12 14:46:44 -0700236 if (xliffDepth == 0 && pseudolocalize > 0) {
Igor Viarheichykcbb1e672015-05-14 18:47:00 -0700237 curString.append(pseudo.text(text));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 } else {
Kenny Root15fe2cb2010-05-28 15:44:32 -0700239 if (isFormatted && hasSubstitutionErrors(fileName, inXml, text) != NO_ERROR) {
240 return UNKNOWN_ERROR;
241 } else {
242 curString.append(text);
243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245 } else if (code == ResXMLTree::START_TAG) {
246 const String16 element16(inXml->getElementName(&len));
247 const String8 element8(element16);
248
249 size_t nslen;
Dan Albertf348c152014-09-08 18:28:00 -0700250 const char16_t* ns = inXml->getElementNamespace(&nslen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 if (ns == NULL) {
Dan Albertf348c152014-09-08 18:28:00 -0700252 ns = (const char16_t*)"\0\0";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 nslen = 0;
254 }
255 const String8 nspace(String16(ns, nslen));
256 if (nspace == XLIFF_XMLNS) {
257 const int N = sizeof(ALLOWED_XLIFF_ELEMENTS)/sizeof(ALLOWED_XLIFF_ELEMENTS[0]);
258 for (int i=0; i<N; i++) {
259 if (element8 == ALLOWED_XLIFF_ELEMENTS[i]) {
260 xliffDepth++;
261 // in this case, treat it like it was just text, in other words, do nothing
262 // here and silently drop this element
263 goto moveon;
264 }
265 }
266 {
267 SourcePos(String8(fileName), inXml->getLineNumber()).error(
268 "Found unsupported XLIFF tag <%s>\n",
269 element8.string());
270 return UNKNOWN_ERROR;
271 }
272moveon:
273 continue;
274 }
275
276 if (outSpans == NULL) {
277 SourcePos(String8(fileName), inXml->getLineNumber()).error(
278 "Found style tag <%s> where styles are not allowed\n", element8.string());
279 return UNKNOWN_ERROR;
280 }
281
282 if (!ResTable::collectString(outString, curString.string(),
283 curString.size(), false, &errorMsg, true)) {
284 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
285 errorMsg, String8(curString).string());
286 return UNKNOWN_ERROR;
287 }
288 rawString.append(curString);
289 curString = String16();
290
291 StringPool::entry_style_span span;
292 span.name = element16;
293 for (size_t ai=0; ai<inXml->getAttributeCount(); ai++) {
294 span.name.append(String16(";"));
295 const char16_t* str = inXml->getAttributeName(ai, &len);
296 span.name.append(str, len);
297 span.name.append(String16("="));
298 str = inXml->getAttributeStringValue(ai, &len);
299 span.name.append(str, len);
300 }
301 //printf("Span: %s\n", String8(span.name).string());
302 span.span.firstChar = span.span.lastChar = outString->size();
303 spanStack.push(span);
304
305 } else if (code == ResXMLTree::END_TAG) {
306 size_t nslen;
Dan Albertf348c152014-09-08 18:28:00 -0700307 const char16_t* ns = inXml->getElementNamespace(&nslen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 if (ns == NULL) {
Dan Albertf348c152014-09-08 18:28:00 -0700309 ns = (const char16_t*)"\0\0";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 nslen = 0;
311 }
312 const String8 nspace(String16(ns, nslen));
313 if (nspace == XLIFF_XMLNS) {
314 xliffDepth--;
315 continue;
316 }
317 if (!ResTable::collectString(outString, curString.string(),
318 curString.size(), false, &errorMsg, true)) {
319 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
320 errorMsg, String8(curString).string());
321 return UNKNOWN_ERROR;
322 }
323 rawString.append(curString);
324 curString = String16();
325
326 if (spanStack.size() == 0) {
327 if (strcmp16(inXml->getElementName(&len), endTag.string()) != 0) {
328 SourcePos(String8(fileName), inXml->getLineNumber()).error(
329 "Found tag %s where <%s> close is expected\n",
330 String8(inXml->getElementName(&len)).string(),
331 String8(endTag).string());
332 return UNKNOWN_ERROR;
333 }
334 break;
335 }
336 StringPool::entry_style_span span = spanStack.top();
337 String16 spanTag;
338 ssize_t semi = span.name.findFirst(';');
339 if (semi >= 0) {
340 spanTag.setTo(span.name.string(), semi);
341 } else {
342 spanTag.setTo(span.name);
343 }
344 if (strcmp16(inXml->getElementName(&len), spanTag.string()) != 0) {
345 SourcePos(String8(fileName), inXml->getLineNumber()).error(
346 "Found close tag %s where close tag %s is expected\n",
347 String8(inXml->getElementName(&len)).string(),
348 String8(spanTag).string());
349 return UNKNOWN_ERROR;
350 }
351 bool empty = true;
352 if (outString->size() > 0) {
353 span.span.lastChar = outString->size()-1;
354 if (span.span.lastChar >= span.span.firstChar) {
355 empty = false;
356 outSpans->add(span);
357 }
358 }
359 spanStack.pop();
360
Eric Fischerc87d2522009-09-01 15:20:30 -0700361 /*
362 * This warning seems to be just an irritation to most people,
363 * since it is typically introduced by translators who then never
364 * see the warning.
365 */
366 if (0 && empty) {
Marco Nelissendd931862009-07-13 13:02:33 -0700367 fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 fileName, inXml->getLineNumber(),
369 String8(spanTag).string(), String8(*outString).string());
370
371 }
372 } else if (code == ResXMLTree::START_NAMESPACE) {
373 // nothing
374 }
375 }
376
Igor Viarheichykcbb1e672015-05-14 18:47:00 -0700377 curString.append(pseudo.end());
Anton Krumina2ef5c02014-03-12 14:46:44 -0700378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 if (code == ResXMLTree::BAD_DOCUMENT) {
380 SourcePos(String8(fileName), inXml->getLineNumber()).error(
381 "Error parsing XML\n");
382 }
383
384 if (outSpans != NULL && outSpans->size() > 0) {
385 if (curString.size() > 0) {
386 if (!ResTable::collectString(outString, curString.string(),
387 curString.size(), false, &errorMsg, true)) {
388 SourcePos(String8(fileName), inXml->getLineNumber()).error(
389 "%s (in %s)\n",
390 errorMsg, String8(curString).string());
391 return UNKNOWN_ERROR;
392 }
393 }
394 } else {
395 // There is no style information, so string processing will happen
396 // later as part of the overall type conversion. Return to the
397 // client the raw unprocessed text.
398 rawString.append(curString);
399 outString->setTo(rawString);
400 }
401
402 return NO_ERROR;
403}
404
405struct namespace_entry {
406 String8 prefix;
407 String8 uri;
408};
409
410static String8 make_prefix(int depth)
411{
412 String8 prefix;
413 int i;
414 for (i=0; i<depth; i++) {
415 prefix.append(" ");
416 }
417 return prefix;
418}
419
420static String8 build_namespace(const Vector<namespace_entry>& namespaces,
Dan Albertf348c152014-09-08 18:28:00 -0700421 const char16_t* ns)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422{
423 String8 str;
424 if (ns != NULL) {
425 str = String8(ns);
426 const size_t N = namespaces.size();
427 for (size_t i=0; i<N; i++) {
428 const namespace_entry& ne = namespaces.itemAt(i);
429 if (ne.uri == str) {
430 str = ne.prefix;
431 break;
432 }
433 }
434 str.append(":");
435 }
436 return str;
437}
438
439void printXMLBlock(ResXMLTree* block)
440{
441 block->restart();
442
443 Vector<namespace_entry> namespaces;
444
445 ResXMLTree::event_code_t code;
446 int depth = 0;
447 while ((code=block->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
448 String8 prefix = make_prefix(depth);
449 int i;
450 if (code == ResXMLTree::START_TAG) {
451 size_t len;
Dan Albertf348c152014-09-08 18:28:00 -0700452 const char16_t* ns16 = block->getElementNamespace(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 String8 elemNs = build_namespace(namespaces, ns16);
Dan Albertf348c152014-09-08 18:28:00 -0700454 const char16_t* com16 = block->getComment(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 if (com16) {
456 printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string());
457 }
458 printf("%sE: %s%s (line=%d)\n", prefix.string(), elemNs.string(),
459 String8(block->getElementName(&len)).string(),
460 block->getLineNumber());
461 int N = block->getAttributeCount();
462 depth++;
463 prefix = make_prefix(depth);
464 for (i=0; i<N; i++) {
465 uint32_t res = block->getAttributeNameResID(i);
466 ns16 = block->getAttributeNamespace(i, &len);
467 String8 ns = build_namespace(namespaces, ns16);
468 String8 name(block->getAttributeName(i, &len));
469 printf("%sA: ", prefix.string());
470 if (res) {
471 printf("%s%s(0x%08x)", ns.string(), name.string(), res);
472 } else {
473 printf("%s%s", ns.string(), name.string());
474 }
475 Res_value value;
476 block->getAttributeValue(i, &value);
477 if (value.dataType == Res_value::TYPE_NULL) {
478 printf("=(null)");
479 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
480 printf("=@0x%x", (int)value.data);
481 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
482 printf("=?0x%x", (int)value.data);
483 } else if (value.dataType == Res_value::TYPE_STRING) {
484 printf("=\"%s\"",
Shachar Shemesh9872bf42010-12-20 17:38:33 +0200485 ResTable::normalizeForOutput(String8(block->getAttributeStringValue(i,
486 &len)).string()).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 } else {
488 printf("=(type 0x%x)0x%x", (int)value.dataType, (int)value.data);
489 }
490 const char16_t* val = block->getAttributeStringValue(i, &len);
491 if (val != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +0200492 printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).string()).
493 string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
495 printf("\n");
496 }
497 } else if (code == ResXMLTree::END_TAG) {
498 depth--;
499 } else if (code == ResXMLTree::START_NAMESPACE) {
500 namespace_entry ns;
501 size_t len;
Dan Albertf348c152014-09-08 18:28:00 -0700502 const char16_t* prefix16 = block->getNamespacePrefix(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 if (prefix16) {
504 ns.prefix = String8(prefix16);
505 } else {
506 ns.prefix = "<DEF>";
507 }
508 ns.uri = String8(block->getNamespaceUri(&len));
509 namespaces.push(ns);
510 printf("%sN: %s=%s\n", prefix.string(), ns.prefix.string(),
511 ns.uri.string());
512 depth++;
513 } else if (code == ResXMLTree::END_NAMESPACE) {
514 depth--;
515 const namespace_entry& ns = namespaces.top();
516 size_t len;
Dan Albertf348c152014-09-08 18:28:00 -0700517 const char16_t* prefix16 = block->getNamespacePrefix(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 String8 pr;
519 if (prefix16) {
520 pr = String8(prefix16);
521 } else {
522 pr = "<DEF>";
523 }
524 if (ns.prefix != pr) {
525 prefix = make_prefix(depth);
526 printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
527 prefix.string(), pr.string(), ns.prefix.string());
528 }
529 String8 uri = String8(block->getNamespaceUri(&len));
530 if (ns.uri != uri) {
531 prefix = make_prefix(depth);
532 printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
533 prefix.string(), uri.string(), ns.uri.string());
534 }
535 namespaces.pop();
536 } else if (code == ResXMLTree::TEXT) {
537 size_t len;
Shachar Shemesh429dad62012-07-08 06:37:48 +0300538 printf("%sC: \"%s\"\n", prefix.string(),
539 ResTable::normalizeForOutput(String8(block->getText(&len)).string()).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541 }
542
543 block->restart();
544}
545
546status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree,
547 bool stripAll, bool keepComments,
548 const char** cDataTags)
549{
550 sp<XMLNode> root = XMLNode::parse(file);
551 if (root == NULL) {
552 return UNKNOWN_ERROR;
553 }
554 root->removeWhitespace(stripAll, cDataTags);
555
Andreas Gampe2412f842014-09-30 20:55:57 -0700556 if (kIsDebug) {
557 printf("Input XML from %s:\n", (const char*)file->getPrintableSource());
558 root->print();
559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8());
561 status_t err = root->flatten(rsc, !keepComments, false);
562 if (err != NO_ERROR) {
563 return err;
564 }
565 err = outTree->setTo(rsc->getData(), rsc->getSize(), true);
566 if (err != NO_ERROR) {
567 return err;
568 }
569
Andreas Gampe2412f842014-09-30 20:55:57 -0700570 if (kIsDebug) {
571 printf("Output XML:\n");
572 printXMLBlock(outTree);
573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574
575 return NO_ERROR;
576}
577
578sp<XMLNode> XMLNode::parse(const sp<AaptFile>& file)
579{
580 char buf[16384];
581 int fd = open(file->getSourceFile().string(), O_RDONLY | O_BINARY);
582 if (fd < 0) {
583 SourcePos(file->getSourceFile(), -1).error("Unable to open file for read: %s",
584 strerror(errno));
585 return NULL;
586 }
587
588 XML_Parser parser = XML_ParserCreateNS(NULL, 1);
589 ParseState state;
590 state.filename = file->getPrintableSource();
591 state.parser = parser;
592 XML_SetUserData(parser, &state);
593 XML_SetElementHandler(parser, startElement, endElement);
594 XML_SetNamespaceDeclHandler(parser, startNamespace, endNamespace);
595 XML_SetCharacterDataHandler(parser, characterData);
596 XML_SetCommentHandler(parser, commentData);
597
598 ssize_t len;
599 bool done;
600 do {
601 len = read(fd, buf, sizeof(buf));
602 done = len < (ssize_t)sizeof(buf);
603 if (len < 0) {
604 SourcePos(file->getSourceFile(), -1).error("Error reading file: %s\n", strerror(errno));
605 close(fd);
606 return NULL;
607 }
608 if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
609 SourcePos(file->getSourceFile(), (int)XML_GetCurrentLineNumber(parser)).error(
610 "Error parsing XML: %s\n", XML_ErrorString(XML_GetErrorCode(parser)));
611 close(fd);
612 return NULL;
613 }
614 } while (!done);
615
616 XML_ParserFree(parser);
617 if (state.root == NULL) {
618 SourcePos(file->getSourceFile(), -1).error("No XML data generated when parsing");
619 }
620 close(fd);
621 return state.root;
622}
623
Adam Lesinskie572c012014-09-19 15:10:04 -0700624XMLNode::XMLNode()
625 : mNextAttributeIndex(0x80000000)
626 , mStartLineNumber(0)
627 , mEndLineNumber(0)
628 , mUTF8(false) {}
629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630XMLNode::XMLNode(const String8& filename, const String16& s1, const String16& s2, bool isNamespace)
631 : mNextAttributeIndex(0x80000000)
632 , mFilename(filename)
633 , mStartLineNumber(0)
634 , mEndLineNumber(0)
Kenny Root19138462009-12-04 09:38:48 -0800635 , mUTF8(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636{
637 if (isNamespace) {
638 mNamespacePrefix = s1;
639 mNamespaceUri = s2;
640 } else {
641 mNamespaceUri = s1;
642 mElementName = s2;
643 }
644}
645
646XMLNode::XMLNode(const String8& filename)
647 : mFilename(filename)
648{
Marco Nelissen6a1fade2009-04-20 16:16:01 -0700649 memset(&mCharsValue, 0, sizeof(mCharsValue));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650}
651
652XMLNode::type XMLNode::getType() const
653{
654 if (mElementName.size() != 0) {
655 return TYPE_ELEMENT;
656 }
657 if (mNamespaceUri.size() != 0) {
658 return TYPE_NAMESPACE;
659 }
660 return TYPE_CDATA;
661}
662
663const String16& XMLNode::getNamespacePrefix() const
664{
665 return mNamespacePrefix;
666}
667
668const String16& XMLNode::getNamespaceUri() const
669{
670 return mNamespaceUri;
671}
672
673const String16& XMLNode::getElementNamespace() const
674{
675 return mNamespaceUri;
676}
677
678const String16& XMLNode::getElementName() const
679{
680 return mElementName;
681}
682
683const Vector<sp<XMLNode> >& XMLNode::getChildren() const
684{
685 return mChildren;
686}
687
Dianne Hackborn62da8462009-05-13 15:06:13 -0700688const String8& XMLNode::getFilename() const
689{
690 return mFilename;
691}
692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693const Vector<XMLNode::attribute_entry>&
694 XMLNode::getAttributes() const
695{
696 return mAttributes;
697}
698
Dianne Hackborn62da8462009-05-13 15:06:13 -0700699const XMLNode::attribute_entry* XMLNode::getAttribute(const String16& ns,
700 const String16& name) const
701{
702 for (size_t i=0; i<mAttributes.size(); i++) {
703 const attribute_entry& ae(mAttributes.itemAt(i));
704 if (ae.ns == ns && ae.name == name) {
705 return &ae;
706 }
707 }
708
709 return NULL;
710}
711
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600712XMLNode::attribute_entry* XMLNode::editAttribute(const String16& ns,
713 const String16& name)
714{
715 for (size_t i=0; i<mAttributes.size(); i++) {
716 attribute_entry * ae = &mAttributes.editItemAt(i);
717 if (ae->ns == ns && ae->name == name) {
718 return ae;
719 }
720 }
721
722 return NULL;
723}
724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725const String16& XMLNode::getCData() const
726{
727 return mChars;
728}
729
730const String16& XMLNode::getComment() const
731{
732 return mComment;
733}
734
735int32_t XMLNode::getStartLineNumber() const
736{
737 return mStartLineNumber;
738}
739
740int32_t XMLNode::getEndLineNumber() const
741{
742 return mEndLineNumber;
743}
744
Dianne Hackborn62da8462009-05-13 15:06:13 -0700745sp<XMLNode> XMLNode::searchElement(const String16& tagNamespace, const String16& tagName)
746{
747 if (getType() == XMLNode::TYPE_ELEMENT
748 && mNamespaceUri == tagNamespace
749 && mElementName == tagName) {
750 return this;
751 }
752
753 for (size_t i=0; i<mChildren.size(); i++) {
754 sp<XMLNode> found = mChildren.itemAt(i)->searchElement(tagNamespace, tagName);
755 if (found != NULL) {
756 return found;
757 }
758 }
759
760 return NULL;
761}
762
763sp<XMLNode> XMLNode::getChildElement(const String16& tagNamespace, const String16& tagName)
764{
765 for (size_t i=0; i<mChildren.size(); i++) {
766 sp<XMLNode> child = mChildren.itemAt(i);
767 if (child->getType() == XMLNode::TYPE_ELEMENT
768 && child->mNamespaceUri == tagNamespace
769 && child->mElementName == tagName) {
770 return child;
771 }
772 }
773
774 return NULL;
775}
776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777status_t XMLNode::addChild(const sp<XMLNode>& child)
778{
779 if (getType() == TYPE_CDATA) {
780 SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
781 return UNKNOWN_ERROR;
782 }
783 //printf("Adding child %p to parent %p\n", child.get(), this);
784 mChildren.add(child);
785 return NO_ERROR;
786}
787
Dianne Hackborn62da8462009-05-13 15:06:13 -0700788status_t XMLNode::insertChildAt(const sp<XMLNode>& child, size_t index)
789{
790 if (getType() == TYPE_CDATA) {
791 SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
792 return UNKNOWN_ERROR;
793 }
794 //printf("Adding child %p to parent %p\n", child.get(), this);
795 mChildren.insertAt(child, index);
796 return NO_ERROR;
797}
798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799status_t XMLNode::addAttribute(const String16& ns, const String16& name,
800 const String16& value)
801{
802 if (getType() == TYPE_CDATA) {
803 SourcePos(mFilename, getStartLineNumber()).error("Child to CDATA node.");
804 return UNKNOWN_ERROR;
805 }
Xavier Ducrohetf8aea992012-02-02 17:18:18 -0800806
807 if (ns != RESOURCES_TOOLS_NAMESPACE) {
808 attribute_entry e;
809 e.index = mNextAttributeIndex++;
810 e.ns = ns;
811 e.name = name;
812 e.string = value;
813 mAttributes.add(e);
814 mAttributeOrder.add(e.index, mAttributes.size()-1);
815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 return NO_ERROR;
817}
818
Adam Lesinskie572c012014-09-19 15:10:04 -0700819status_t XMLNode::removeAttribute(size_t index)
820{
821 if (getType() == TYPE_CDATA) {
822 return UNKNOWN_ERROR;
823 }
824
825 if (index >= mAttributes.size()) {
826 return UNKNOWN_ERROR;
827 }
828
829 const attribute_entry& e = mAttributes[index];
830 const uint32_t key = e.nameResId ? e.nameResId : e.index;
831 mAttributeOrder.removeItem(key);
832 mAttributes.removeAt(index);
833
834 // Shift all the indices.
835 const size_t attrCount = mAttributeOrder.size();
836 for (size_t i = 0; i < attrCount; i++) {
837 size_t attrIdx = mAttributeOrder[i];
838 if (attrIdx > index) {
839 mAttributeOrder.replaceValueAt(i, attrIdx - 1);
840 }
841 }
842 return NO_ERROR;
843}
844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845void XMLNode::setAttributeResID(size_t attrIdx, uint32_t resId)
846{
847 attribute_entry& e = mAttributes.editItemAt(attrIdx);
848 if (e.nameResId) {
849 mAttributeOrder.removeItem(e.nameResId);
850 } else {
851 mAttributeOrder.removeItem(e.index);
852 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700853 if (kIsDebug) {
854 printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
855 String8(getElementName()).string(),
856 String8(mAttributes.itemAt(attrIdx).name).string(),
857 String8(mAttributes.itemAt(attrIdx).string).string(),
858 resId);
859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 mAttributes.editItemAt(attrIdx).nameResId = resId;
861 mAttributeOrder.add(resId, attrIdx);
862}
863
864status_t XMLNode::appendChars(const String16& chars)
865{
866 if (getType() != TYPE_CDATA) {
867 SourcePos(mFilename, getStartLineNumber()).error("Adding characters to element node.");
868 return UNKNOWN_ERROR;
869 }
870 mChars.append(chars);
871 return NO_ERROR;
872}
873
874status_t XMLNode::appendComment(const String16& comment)
875{
876 if (mComment.size() > 0) {
877 mComment.append(String16("\n"));
878 }
879 mComment.append(comment);
880 return NO_ERROR;
881}
882
883void XMLNode::setStartLineNumber(int32_t line)
884{
885 mStartLineNumber = line;
886}
887
888void XMLNode::setEndLineNumber(int32_t line)
889{
890 mEndLineNumber = line;
891}
892
893void XMLNode::removeWhitespace(bool stripAll, const char** cDataTags)
894{
895 //printf("Removing whitespace in %s\n", String8(mElementName).string());
896 size_t N = mChildren.size();
897 if (cDataTags) {
898 String8 tag(mElementName);
899 const char** p = cDataTags;
900 while (*p) {
901 if (tag == *p) {
902 stripAll = false;
903 break;
904 }
905 }
906 }
907 for (size_t i=0; i<N; i++) {
908 sp<XMLNode> node = mChildren.itemAt(i);
909 if (node->getType() == TYPE_CDATA) {
910 // This is a CDATA node...
911 const char16_t* p = node->mChars.string();
912 while (*p != 0 && *p < 128 && isspace(*p)) {
913 p++;
914 }
915 //printf("Space ends at %d in \"%s\"\n",
916 // (int)(p-node->mChars.string()),
917 // String8(node->mChars).string());
918 if (*p == 0) {
919 if (stripAll) {
920 // Remove this node!
921 mChildren.removeAt(i);
922 N--;
923 i--;
924 } else {
925 node->mChars = String16(" ");
926 }
927 } else {
928 // Compact leading/trailing whitespace.
929 const char16_t* e = node->mChars.string()+node->mChars.size()-1;
930 while (e > p && *e < 128 && isspace(*e)) {
931 e--;
932 }
933 if (p > node->mChars.string()) {
934 p--;
935 }
936 if (e < (node->mChars.string()+node->mChars.size()-1)) {
937 e++;
938 }
939 if (p > node->mChars.string() ||
940 e < (node->mChars.string()+node->mChars.size()-1)) {
941 String16 tmp(p, e-p+1);
942 node->mChars = tmp;
943 }
944 }
945 } else {
946 node->removeWhitespace(stripAll, cDataTags);
947 }
948 }
949}
950
951status_t XMLNode::parseValues(const sp<AaptAssets>& assets,
952 ResourceTable* table)
953{
954 bool hasErrors = false;
955
956 if (getType() == TYPE_ELEMENT) {
957 const size_t N = mAttributes.size();
958 String16 defPackage(assets->getPackage());
959 for (size_t i=0; i<N; i++) {
960 attribute_entry& e = mAttributes.editItemAt(i);
961 AccessorCookie ac(SourcePos(mFilename, getStartLineNumber()), String8(e.name),
962 String8(e.string));
963 table->setCurrentXmlPos(SourcePos(mFilename, getStartLineNumber()));
964 if (!assets->getIncludedResources()
965 .stringToValue(&e.value, &e.string,
966 e.string.string(), e.string.size(), true, true,
967 e.nameResId, NULL, &defPackage, table, &ac)) {
968 hasErrors = true;
969 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700970 if (kIsDebug) {
971 printf("Attr %s: type=0x%x, str=%s\n",
972 String8(e.name).string(), e.value.dataType,
973 String8(e.string).string());
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
977 const size_t N = mChildren.size();
978 for (size_t i=0; i<N; i++) {
979 status_t err = mChildren.itemAt(i)->parseValues(assets, table);
980 if (err != NO_ERROR) {
981 hasErrors = true;
982 }
983 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700984 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985}
986
987status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets,
988 const ResourceTable* table)
989{
990 bool hasErrors = false;
991
992 if (getType() == TYPE_ELEMENT) {
993 String16 attr("attr");
994 const char* errorMsg;
995 const size_t N = mAttributes.size();
996 for (size_t i=0; i<N; i++) {
997 const attribute_entry& e = mAttributes.itemAt(i);
998 if (e.ns.size() <= 0) continue;
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -0700999 bool nsIsPublic = true;
inazaruke3489092011-05-22 15:09:06 -07001000 String16 pkg(getNamespaceResourcePackage(String16(assets->getPackage()), e.ns, &nsIsPublic));
Andreas Gampe2412f842014-09-30 20:55:57 -07001001 if (kIsDebug) {
1002 printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
1003 String8(getElementName()).string(),
1004 String8(e.name).string(),
1005 String8(e.string).string(),
1006 String8(e.ns).string(),
1007 (nsIsPublic) ? "public" : "private",
1008 String8(pkg).string());
1009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 if (pkg.size() <= 0) continue;
1011 uint32_t res = table != NULL
1012 ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic)
1013 : assets->getIncludedResources().
1014 identifierForName(e.name.string(), e.name.size(),
1015 attr.string(), attr.size(),
1016 pkg.string(), pkg.size());
1017 if (res != 0) {
Andreas Gampe2412f842014-09-30 20:55:57 -07001018 if (kIsDebug) {
1019 printf("XML attribute name %s: resid=0x%08x\n",
1020 String8(e.name).string(), res);
1021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 setAttributeResID(i, res);
1023 } else {
1024 SourcePos(mFilename, getStartLineNumber()).error(
1025 "No resource identifier found for attribute '%s' in package '%s'\n",
1026 String8(e.name).string(), String8(pkg).string());
1027 hasErrors = true;
1028 }
1029 }
1030 }
1031 const size_t N = mChildren.size();
1032 for (size_t i=0; i<N; i++) {
1033 status_t err = mChildren.itemAt(i)->assignResourceIds(assets, table);
1034 if (err < NO_ERROR) {
1035 hasErrors = true;
1036 }
1037 }
1038
Andreas Gampe2412f842014-09-30 20:55:57 -07001039 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040}
1041
Adam Lesinskie572c012014-09-19 15:10:04 -07001042sp<XMLNode> XMLNode::clone() const {
1043 sp<XMLNode> copy = new XMLNode();
1044 copy->mNamespacePrefix = mNamespacePrefix;
1045 copy->mNamespaceUri = mNamespaceUri;
1046 copy->mElementName = mElementName;
1047
1048 const size_t childCount = mChildren.size();
1049 for (size_t i = 0; i < childCount; i++) {
1050 copy->mChildren.add(mChildren[i]->clone());
1051 }
1052
1053 copy->mAttributes = mAttributes;
1054 copy->mAttributeOrder = mAttributeOrder;
1055 copy->mNextAttributeIndex = mNextAttributeIndex;
1056 copy->mChars = mChars;
1057 memcpy(&copy->mCharsValue, &mCharsValue, sizeof(mCharsValue));
1058 copy->mComment = mComment;
1059 copy->mFilename = mFilename;
1060 copy->mStartLineNumber = mStartLineNumber;
1061 copy->mEndLineNumber = mEndLineNumber;
1062 copy->mUTF8 = mUTF8;
1063 return copy;
1064}
1065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066status_t XMLNode::flatten(const sp<AaptFile>& dest,
1067 bool stripComments, bool stripRawValues) const
1068{
Jeff Brown345b7eb2012-03-16 15:25:17 -07001069 StringPool strings(mUTF8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 Vector<uint32_t> resids;
1071
1072 // First collect just the strings for attribute names that have a
1073 // resource ID assigned to them. This ensures that the resource ID
1074 // array is compact, and makes it easier to deal with attribute names
1075 // in different namespaces (and thus with different resource IDs).
1076 collect_resid_strings(&strings, &resids);
1077
1078 // Next collect all remainibng strings.
1079 collect_strings(&strings, &resids, stripComments, stripRawValues);
1080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 sp<AaptFile> stringPool = strings.createStringBlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082
1083 ResXMLTree_header header;
1084 memset(&header, 0, sizeof(header));
1085 header.header.type = htods(RES_XML_TYPE);
1086 header.header.headerSize = htods(sizeof(header));
1087
1088 const size_t basePos = dest->getSize();
1089 dest->writeData(&header, sizeof(header));
1090 dest->writeData(stringPool->getData(), stringPool->getSize());
1091
1092 // If we have resource IDs, write them.
1093 if (resids.size() > 0) {
1094 const size_t resIdsPos = dest->getSize();
1095 const size_t resIdsSize =
1096 sizeof(ResChunk_header)+(sizeof(uint32_t)*resids.size());
1097 ResChunk_header* idsHeader = (ResChunk_header*)
1098 (((const uint8_t*)dest->editData(resIdsPos+resIdsSize))+resIdsPos);
1099 idsHeader->type = htods(RES_XML_RESOURCE_MAP_TYPE);
1100 idsHeader->headerSize = htods(sizeof(*idsHeader));
1101 idsHeader->size = htodl(resIdsSize);
1102 uint32_t* ids = (uint32_t*)(idsHeader+1);
1103 for (size_t i=0; i<resids.size(); i++) {
1104 *ids++ = htodl(resids[i]);
1105 }
1106 }
1107
1108 flatten_node(strings, dest, stripComments, stripRawValues);
1109
1110 void* data = dest->editData();
1111 ResXMLTree_header* hd = (ResXMLTree_header*)(((uint8_t*)data)+basePos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 hd->header.size = htodl(dest->getSize()-basePos);
1113
Andreas Gampe2412f842014-09-30 20:55:57 -07001114 if (kPrintStringMetrics) {
1115 fprintf(stderr, "**** total xml size: %zu / %zu%% strings (in %s)\n",
1116 dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
1117 dest->getPath().string());
1118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119
1120 return NO_ERROR;
1121}
1122
1123void XMLNode::print(int indent)
1124{
1125 String8 prefix;
1126 int i;
1127 for (i=0; i<indent; i++) {
1128 prefix.append(" ");
1129 }
1130 if (getType() == TYPE_ELEMENT) {
1131 String8 elemNs(getNamespaceUri());
1132 if (elemNs.size() > 0) {
1133 elemNs.append(":");
1134 }
1135 printf("%s E: %s%s", prefix.string(),
1136 elemNs.string(), String8(getElementName()).string());
1137 int N = mAttributes.size();
1138 for (i=0; i<N; i++) {
1139 ssize_t idx = mAttributeOrder.valueAt(i);
1140 if (i == 0) {
1141 printf(" / ");
1142 } else {
1143 printf(", ");
1144 }
1145 const attribute_entry& attr = mAttributes.itemAt(idx);
1146 String8 attrNs(attr.ns);
1147 if (attrNs.size() > 0) {
1148 attrNs.append(":");
1149 }
1150 if (attr.nameResId) {
1151 printf("%s%s(0x%08x)", attrNs.string(),
1152 String8(attr.name).string(), attr.nameResId);
1153 } else {
1154 printf("%s%s", attrNs.string(), String8(attr.name).string());
1155 }
1156 printf("=%s", String8(attr.string).string());
1157 }
1158 printf("\n");
1159 } else if (getType() == TYPE_NAMESPACE) {
1160 printf("%s N: %s=%s\n", prefix.string(),
1161 getNamespacePrefix().size() > 0
1162 ? String8(getNamespacePrefix()).string() : "<DEF>",
1163 String8(getNamespaceUri()).string());
1164 } else {
1165 printf("%s C: \"%s\"\n", prefix.string(), String8(getCData()).string());
1166 }
1167 int N = mChildren.size();
1168 for (i=0; i<N; i++) {
1169 mChildren.itemAt(i)->print(indent+1);
1170 }
1171}
1172
1173static void splitName(const char* name, String16* outNs, String16* outName)
1174{
1175 const char* p = name;
1176 while (*p != 0 && *p != 1) {
1177 p++;
1178 }
1179 if (*p == 0) {
1180 *outNs = String16();
1181 *outName = String16(name);
1182 } else {
1183 *outNs = String16(name, (p-name));
1184 *outName = String16(p+1);
1185 }
1186}
1187
1188void XMLCALL
1189XMLNode::startNamespace(void *userData, const char *prefix, const char *uri)
1190{
Andreas Gampe2412f842014-09-30 20:55:57 -07001191 if (kIsDebugParse) {
1192 printf("Start Namespace: %s %s\n", prefix, uri);
1193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 ParseState* st = (ParseState*)userData;
1195 sp<XMLNode> node = XMLNode::newNamespace(st->filename,
1196 String16(prefix != NULL ? prefix : ""), String16(uri));
1197 node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1198 if (st->stack.size() > 0) {
1199 st->stack.itemAt(st->stack.size()-1)->addChild(node);
1200 } else {
1201 st->root = node;
1202 }
1203 st->stack.push(node);
1204}
1205
1206void XMLCALL
1207XMLNode::startElement(void *userData, const char *name, const char **atts)
1208{
Andreas Gampe2412f842014-09-30 20:55:57 -07001209 if (kIsDebugParse) {
1210 printf("Start Element: %s\n", name);
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 ParseState* st = (ParseState*)userData;
1213 String16 ns16, name16;
1214 splitName(name, &ns16, &name16);
1215 sp<XMLNode> node = XMLNode::newElement(st->filename, ns16, name16);
1216 node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1217 if (st->pendingComment.size() > 0) {
1218 node->appendComment(st->pendingComment);
1219 st->pendingComment = String16();
1220 }
1221 if (st->stack.size() > 0) {
1222 st->stack.itemAt(st->stack.size()-1)->addChild(node);
1223 } else {
1224 st->root = node;
1225 }
1226 st->stack.push(node);
1227
1228 for (int i = 0; atts[i]; i += 2) {
1229 splitName(atts[i], &ns16, &name16);
1230 node->addAttribute(ns16, name16, String16(atts[i+1]));
1231 }
1232}
1233
1234void XMLCALL
1235XMLNode::characterData(void *userData, const XML_Char *s, int len)
1236{
Andreas Gampe2412f842014-09-30 20:55:57 -07001237 if (kIsDebugParse) {
1238 printf("CDATA: \"%s\"\n", String8(s, len).string());
1239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 ParseState* st = (ParseState*)userData;
1241 sp<XMLNode> node = NULL;
1242 if (st->stack.size() == 0) {
1243 return;
1244 }
1245 sp<XMLNode> parent = st->stack.itemAt(st->stack.size()-1);
1246 if (parent != NULL && parent->getChildren().size() > 0) {
1247 node = parent->getChildren()[parent->getChildren().size()-1];
1248 if (node->getType() != TYPE_CDATA) {
1249 // Last node is not CDATA, need to make a new node.
1250 node = NULL;
1251 }
1252 }
1253
1254 if (node == NULL) {
1255 node = XMLNode::newCData(st->filename);
1256 node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1257 parent->addChild(node);
1258 }
1259
1260 node->appendChars(String16(s, len));
1261}
1262
1263void XMLCALL
1264XMLNode::endElement(void *userData, const char *name)
1265{
Andreas Gampe2412f842014-09-30 20:55:57 -07001266 if (kIsDebugParse) {
1267 printf("End Element: %s\n", name);
1268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 ParseState* st = (ParseState*)userData;
1270 sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
1271 node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
1272 if (st->pendingComment.size() > 0) {
1273 node->appendComment(st->pendingComment);
1274 st->pendingComment = String16();
1275 }
1276 String16 ns16, name16;
1277 splitName(name, &ns16, &name16);
1278 LOG_ALWAYS_FATAL_IF(node->getElementNamespace() != ns16
1279 || node->getElementName() != name16,
1280 "Bad end element %s", name);
1281 st->stack.pop();
1282}
1283
1284void XMLCALL
1285XMLNode::endNamespace(void *userData, const char *prefix)
1286{
1287 const char* nonNullPrefix = prefix != NULL ? prefix : "";
Andreas Gampe2412f842014-09-30 20:55:57 -07001288 if (kIsDebugParse) {
1289 printf("End Namespace: %s\n", prefix);
1290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 ParseState* st = (ParseState*)userData;
1292 sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
1293 node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
1294 LOG_ALWAYS_FATAL_IF(node->getNamespacePrefix() != String16(nonNullPrefix),
1295 "Bad end namespace %s", prefix);
1296 st->stack.pop();
1297}
1298
1299void XMLCALL
1300XMLNode::commentData(void *userData, const char *comment)
1301{
Andreas Gampe2412f842014-09-30 20:55:57 -07001302 if (kIsDebugParse) {
1303 printf("Comment: %s\n", comment);
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ParseState* st = (ParseState*)userData;
1306 if (st->pendingComment.size() > 0) {
1307 st->pendingComment.append(String16("\n"));
1308 }
1309 st->pendingComment.append(String16(comment));
1310}
1311
1312status_t XMLNode::collect_strings(StringPool* dest, Vector<uint32_t>* outResIds,
1313 bool stripComments, bool stripRawValues) const
1314{
1315 collect_attr_strings(dest, outResIds, true);
1316
1317 int i;
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001318 if (RESOURCES_TOOLS_NAMESPACE != mNamespaceUri) {
1319 if (mNamespacePrefix.size() > 0) {
1320 dest->add(mNamespacePrefix, true);
1321 }
1322 if (mNamespaceUri.size() > 0) {
1323 dest->add(mNamespaceUri, true);
1324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326 if (mElementName.size() > 0) {
1327 dest->add(mElementName, true);
1328 }
1329
1330 if (!stripComments && mComment.size() > 0) {
1331 dest->add(mComment, true);
1332 }
1333
1334 const int NA = mAttributes.size();
1335
1336 for (i=0; i<NA; i++) {
1337 const attribute_entry& ae = mAttributes.itemAt(i);
1338 if (ae.ns.size() > 0) {
1339 dest->add(ae.ns, true);
1340 }
1341 if (!stripRawValues || ae.needStringValue()) {
1342 dest->add(ae.string, true);
1343 }
1344 /*
1345 if (ae.value.dataType == Res_value::TYPE_NULL
1346 || ae.value.dataType == Res_value::TYPE_STRING) {
1347 dest->add(ae.string, true);
1348 }
1349 */
1350 }
1351
1352 if (mElementName.size() == 0) {
1353 // If not an element, include the CDATA, even if it is empty.
1354 dest->add(mChars, true);
1355 }
1356
1357 const int NC = mChildren.size();
1358
1359 for (i=0; i<NC; i++) {
1360 mChildren.itemAt(i)->collect_strings(dest, outResIds,
1361 stripComments, stripRawValues);
1362 }
1363
1364 return NO_ERROR;
1365}
1366
1367status_t XMLNode::collect_attr_strings(StringPool* outPool,
1368 Vector<uint32_t>* outResIds, bool allAttrs) const {
1369 const int NA = mAttributes.size();
1370
1371 for (int i=0; i<NA; i++) {
1372 const attribute_entry& attr = mAttributes.itemAt(i);
1373 uint32_t id = attr.nameResId;
1374 if (id || allAttrs) {
1375 // See if we have already assigned this resource ID to a pooled
1376 // string...
1377 const Vector<size_t>* indices = outPool->offsetsForString(attr.name);
1378 ssize_t idx = -1;
1379 if (indices != NULL) {
1380 const int NJ = indices->size();
1381 const size_t NR = outResIds->size();
1382 for (int j=0; j<NJ; j++) {
1383 size_t strIdx = indices->itemAt(j);
1384 if (strIdx >= NR) {
1385 if (id == 0) {
1386 // We don't need to assign a resource ID for this one.
1387 idx = strIdx;
1388 break;
1389 }
1390 // Just ignore strings that are out of range of
1391 // the currently assigned resource IDs... we add
1392 // strings as we assign the first ID.
1393 } else if (outResIds->itemAt(strIdx) == id) {
1394 idx = strIdx;
1395 break;
1396 }
1397 }
1398 }
1399 if (idx < 0) {
1400 idx = outPool->add(attr.name);
Andreas Gampe2412f842014-09-30 20:55:57 -07001401 if (kIsDebug) {
1402 printf("Adding attr %s (resid 0x%08x) to pool: idx=%zd\n",
1403 String8(attr.name).string(), id, SSIZE(idx));
1404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 if (id != 0) {
1406 while ((ssize_t)outResIds->size() <= idx) {
1407 outResIds->add(0);
1408 }
1409 outResIds->replaceAt(id, idx);
1410 }
1411 }
1412 attr.namePoolIdx = idx;
Andreas Gampe2412f842014-09-30 20:55:57 -07001413 if (kIsDebug) {
1414 printf("String %s offset=0x%08zd\n", String8(attr.name).string(), SSIZE(idx));
1415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 }
1418
1419 return NO_ERROR;
1420}
1421
1422status_t XMLNode::collect_resid_strings(StringPool* outPool,
1423 Vector<uint32_t>* outResIds) const
1424{
1425 collect_attr_strings(outPool, outResIds, false);
1426
1427 const int NC = mChildren.size();
1428
1429 for (int i=0; i<NC; i++) {
1430 mChildren.itemAt(i)->collect_resid_strings(outPool, outResIds);
1431 }
1432
1433 return NO_ERROR;
1434}
1435
1436status_t XMLNode::flatten_node(const StringPool& strings, const sp<AaptFile>& dest,
1437 bool stripComments, bool stripRawValues) const
1438{
1439 ResXMLTree_node node;
1440 ResXMLTree_cdataExt cdataExt;
1441 ResXMLTree_namespaceExt namespaceExt;
1442 ResXMLTree_attrExt attrExt;
1443 const void* extData = NULL;
1444 size_t extSize = 0;
1445 ResXMLTree_attribute attr;
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001446 bool writeCurrentNode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447
1448 const size_t NA = mAttributes.size();
1449 const size_t NC = mChildren.size();
1450 size_t i;
1451
1452 LOG_ALWAYS_FATAL_IF(NA != mAttributeOrder.size(), "Attributes messed up!");
1453
1454 const String16 id16("id");
1455 const String16 class16("class");
1456 const String16 style16("style");
1457
1458 const type type = getType();
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 memset(&node, 0, sizeof(node));
1461 memset(&attr, 0, sizeof(attr));
1462 node.header.headerSize = htods(sizeof(node));
1463 node.lineNumber = htodl(getStartLineNumber());
1464 if (!stripComments) {
1465 node.comment.index = htodl(
1466 mComment.size() > 0 ? strings.offsetForString(mComment) : -1);
1467 //if (mComment.size() > 0) {
1468 // printf("Flattening comment: %s\n", String8(mComment).string());
1469 //}
1470 } else {
1471 node.comment.index = htodl((uint32_t)-1);
1472 }
1473 if (type == TYPE_ELEMENT) {
1474 node.header.type = htods(RES_XML_START_ELEMENT_TYPE);
1475 extData = &attrExt;
1476 extSize = sizeof(attrExt);
1477 memset(&attrExt, 0, sizeof(attrExt));
1478 if (mNamespaceUri.size() > 0) {
1479 attrExt.ns.index = htodl(strings.offsetForString(mNamespaceUri));
1480 } else {
1481 attrExt.ns.index = htodl((uint32_t)-1);
1482 }
1483 attrExt.name.index = htodl(strings.offsetForString(mElementName));
1484 attrExt.attributeStart = htods(sizeof(attrExt));
1485 attrExt.attributeSize = htods(sizeof(attr));
1486 attrExt.attributeCount = htods(NA);
1487 attrExt.idIndex = htods(0);
1488 attrExt.classIndex = htods(0);
1489 attrExt.styleIndex = htods(0);
1490 for (i=0; i<NA; i++) {
1491 ssize_t idx = mAttributeOrder.valueAt(i);
1492 const attribute_entry& ae = mAttributes.itemAt(idx);
1493 if (ae.ns.size() == 0) {
1494 if (ae.name == id16) {
1495 attrExt.idIndex = htods(i+1);
1496 } else if (ae.name == class16) {
1497 attrExt.classIndex = htods(i+1);
1498 } else if (ae.name == style16) {
1499 attrExt.styleIndex = htods(i+1);
1500 }
1501 }
1502 }
1503 } else if (type == TYPE_NAMESPACE) {
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001504 if (mNamespaceUri == RESOURCES_TOOLS_NAMESPACE) {
1505 writeCurrentNode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 } else {
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001507 node.header.type = htods(RES_XML_START_NAMESPACE_TYPE);
1508 extData = &namespaceExt;
1509 extSize = sizeof(namespaceExt);
1510 memset(&namespaceExt, 0, sizeof(namespaceExt));
1511 if (mNamespacePrefix.size() > 0) {
1512 namespaceExt.prefix.index = htodl(strings.offsetForString(mNamespacePrefix));
1513 } else {
1514 namespaceExt.prefix.index = htodl((uint32_t)-1);
1515 }
1516 namespaceExt.prefix.index = htodl(strings.offsetForString(mNamespacePrefix));
1517 namespaceExt.uri.index = htodl(strings.offsetForString(mNamespaceUri));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 LOG_ALWAYS_FATAL_IF(NA != 0, "Namespace nodes can't have attributes!");
1520 } else if (type == TYPE_CDATA) {
1521 node.header.type = htods(RES_XML_CDATA_TYPE);
1522 extData = &cdataExt;
1523 extSize = sizeof(cdataExt);
1524 memset(&cdataExt, 0, sizeof(cdataExt));
1525 cdataExt.data.index = htodl(strings.offsetForString(mChars));
1526 cdataExt.typedData.size = htods(sizeof(cdataExt.typedData));
1527 cdataExt.typedData.res0 = 0;
1528 cdataExt.typedData.dataType = mCharsValue.dataType;
1529 cdataExt.typedData.data = htodl(mCharsValue.data);
1530 LOG_ALWAYS_FATAL_IF(NA != 0, "CDATA nodes can't have attributes!");
1531 }
1532
1533 node.header.size = htodl(sizeof(node) + extSize + (sizeof(attr)*NA));
1534
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001535 if (writeCurrentNode) {
1536 dest->writeData(&node, sizeof(node));
1537 if (extSize > 0) {
1538 dest->writeData(extData, extSize);
1539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541
1542 for (i=0; i<NA; i++) {
1543 ssize_t idx = mAttributeOrder.valueAt(i);
1544 const attribute_entry& ae = mAttributes.itemAt(idx);
1545 if (ae.ns.size() > 0) {
1546 attr.ns.index = htodl(strings.offsetForString(ae.ns));
1547 } else {
1548 attr.ns.index = htodl((uint32_t)-1);
1549 }
1550 attr.name.index = htodl(ae.namePoolIdx);
1551
1552 if (!stripRawValues || ae.needStringValue()) {
1553 attr.rawValue.index = htodl(strings.offsetForString(ae.string));
1554 } else {
1555 attr.rawValue.index = htodl((uint32_t)-1);
1556 }
1557 attr.typedValue.size = htods(sizeof(attr.typedValue));
1558 if (ae.value.dataType == Res_value::TYPE_NULL
1559 || ae.value.dataType == Res_value::TYPE_STRING) {
1560 attr.typedValue.res0 = 0;
1561 attr.typedValue.dataType = Res_value::TYPE_STRING;
1562 attr.typedValue.data = htodl(strings.offsetForString(ae.string));
1563 } else {
1564 attr.typedValue.res0 = 0;
1565 attr.typedValue.dataType = ae.value.dataType;
1566 attr.typedValue.data = htodl(ae.value.data);
1567 }
1568 dest->writeData(&attr, sizeof(attr));
1569 }
1570
1571 for (i=0; i<NC; i++) {
1572 status_t err = mChildren.itemAt(i)->flatten_node(strings, dest,
1573 stripComments, stripRawValues);
1574 if (err != NO_ERROR) {
1575 return err;
1576 }
1577 }
1578
1579 if (type == TYPE_ELEMENT) {
1580 ResXMLTree_endElementExt endElementExt;
1581 memset(&endElementExt, 0, sizeof(endElementExt));
1582 node.header.type = htods(RES_XML_END_ELEMENT_TYPE);
1583 node.header.size = htodl(sizeof(node)+sizeof(endElementExt));
1584 node.lineNumber = htodl(getEndLineNumber());
1585 node.comment.index = htodl((uint32_t)-1);
1586 endElementExt.ns.index = attrExt.ns.index;
1587 endElementExt.name.index = attrExt.name.index;
1588 dest->writeData(&node, sizeof(node));
1589 dest->writeData(&endElementExt, sizeof(endElementExt));
1590 } else if (type == TYPE_NAMESPACE) {
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001591 if (writeCurrentNode) {
1592 node.header.type = htods(RES_XML_END_NAMESPACE_TYPE);
1593 node.lineNumber = htodl(getEndLineNumber());
1594 node.comment.index = htodl((uint32_t)-1);
1595 node.header.size = htodl(sizeof(node)+extSize);
1596 dest->writeData(&node, sizeof(node));
1597 dest->writeData(extData, extSize);
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600
1601 return NO_ERROR;
1602}