blob: cda24ebe88be136f0bd835573de1f32044d3d199 [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.
21#if HAVE_PRINTF_ZD
22# 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;
216 const char* errorMsg;
217 int xliffDepth = 0;
218 bool firstTime = true;
219
220 size_t len;
221 ResXMLTree::event_code_t code;
Anton Krumina2ef5c02014-03-12 14:46:44 -0700222 // Bracketing if pseudolocalization accented method specified.
223 if (pseudolocalize == PSEUDO_ACCENTED) {
224 curString.append(String16(String8("[")));
225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 while ((code=inXml->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 if (code == ResXMLTree::TEXT) {
228 String16 text(inXml->getText(&len));
229 if (firstTime && text.size() > 0) {
230 firstTime = false;
231 if (text.string()[0] == '@') {
232 // If this is a resource reference, don't do the pseudoloc.
Anton Krumina2ef5c02014-03-12 14:46:44 -0700233 pseudolocalize = NO_PSEUDOLOCALIZATION;
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) {
237 String16 pseudo;
238 if (pseudolocalize == PSEUDO_ACCENTED) {
239 pseudo = pseudolocalize_string(text);
240 } else if (pseudolocalize == PSEUDO_BIDI) {
241 pseudo = pseudobidi_string(text);
242 } else {
243 pseudo = text;
244 }
245 curString.append(pseudo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 } else {
Kenny Root15fe2cb2010-05-28 15:44:32 -0700247 if (isFormatted && hasSubstitutionErrors(fileName, inXml, text) != NO_ERROR) {
248 return UNKNOWN_ERROR;
249 } else {
250 curString.append(text);
251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 }
253 } else if (code == ResXMLTree::START_TAG) {
254 const String16 element16(inXml->getElementName(&len));
255 const String8 element8(element16);
256
257 size_t nslen;
Dan Albertf348c152014-09-08 18:28:00 -0700258 const char16_t* ns = inXml->getElementNamespace(&nslen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 if (ns == NULL) {
Dan Albertf348c152014-09-08 18:28:00 -0700260 ns = (const char16_t*)"\0\0";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 nslen = 0;
262 }
263 const String8 nspace(String16(ns, nslen));
264 if (nspace == XLIFF_XMLNS) {
265 const int N = sizeof(ALLOWED_XLIFF_ELEMENTS)/sizeof(ALLOWED_XLIFF_ELEMENTS[0]);
266 for (int i=0; i<N; i++) {
267 if (element8 == ALLOWED_XLIFF_ELEMENTS[i]) {
268 xliffDepth++;
269 // in this case, treat it like it was just text, in other words, do nothing
270 // here and silently drop this element
271 goto moveon;
272 }
273 }
274 {
275 SourcePos(String8(fileName), inXml->getLineNumber()).error(
276 "Found unsupported XLIFF tag <%s>\n",
277 element8.string());
278 return UNKNOWN_ERROR;
279 }
280moveon:
281 continue;
282 }
283
284 if (outSpans == NULL) {
285 SourcePos(String8(fileName), inXml->getLineNumber()).error(
286 "Found style tag <%s> where styles are not allowed\n", element8.string());
287 return UNKNOWN_ERROR;
288 }
289
290 if (!ResTable::collectString(outString, curString.string(),
291 curString.size(), false, &errorMsg, true)) {
292 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
293 errorMsg, String8(curString).string());
294 return UNKNOWN_ERROR;
295 }
296 rawString.append(curString);
297 curString = String16();
298
299 StringPool::entry_style_span span;
300 span.name = element16;
301 for (size_t ai=0; ai<inXml->getAttributeCount(); ai++) {
302 span.name.append(String16(";"));
303 const char16_t* str = inXml->getAttributeName(ai, &len);
304 span.name.append(str, len);
305 span.name.append(String16("="));
306 str = inXml->getAttributeStringValue(ai, &len);
307 span.name.append(str, len);
308 }
309 //printf("Span: %s\n", String8(span.name).string());
310 span.span.firstChar = span.span.lastChar = outString->size();
311 spanStack.push(span);
312
313 } else if (code == ResXMLTree::END_TAG) {
314 size_t nslen;
Dan Albertf348c152014-09-08 18:28:00 -0700315 const char16_t* ns = inXml->getElementNamespace(&nslen);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 if (ns == NULL) {
Dan Albertf348c152014-09-08 18:28:00 -0700317 ns = (const char16_t*)"\0\0";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 nslen = 0;
319 }
320 const String8 nspace(String16(ns, nslen));
321 if (nspace == XLIFF_XMLNS) {
322 xliffDepth--;
323 continue;
324 }
325 if (!ResTable::collectString(outString, curString.string(),
326 curString.size(), false, &errorMsg, true)) {
327 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
328 errorMsg, String8(curString).string());
329 return UNKNOWN_ERROR;
330 }
331 rawString.append(curString);
332 curString = String16();
333
334 if (spanStack.size() == 0) {
335 if (strcmp16(inXml->getElementName(&len), endTag.string()) != 0) {
336 SourcePos(String8(fileName), inXml->getLineNumber()).error(
337 "Found tag %s where <%s> close is expected\n",
338 String8(inXml->getElementName(&len)).string(),
339 String8(endTag).string());
340 return UNKNOWN_ERROR;
341 }
342 break;
343 }
344 StringPool::entry_style_span span = spanStack.top();
345 String16 spanTag;
346 ssize_t semi = span.name.findFirst(';');
347 if (semi >= 0) {
348 spanTag.setTo(span.name.string(), semi);
349 } else {
350 spanTag.setTo(span.name);
351 }
352 if (strcmp16(inXml->getElementName(&len), spanTag.string()) != 0) {
353 SourcePos(String8(fileName), inXml->getLineNumber()).error(
354 "Found close tag %s where close tag %s is expected\n",
355 String8(inXml->getElementName(&len)).string(),
356 String8(spanTag).string());
357 return UNKNOWN_ERROR;
358 }
359 bool empty = true;
360 if (outString->size() > 0) {
361 span.span.lastChar = outString->size()-1;
362 if (span.span.lastChar >= span.span.firstChar) {
363 empty = false;
364 outSpans->add(span);
365 }
366 }
367 spanStack.pop();
368
Eric Fischerc87d2522009-09-01 15:20:30 -0700369 /*
370 * This warning seems to be just an irritation to most people,
371 * since it is typically introduced by translators who then never
372 * see the warning.
373 */
374 if (0 && empty) {
Marco Nelissendd931862009-07-13 13:02:33 -0700375 fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 fileName, inXml->getLineNumber(),
377 String8(spanTag).string(), String8(*outString).string());
378
379 }
380 } else if (code == ResXMLTree::START_NAMESPACE) {
381 // nothing
382 }
383 }
384
Anton Krumina2ef5c02014-03-12 14:46:44 -0700385 // Bracketing if pseudolocalization accented method specified.
386 if (pseudolocalize == PSEUDO_ACCENTED) {
387 const char16_t* str = outString->string();
388 const char16_t* p = str;
389 const char16_t* e = p + outString->size();
390 int words_cnt = 0;
391 while (p < e) {
392 if (isspace(*p)) {
393 words_cnt++;
394 }
395 p++;
396 }
397 unsigned int length = words_cnt > 3 ? outString->size() :
398 outString->size() / 2;
399 curString.append(String16(String8(" ")));
400 curString.append(pseudo_generate_expansion(length));
401 curString.append(String16(String8("]")));
402 }
403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 if (code == ResXMLTree::BAD_DOCUMENT) {
405 SourcePos(String8(fileName), inXml->getLineNumber()).error(
406 "Error parsing XML\n");
407 }
408
409 if (outSpans != NULL && outSpans->size() > 0) {
410 if (curString.size() > 0) {
411 if (!ResTable::collectString(outString, curString.string(),
412 curString.size(), false, &errorMsg, true)) {
413 SourcePos(String8(fileName), inXml->getLineNumber()).error(
414 "%s (in %s)\n",
415 errorMsg, String8(curString).string());
416 return UNKNOWN_ERROR;
417 }
418 }
419 } else {
420 // There is no style information, so string processing will happen
421 // later as part of the overall type conversion. Return to the
422 // client the raw unprocessed text.
423 rawString.append(curString);
424 outString->setTo(rawString);
425 }
426
427 return NO_ERROR;
428}
429
430struct namespace_entry {
431 String8 prefix;
432 String8 uri;
433};
434
435static String8 make_prefix(int depth)
436{
437 String8 prefix;
438 int i;
439 for (i=0; i<depth; i++) {
440 prefix.append(" ");
441 }
442 return prefix;
443}
444
445static String8 build_namespace(const Vector<namespace_entry>& namespaces,
Dan Albertf348c152014-09-08 18:28:00 -0700446 const char16_t* ns)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447{
448 String8 str;
449 if (ns != NULL) {
450 str = String8(ns);
451 const size_t N = namespaces.size();
452 for (size_t i=0; i<N; i++) {
453 const namespace_entry& ne = namespaces.itemAt(i);
454 if (ne.uri == str) {
455 str = ne.prefix;
456 break;
457 }
458 }
459 str.append(":");
460 }
461 return str;
462}
463
464void printXMLBlock(ResXMLTree* block)
465{
466 block->restart();
467
468 Vector<namespace_entry> namespaces;
469
470 ResXMLTree::event_code_t code;
471 int depth = 0;
472 while ((code=block->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
473 String8 prefix = make_prefix(depth);
474 int i;
475 if (code == ResXMLTree::START_TAG) {
476 size_t len;
Dan Albertf348c152014-09-08 18:28:00 -0700477 const char16_t* ns16 = block->getElementNamespace(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 String8 elemNs = build_namespace(namespaces, ns16);
Dan Albertf348c152014-09-08 18:28:00 -0700479 const char16_t* com16 = block->getComment(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 if (com16) {
481 printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string());
482 }
483 printf("%sE: %s%s (line=%d)\n", prefix.string(), elemNs.string(),
484 String8(block->getElementName(&len)).string(),
485 block->getLineNumber());
486 int N = block->getAttributeCount();
487 depth++;
488 prefix = make_prefix(depth);
489 for (i=0; i<N; i++) {
490 uint32_t res = block->getAttributeNameResID(i);
491 ns16 = block->getAttributeNamespace(i, &len);
492 String8 ns = build_namespace(namespaces, ns16);
493 String8 name(block->getAttributeName(i, &len));
494 printf("%sA: ", prefix.string());
495 if (res) {
496 printf("%s%s(0x%08x)", ns.string(), name.string(), res);
497 } else {
498 printf("%s%s", ns.string(), name.string());
499 }
500 Res_value value;
501 block->getAttributeValue(i, &value);
502 if (value.dataType == Res_value::TYPE_NULL) {
503 printf("=(null)");
504 } else if (value.dataType == Res_value::TYPE_REFERENCE) {
505 printf("=@0x%x", (int)value.data);
506 } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
507 printf("=?0x%x", (int)value.data);
508 } else if (value.dataType == Res_value::TYPE_STRING) {
509 printf("=\"%s\"",
Shachar Shemesh9872bf42010-12-20 17:38:33 +0200510 ResTable::normalizeForOutput(String8(block->getAttributeStringValue(i,
511 &len)).string()).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 } else {
513 printf("=(type 0x%x)0x%x", (int)value.dataType, (int)value.data);
514 }
515 const char16_t* val = block->getAttributeStringValue(i, &len);
516 if (val != NULL) {
Shachar Shemesh9872bf42010-12-20 17:38:33 +0200517 printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).string()).
518 string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 }
520 printf("\n");
521 }
522 } else if (code == ResXMLTree::END_TAG) {
523 depth--;
524 } else if (code == ResXMLTree::START_NAMESPACE) {
525 namespace_entry ns;
526 size_t len;
Dan Albertf348c152014-09-08 18:28:00 -0700527 const char16_t* prefix16 = block->getNamespacePrefix(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 if (prefix16) {
529 ns.prefix = String8(prefix16);
530 } else {
531 ns.prefix = "<DEF>";
532 }
533 ns.uri = String8(block->getNamespaceUri(&len));
534 namespaces.push(ns);
535 printf("%sN: %s=%s\n", prefix.string(), ns.prefix.string(),
536 ns.uri.string());
537 depth++;
538 } else if (code == ResXMLTree::END_NAMESPACE) {
539 depth--;
540 const namespace_entry& ns = namespaces.top();
541 size_t len;
Dan Albertf348c152014-09-08 18:28:00 -0700542 const char16_t* prefix16 = block->getNamespacePrefix(&len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 String8 pr;
544 if (prefix16) {
545 pr = String8(prefix16);
546 } else {
547 pr = "<DEF>";
548 }
549 if (ns.prefix != pr) {
550 prefix = make_prefix(depth);
551 printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
552 prefix.string(), pr.string(), ns.prefix.string());
553 }
554 String8 uri = String8(block->getNamespaceUri(&len));
555 if (ns.uri != uri) {
556 prefix = make_prefix(depth);
557 printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
558 prefix.string(), uri.string(), ns.uri.string());
559 }
560 namespaces.pop();
561 } else if (code == ResXMLTree::TEXT) {
562 size_t len;
Shachar Shemesh429dad62012-07-08 06:37:48 +0300563 printf("%sC: \"%s\"\n", prefix.string(),
564 ResTable::normalizeForOutput(String8(block->getText(&len)).string()).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 }
566 }
567
568 block->restart();
569}
570
571status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree,
572 bool stripAll, bool keepComments,
573 const char** cDataTags)
574{
575 sp<XMLNode> root = XMLNode::parse(file);
576 if (root == NULL) {
577 return UNKNOWN_ERROR;
578 }
579 root->removeWhitespace(stripAll, cDataTags);
580
Andreas Gampe2412f842014-09-30 20:55:57 -0700581 if (kIsDebug) {
582 printf("Input XML from %s:\n", (const char*)file->getPrintableSource());
583 root->print();
584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8());
586 status_t err = root->flatten(rsc, !keepComments, false);
587 if (err != NO_ERROR) {
588 return err;
589 }
590 err = outTree->setTo(rsc->getData(), rsc->getSize(), true);
591 if (err != NO_ERROR) {
592 return err;
593 }
594
Andreas Gampe2412f842014-09-30 20:55:57 -0700595 if (kIsDebug) {
596 printf("Output XML:\n");
597 printXMLBlock(outTree);
598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599
600 return NO_ERROR;
601}
602
603sp<XMLNode> XMLNode::parse(const sp<AaptFile>& file)
604{
605 char buf[16384];
606 int fd = open(file->getSourceFile().string(), O_RDONLY | O_BINARY);
607 if (fd < 0) {
608 SourcePos(file->getSourceFile(), -1).error("Unable to open file for read: %s",
609 strerror(errno));
610 return NULL;
611 }
612
613 XML_Parser parser = XML_ParserCreateNS(NULL, 1);
614 ParseState state;
615 state.filename = file->getPrintableSource();
616 state.parser = parser;
617 XML_SetUserData(parser, &state);
618 XML_SetElementHandler(parser, startElement, endElement);
619 XML_SetNamespaceDeclHandler(parser, startNamespace, endNamespace);
620 XML_SetCharacterDataHandler(parser, characterData);
621 XML_SetCommentHandler(parser, commentData);
622
623 ssize_t len;
624 bool done;
625 do {
626 len = read(fd, buf, sizeof(buf));
627 done = len < (ssize_t)sizeof(buf);
628 if (len < 0) {
629 SourcePos(file->getSourceFile(), -1).error("Error reading file: %s\n", strerror(errno));
630 close(fd);
631 return NULL;
632 }
633 if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
634 SourcePos(file->getSourceFile(), (int)XML_GetCurrentLineNumber(parser)).error(
635 "Error parsing XML: %s\n", XML_ErrorString(XML_GetErrorCode(parser)));
636 close(fd);
637 return NULL;
638 }
639 } while (!done);
640
641 XML_ParserFree(parser);
642 if (state.root == NULL) {
643 SourcePos(file->getSourceFile(), -1).error("No XML data generated when parsing");
644 }
645 close(fd);
646 return state.root;
647}
648
649XMLNode::XMLNode(const String8& filename, const String16& s1, const String16& s2, bool isNamespace)
650 : mNextAttributeIndex(0x80000000)
651 , mFilename(filename)
652 , mStartLineNumber(0)
653 , mEndLineNumber(0)
Kenny Root19138462009-12-04 09:38:48 -0800654 , mUTF8(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655{
656 if (isNamespace) {
657 mNamespacePrefix = s1;
658 mNamespaceUri = s2;
659 } else {
660 mNamespaceUri = s1;
661 mElementName = s2;
662 }
663}
664
665XMLNode::XMLNode(const String8& filename)
666 : mFilename(filename)
667{
Marco Nelissen6a1fade2009-04-20 16:16:01 -0700668 memset(&mCharsValue, 0, sizeof(mCharsValue));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669}
670
671XMLNode::type XMLNode::getType() const
672{
673 if (mElementName.size() != 0) {
674 return TYPE_ELEMENT;
675 }
676 if (mNamespaceUri.size() != 0) {
677 return TYPE_NAMESPACE;
678 }
679 return TYPE_CDATA;
680}
681
682const String16& XMLNode::getNamespacePrefix() const
683{
684 return mNamespacePrefix;
685}
686
687const String16& XMLNode::getNamespaceUri() const
688{
689 return mNamespaceUri;
690}
691
692const String16& XMLNode::getElementNamespace() const
693{
694 return mNamespaceUri;
695}
696
697const String16& XMLNode::getElementName() const
698{
699 return mElementName;
700}
701
702const Vector<sp<XMLNode> >& XMLNode::getChildren() const
703{
704 return mChildren;
705}
706
Dianne Hackborn62da8462009-05-13 15:06:13 -0700707const String8& XMLNode::getFilename() const
708{
709 return mFilename;
710}
711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712const Vector<XMLNode::attribute_entry>&
713 XMLNode::getAttributes() const
714{
715 return mAttributes;
716}
717
Dianne Hackborn62da8462009-05-13 15:06:13 -0700718const XMLNode::attribute_entry* XMLNode::getAttribute(const String16& ns,
719 const String16& name) const
720{
721 for (size_t i=0; i<mAttributes.size(); i++) {
722 const attribute_entry& ae(mAttributes.itemAt(i));
723 if (ae.ns == ns && ae.name == name) {
724 return &ae;
725 }
726 }
727
728 return NULL;
729}
730
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600731XMLNode::attribute_entry* XMLNode::editAttribute(const String16& ns,
732 const String16& name)
733{
734 for (size_t i=0; i<mAttributes.size(); i++) {
735 attribute_entry * ae = &mAttributes.editItemAt(i);
736 if (ae->ns == ns && ae->name == name) {
737 return ae;
738 }
739 }
740
741 return NULL;
742}
743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744const String16& XMLNode::getCData() const
745{
746 return mChars;
747}
748
749const String16& XMLNode::getComment() const
750{
751 return mComment;
752}
753
754int32_t XMLNode::getStartLineNumber() const
755{
756 return mStartLineNumber;
757}
758
759int32_t XMLNode::getEndLineNumber() const
760{
761 return mEndLineNumber;
762}
763
Dianne Hackborn62da8462009-05-13 15:06:13 -0700764sp<XMLNode> XMLNode::searchElement(const String16& tagNamespace, const String16& tagName)
765{
766 if (getType() == XMLNode::TYPE_ELEMENT
767 && mNamespaceUri == tagNamespace
768 && mElementName == tagName) {
769 return this;
770 }
771
772 for (size_t i=0; i<mChildren.size(); i++) {
773 sp<XMLNode> found = mChildren.itemAt(i)->searchElement(tagNamespace, tagName);
774 if (found != NULL) {
775 return found;
776 }
777 }
778
779 return NULL;
780}
781
782sp<XMLNode> XMLNode::getChildElement(const String16& tagNamespace, const String16& tagName)
783{
784 for (size_t i=0; i<mChildren.size(); i++) {
785 sp<XMLNode> child = mChildren.itemAt(i);
786 if (child->getType() == XMLNode::TYPE_ELEMENT
787 && child->mNamespaceUri == tagNamespace
788 && child->mElementName == tagName) {
789 return child;
790 }
791 }
792
793 return NULL;
794}
795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796status_t XMLNode::addChild(const sp<XMLNode>& child)
797{
798 if (getType() == TYPE_CDATA) {
799 SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
800 return UNKNOWN_ERROR;
801 }
802 //printf("Adding child %p to parent %p\n", child.get(), this);
803 mChildren.add(child);
804 return NO_ERROR;
805}
806
Dianne Hackborn62da8462009-05-13 15:06:13 -0700807status_t XMLNode::insertChildAt(const sp<XMLNode>& child, size_t index)
808{
809 if (getType() == TYPE_CDATA) {
810 SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
811 return UNKNOWN_ERROR;
812 }
813 //printf("Adding child %p to parent %p\n", child.get(), this);
814 mChildren.insertAt(child, index);
815 return NO_ERROR;
816}
817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818status_t XMLNode::addAttribute(const String16& ns, const String16& name,
819 const String16& value)
820{
821 if (getType() == TYPE_CDATA) {
822 SourcePos(mFilename, getStartLineNumber()).error("Child to CDATA node.");
823 return UNKNOWN_ERROR;
824 }
Xavier Ducrohetf8aea992012-02-02 17:18:18 -0800825
826 if (ns != RESOURCES_TOOLS_NAMESPACE) {
827 attribute_entry e;
828 e.index = mNextAttributeIndex++;
829 e.ns = ns;
830 e.name = name;
831 e.string = value;
832 mAttributes.add(e);
833 mAttributeOrder.add(e.index, mAttributes.size()-1);
834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 return NO_ERROR;
836}
837
838void XMLNode::setAttributeResID(size_t attrIdx, uint32_t resId)
839{
840 attribute_entry& e = mAttributes.editItemAt(attrIdx);
841 if (e.nameResId) {
842 mAttributeOrder.removeItem(e.nameResId);
843 } else {
844 mAttributeOrder.removeItem(e.index);
845 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700846 if (kIsDebug) {
847 printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
848 String8(getElementName()).string(),
849 String8(mAttributes.itemAt(attrIdx).name).string(),
850 String8(mAttributes.itemAt(attrIdx).string).string(),
851 resId);
852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 mAttributes.editItemAt(attrIdx).nameResId = resId;
854 mAttributeOrder.add(resId, attrIdx);
855}
856
857status_t XMLNode::appendChars(const String16& chars)
858{
859 if (getType() != TYPE_CDATA) {
860 SourcePos(mFilename, getStartLineNumber()).error("Adding characters to element node.");
861 return UNKNOWN_ERROR;
862 }
863 mChars.append(chars);
864 return NO_ERROR;
865}
866
867status_t XMLNode::appendComment(const String16& comment)
868{
869 if (mComment.size() > 0) {
870 mComment.append(String16("\n"));
871 }
872 mComment.append(comment);
873 return NO_ERROR;
874}
875
876void XMLNode::setStartLineNumber(int32_t line)
877{
878 mStartLineNumber = line;
879}
880
881void XMLNode::setEndLineNumber(int32_t line)
882{
883 mEndLineNumber = line;
884}
885
886void XMLNode::removeWhitespace(bool stripAll, const char** cDataTags)
887{
888 //printf("Removing whitespace in %s\n", String8(mElementName).string());
889 size_t N = mChildren.size();
890 if (cDataTags) {
891 String8 tag(mElementName);
892 const char** p = cDataTags;
893 while (*p) {
894 if (tag == *p) {
895 stripAll = false;
896 break;
897 }
898 }
899 }
900 for (size_t i=0; i<N; i++) {
901 sp<XMLNode> node = mChildren.itemAt(i);
902 if (node->getType() == TYPE_CDATA) {
903 // This is a CDATA node...
904 const char16_t* p = node->mChars.string();
905 while (*p != 0 && *p < 128 && isspace(*p)) {
906 p++;
907 }
908 //printf("Space ends at %d in \"%s\"\n",
909 // (int)(p-node->mChars.string()),
910 // String8(node->mChars).string());
911 if (*p == 0) {
912 if (stripAll) {
913 // Remove this node!
914 mChildren.removeAt(i);
915 N--;
916 i--;
917 } else {
918 node->mChars = String16(" ");
919 }
920 } else {
921 // Compact leading/trailing whitespace.
922 const char16_t* e = node->mChars.string()+node->mChars.size()-1;
923 while (e > p && *e < 128 && isspace(*e)) {
924 e--;
925 }
926 if (p > node->mChars.string()) {
927 p--;
928 }
929 if (e < (node->mChars.string()+node->mChars.size()-1)) {
930 e++;
931 }
932 if (p > node->mChars.string() ||
933 e < (node->mChars.string()+node->mChars.size()-1)) {
934 String16 tmp(p, e-p+1);
935 node->mChars = tmp;
936 }
937 }
938 } else {
939 node->removeWhitespace(stripAll, cDataTags);
940 }
941 }
942}
943
944status_t XMLNode::parseValues(const sp<AaptAssets>& assets,
945 ResourceTable* table)
946{
947 bool hasErrors = false;
948
949 if (getType() == TYPE_ELEMENT) {
950 const size_t N = mAttributes.size();
951 String16 defPackage(assets->getPackage());
952 for (size_t i=0; i<N; i++) {
953 attribute_entry& e = mAttributes.editItemAt(i);
954 AccessorCookie ac(SourcePos(mFilename, getStartLineNumber()), String8(e.name),
955 String8(e.string));
956 table->setCurrentXmlPos(SourcePos(mFilename, getStartLineNumber()));
957 if (!assets->getIncludedResources()
958 .stringToValue(&e.value, &e.string,
959 e.string.string(), e.string.size(), true, true,
960 e.nameResId, NULL, &defPackage, table, &ac)) {
961 hasErrors = true;
962 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700963 if (kIsDebug) {
964 printf("Attr %s: type=0x%x, str=%s\n",
965 String8(e.name).string(), e.value.dataType,
966 String8(e.string).string());
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969 }
970 const size_t N = mChildren.size();
971 for (size_t i=0; i<N; i++) {
972 status_t err = mChildren.itemAt(i)->parseValues(assets, table);
973 if (err != NO_ERROR) {
974 hasErrors = true;
975 }
976 }
Andreas Gampe2412f842014-09-30 20:55:57 -0700977 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978}
979
980status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets,
981 const ResourceTable* table)
982{
983 bool hasErrors = false;
984
985 if (getType() == TYPE_ELEMENT) {
986 String16 attr("attr");
987 const char* errorMsg;
988 const size_t N = mAttributes.size();
989 for (size_t i=0; i<N; i++) {
990 const attribute_entry& e = mAttributes.itemAt(i);
991 if (e.ns.size() <= 0) continue;
Andreas Gampeb8dc7bc2014-10-01 19:07:51 -0700992 bool nsIsPublic = true;
inazaruke3489092011-05-22 15:09:06 -0700993 String16 pkg(getNamespaceResourcePackage(String16(assets->getPackage()), e.ns, &nsIsPublic));
Andreas Gampe2412f842014-09-30 20:55:57 -0700994 if (kIsDebug) {
995 printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
996 String8(getElementName()).string(),
997 String8(e.name).string(),
998 String8(e.string).string(),
999 String8(e.ns).string(),
1000 (nsIsPublic) ? "public" : "private",
1001 String8(pkg).string());
1002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 if (pkg.size() <= 0) continue;
1004 uint32_t res = table != NULL
1005 ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic)
1006 : assets->getIncludedResources().
1007 identifierForName(e.name.string(), e.name.size(),
1008 attr.string(), attr.size(),
1009 pkg.string(), pkg.size());
1010 if (res != 0) {
Andreas Gampe2412f842014-09-30 20:55:57 -07001011 if (kIsDebug) {
1012 printf("XML attribute name %s: resid=0x%08x\n",
1013 String8(e.name).string(), res);
1014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 setAttributeResID(i, res);
1016 } else {
1017 SourcePos(mFilename, getStartLineNumber()).error(
1018 "No resource identifier found for attribute '%s' in package '%s'\n",
1019 String8(e.name).string(), String8(pkg).string());
1020 hasErrors = true;
1021 }
1022 }
1023 }
1024 const size_t N = mChildren.size();
1025 for (size_t i=0; i<N; i++) {
1026 status_t err = mChildren.itemAt(i)->assignResourceIds(assets, table);
1027 if (err < NO_ERROR) {
1028 hasErrors = true;
1029 }
1030 }
1031
Andreas Gampe2412f842014-09-30 20:55:57 -07001032 return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033}
1034
1035status_t XMLNode::flatten(const sp<AaptFile>& dest,
1036 bool stripComments, bool stripRawValues) const
1037{
Jeff Brown345b7eb2012-03-16 15:25:17 -07001038 StringPool strings(mUTF8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 Vector<uint32_t> resids;
1040
1041 // First collect just the strings for attribute names that have a
1042 // resource ID assigned to them. This ensures that the resource ID
1043 // array is compact, and makes it easier to deal with attribute names
1044 // in different namespaces (and thus with different resource IDs).
1045 collect_resid_strings(&strings, &resids);
1046
1047 // Next collect all remainibng strings.
1048 collect_strings(&strings, &resids, stripComments, stripRawValues);
1049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 sp<AaptFile> stringPool = strings.createStringBlock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051
1052 ResXMLTree_header header;
1053 memset(&header, 0, sizeof(header));
1054 header.header.type = htods(RES_XML_TYPE);
1055 header.header.headerSize = htods(sizeof(header));
1056
1057 const size_t basePos = dest->getSize();
1058 dest->writeData(&header, sizeof(header));
1059 dest->writeData(stringPool->getData(), stringPool->getSize());
1060
1061 // If we have resource IDs, write them.
1062 if (resids.size() > 0) {
1063 const size_t resIdsPos = dest->getSize();
1064 const size_t resIdsSize =
1065 sizeof(ResChunk_header)+(sizeof(uint32_t)*resids.size());
1066 ResChunk_header* idsHeader = (ResChunk_header*)
1067 (((const uint8_t*)dest->editData(resIdsPos+resIdsSize))+resIdsPos);
1068 idsHeader->type = htods(RES_XML_RESOURCE_MAP_TYPE);
1069 idsHeader->headerSize = htods(sizeof(*idsHeader));
1070 idsHeader->size = htodl(resIdsSize);
1071 uint32_t* ids = (uint32_t*)(idsHeader+1);
1072 for (size_t i=0; i<resids.size(); i++) {
1073 *ids++ = htodl(resids[i]);
1074 }
1075 }
1076
1077 flatten_node(strings, dest, stripComments, stripRawValues);
1078
1079 void* data = dest->editData();
1080 ResXMLTree_header* hd = (ResXMLTree_header*)(((uint8_t*)data)+basePos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 hd->header.size = htodl(dest->getSize()-basePos);
1082
Andreas Gampe2412f842014-09-30 20:55:57 -07001083 if (kPrintStringMetrics) {
1084 fprintf(stderr, "**** total xml size: %zu / %zu%% strings (in %s)\n",
1085 dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
1086 dest->getPath().string());
1087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088
1089 return NO_ERROR;
1090}
1091
1092void XMLNode::print(int indent)
1093{
1094 String8 prefix;
1095 int i;
1096 for (i=0; i<indent; i++) {
1097 prefix.append(" ");
1098 }
1099 if (getType() == TYPE_ELEMENT) {
1100 String8 elemNs(getNamespaceUri());
1101 if (elemNs.size() > 0) {
1102 elemNs.append(":");
1103 }
1104 printf("%s E: %s%s", prefix.string(),
1105 elemNs.string(), String8(getElementName()).string());
1106 int N = mAttributes.size();
1107 for (i=0; i<N; i++) {
1108 ssize_t idx = mAttributeOrder.valueAt(i);
1109 if (i == 0) {
1110 printf(" / ");
1111 } else {
1112 printf(", ");
1113 }
1114 const attribute_entry& attr = mAttributes.itemAt(idx);
1115 String8 attrNs(attr.ns);
1116 if (attrNs.size() > 0) {
1117 attrNs.append(":");
1118 }
1119 if (attr.nameResId) {
1120 printf("%s%s(0x%08x)", attrNs.string(),
1121 String8(attr.name).string(), attr.nameResId);
1122 } else {
1123 printf("%s%s", attrNs.string(), String8(attr.name).string());
1124 }
1125 printf("=%s", String8(attr.string).string());
1126 }
1127 printf("\n");
1128 } else if (getType() == TYPE_NAMESPACE) {
1129 printf("%s N: %s=%s\n", prefix.string(),
1130 getNamespacePrefix().size() > 0
1131 ? String8(getNamespacePrefix()).string() : "<DEF>",
1132 String8(getNamespaceUri()).string());
1133 } else {
1134 printf("%s C: \"%s\"\n", prefix.string(), String8(getCData()).string());
1135 }
1136 int N = mChildren.size();
1137 for (i=0; i<N; i++) {
1138 mChildren.itemAt(i)->print(indent+1);
1139 }
1140}
1141
1142static void splitName(const char* name, String16* outNs, String16* outName)
1143{
1144 const char* p = name;
1145 while (*p != 0 && *p != 1) {
1146 p++;
1147 }
1148 if (*p == 0) {
1149 *outNs = String16();
1150 *outName = String16(name);
1151 } else {
1152 *outNs = String16(name, (p-name));
1153 *outName = String16(p+1);
1154 }
1155}
1156
1157void XMLCALL
1158XMLNode::startNamespace(void *userData, const char *prefix, const char *uri)
1159{
Andreas Gampe2412f842014-09-30 20:55:57 -07001160 if (kIsDebugParse) {
1161 printf("Start Namespace: %s %s\n", prefix, uri);
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 ParseState* st = (ParseState*)userData;
1164 sp<XMLNode> node = XMLNode::newNamespace(st->filename,
1165 String16(prefix != NULL ? prefix : ""), String16(uri));
1166 node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1167 if (st->stack.size() > 0) {
1168 st->stack.itemAt(st->stack.size()-1)->addChild(node);
1169 } else {
1170 st->root = node;
1171 }
1172 st->stack.push(node);
1173}
1174
1175void XMLCALL
1176XMLNode::startElement(void *userData, const char *name, const char **atts)
1177{
Andreas Gampe2412f842014-09-30 20:55:57 -07001178 if (kIsDebugParse) {
1179 printf("Start Element: %s\n", name);
1180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 ParseState* st = (ParseState*)userData;
1182 String16 ns16, name16;
1183 splitName(name, &ns16, &name16);
1184 sp<XMLNode> node = XMLNode::newElement(st->filename, ns16, name16);
1185 node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1186 if (st->pendingComment.size() > 0) {
1187 node->appendComment(st->pendingComment);
1188 st->pendingComment = String16();
1189 }
1190 if (st->stack.size() > 0) {
1191 st->stack.itemAt(st->stack.size()-1)->addChild(node);
1192 } else {
1193 st->root = node;
1194 }
1195 st->stack.push(node);
1196
1197 for (int i = 0; atts[i]; i += 2) {
1198 splitName(atts[i], &ns16, &name16);
1199 node->addAttribute(ns16, name16, String16(atts[i+1]));
1200 }
1201}
1202
1203void XMLCALL
1204XMLNode::characterData(void *userData, const XML_Char *s, int len)
1205{
Andreas Gampe2412f842014-09-30 20:55:57 -07001206 if (kIsDebugParse) {
1207 printf("CDATA: \"%s\"\n", String8(s, len).string());
1208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 ParseState* st = (ParseState*)userData;
1210 sp<XMLNode> node = NULL;
1211 if (st->stack.size() == 0) {
1212 return;
1213 }
1214 sp<XMLNode> parent = st->stack.itemAt(st->stack.size()-1);
1215 if (parent != NULL && parent->getChildren().size() > 0) {
1216 node = parent->getChildren()[parent->getChildren().size()-1];
1217 if (node->getType() != TYPE_CDATA) {
1218 // Last node is not CDATA, need to make a new node.
1219 node = NULL;
1220 }
1221 }
1222
1223 if (node == NULL) {
1224 node = XMLNode::newCData(st->filename);
1225 node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1226 parent->addChild(node);
1227 }
1228
1229 node->appendChars(String16(s, len));
1230}
1231
1232void XMLCALL
1233XMLNode::endElement(void *userData, const char *name)
1234{
Andreas Gampe2412f842014-09-30 20:55:57 -07001235 if (kIsDebugParse) {
1236 printf("End Element: %s\n", name);
1237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 ParseState* st = (ParseState*)userData;
1239 sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
1240 node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
1241 if (st->pendingComment.size() > 0) {
1242 node->appendComment(st->pendingComment);
1243 st->pendingComment = String16();
1244 }
1245 String16 ns16, name16;
1246 splitName(name, &ns16, &name16);
1247 LOG_ALWAYS_FATAL_IF(node->getElementNamespace() != ns16
1248 || node->getElementName() != name16,
1249 "Bad end element %s", name);
1250 st->stack.pop();
1251}
1252
1253void XMLCALL
1254XMLNode::endNamespace(void *userData, const char *prefix)
1255{
1256 const char* nonNullPrefix = prefix != NULL ? prefix : "";
Andreas Gampe2412f842014-09-30 20:55:57 -07001257 if (kIsDebugParse) {
1258 printf("End Namespace: %s\n", prefix);
1259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 ParseState* st = (ParseState*)userData;
1261 sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
1262 node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
1263 LOG_ALWAYS_FATAL_IF(node->getNamespacePrefix() != String16(nonNullPrefix),
1264 "Bad end namespace %s", prefix);
1265 st->stack.pop();
1266}
1267
1268void XMLCALL
1269XMLNode::commentData(void *userData, const char *comment)
1270{
Andreas Gampe2412f842014-09-30 20:55:57 -07001271 if (kIsDebugParse) {
1272 printf("Comment: %s\n", comment);
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 ParseState* st = (ParseState*)userData;
1275 if (st->pendingComment.size() > 0) {
1276 st->pendingComment.append(String16("\n"));
1277 }
1278 st->pendingComment.append(String16(comment));
1279}
1280
1281status_t XMLNode::collect_strings(StringPool* dest, Vector<uint32_t>* outResIds,
1282 bool stripComments, bool stripRawValues) const
1283{
1284 collect_attr_strings(dest, outResIds, true);
1285
1286 int i;
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001287 if (RESOURCES_TOOLS_NAMESPACE != mNamespaceUri) {
1288 if (mNamespacePrefix.size() > 0) {
1289 dest->add(mNamespacePrefix, true);
1290 }
1291 if (mNamespaceUri.size() > 0) {
1292 dest->add(mNamespaceUri, true);
1293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
1295 if (mElementName.size() > 0) {
1296 dest->add(mElementName, true);
1297 }
1298
1299 if (!stripComments && mComment.size() > 0) {
1300 dest->add(mComment, true);
1301 }
1302
1303 const int NA = mAttributes.size();
1304
1305 for (i=0; i<NA; i++) {
1306 const attribute_entry& ae = mAttributes.itemAt(i);
1307 if (ae.ns.size() > 0) {
1308 dest->add(ae.ns, true);
1309 }
1310 if (!stripRawValues || ae.needStringValue()) {
1311 dest->add(ae.string, true);
1312 }
1313 /*
1314 if (ae.value.dataType == Res_value::TYPE_NULL
1315 || ae.value.dataType == Res_value::TYPE_STRING) {
1316 dest->add(ae.string, true);
1317 }
1318 */
1319 }
1320
1321 if (mElementName.size() == 0) {
1322 // If not an element, include the CDATA, even if it is empty.
1323 dest->add(mChars, true);
1324 }
1325
1326 const int NC = mChildren.size();
1327
1328 for (i=0; i<NC; i++) {
1329 mChildren.itemAt(i)->collect_strings(dest, outResIds,
1330 stripComments, stripRawValues);
1331 }
1332
1333 return NO_ERROR;
1334}
1335
1336status_t XMLNode::collect_attr_strings(StringPool* outPool,
1337 Vector<uint32_t>* outResIds, bool allAttrs) const {
1338 const int NA = mAttributes.size();
1339
1340 for (int i=0; i<NA; i++) {
1341 const attribute_entry& attr = mAttributes.itemAt(i);
1342 uint32_t id = attr.nameResId;
1343 if (id || allAttrs) {
1344 // See if we have already assigned this resource ID to a pooled
1345 // string...
1346 const Vector<size_t>* indices = outPool->offsetsForString(attr.name);
1347 ssize_t idx = -1;
1348 if (indices != NULL) {
1349 const int NJ = indices->size();
1350 const size_t NR = outResIds->size();
1351 for (int j=0; j<NJ; j++) {
1352 size_t strIdx = indices->itemAt(j);
1353 if (strIdx >= NR) {
1354 if (id == 0) {
1355 // We don't need to assign a resource ID for this one.
1356 idx = strIdx;
1357 break;
1358 }
1359 // Just ignore strings that are out of range of
1360 // the currently assigned resource IDs... we add
1361 // strings as we assign the first ID.
1362 } else if (outResIds->itemAt(strIdx) == id) {
1363 idx = strIdx;
1364 break;
1365 }
1366 }
1367 }
1368 if (idx < 0) {
1369 idx = outPool->add(attr.name);
Andreas Gampe2412f842014-09-30 20:55:57 -07001370 if (kIsDebug) {
1371 printf("Adding attr %s (resid 0x%08x) to pool: idx=%zd\n",
1372 String8(attr.name).string(), id, SSIZE(idx));
1373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (id != 0) {
1375 while ((ssize_t)outResIds->size() <= idx) {
1376 outResIds->add(0);
1377 }
1378 outResIds->replaceAt(id, idx);
1379 }
1380 }
1381 attr.namePoolIdx = idx;
Andreas Gampe2412f842014-09-30 20:55:57 -07001382 if (kIsDebug) {
1383 printf("String %s offset=0x%08zd\n", String8(attr.name).string(), SSIZE(idx));
1384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386 }
1387
1388 return NO_ERROR;
1389}
1390
1391status_t XMLNode::collect_resid_strings(StringPool* outPool,
1392 Vector<uint32_t>* outResIds) const
1393{
1394 collect_attr_strings(outPool, outResIds, false);
1395
1396 const int NC = mChildren.size();
1397
1398 for (int i=0; i<NC; i++) {
1399 mChildren.itemAt(i)->collect_resid_strings(outPool, outResIds);
1400 }
1401
1402 return NO_ERROR;
1403}
1404
1405status_t XMLNode::flatten_node(const StringPool& strings, const sp<AaptFile>& dest,
1406 bool stripComments, bool stripRawValues) const
1407{
1408 ResXMLTree_node node;
1409 ResXMLTree_cdataExt cdataExt;
1410 ResXMLTree_namespaceExt namespaceExt;
1411 ResXMLTree_attrExt attrExt;
1412 const void* extData = NULL;
1413 size_t extSize = 0;
1414 ResXMLTree_attribute attr;
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001415 bool writeCurrentNode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416
1417 const size_t NA = mAttributes.size();
1418 const size_t NC = mChildren.size();
1419 size_t i;
1420
1421 LOG_ALWAYS_FATAL_IF(NA != mAttributeOrder.size(), "Attributes messed up!");
1422
1423 const String16 id16("id");
1424 const String16 class16("class");
1425 const String16 style16("style");
1426
1427 const type type = getType();
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 memset(&node, 0, sizeof(node));
1430 memset(&attr, 0, sizeof(attr));
1431 node.header.headerSize = htods(sizeof(node));
1432 node.lineNumber = htodl(getStartLineNumber());
1433 if (!stripComments) {
1434 node.comment.index = htodl(
1435 mComment.size() > 0 ? strings.offsetForString(mComment) : -1);
1436 //if (mComment.size() > 0) {
1437 // printf("Flattening comment: %s\n", String8(mComment).string());
1438 //}
1439 } else {
1440 node.comment.index = htodl((uint32_t)-1);
1441 }
1442 if (type == TYPE_ELEMENT) {
1443 node.header.type = htods(RES_XML_START_ELEMENT_TYPE);
1444 extData = &attrExt;
1445 extSize = sizeof(attrExt);
1446 memset(&attrExt, 0, sizeof(attrExt));
1447 if (mNamespaceUri.size() > 0) {
1448 attrExt.ns.index = htodl(strings.offsetForString(mNamespaceUri));
1449 } else {
1450 attrExt.ns.index = htodl((uint32_t)-1);
1451 }
1452 attrExt.name.index = htodl(strings.offsetForString(mElementName));
1453 attrExt.attributeStart = htods(sizeof(attrExt));
1454 attrExt.attributeSize = htods(sizeof(attr));
1455 attrExt.attributeCount = htods(NA);
1456 attrExt.idIndex = htods(0);
1457 attrExt.classIndex = htods(0);
1458 attrExt.styleIndex = htods(0);
1459 for (i=0; i<NA; i++) {
1460 ssize_t idx = mAttributeOrder.valueAt(i);
1461 const attribute_entry& ae = mAttributes.itemAt(idx);
1462 if (ae.ns.size() == 0) {
1463 if (ae.name == id16) {
1464 attrExt.idIndex = htods(i+1);
1465 } else if (ae.name == class16) {
1466 attrExt.classIndex = htods(i+1);
1467 } else if (ae.name == style16) {
1468 attrExt.styleIndex = htods(i+1);
1469 }
1470 }
1471 }
1472 } else if (type == TYPE_NAMESPACE) {
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001473 if (mNamespaceUri == RESOURCES_TOOLS_NAMESPACE) {
1474 writeCurrentNode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 } else {
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001476 node.header.type = htods(RES_XML_START_NAMESPACE_TYPE);
1477 extData = &namespaceExt;
1478 extSize = sizeof(namespaceExt);
1479 memset(&namespaceExt, 0, sizeof(namespaceExt));
1480 if (mNamespacePrefix.size() > 0) {
1481 namespaceExt.prefix.index = htodl(strings.offsetForString(mNamespacePrefix));
1482 } else {
1483 namespaceExt.prefix.index = htodl((uint32_t)-1);
1484 }
1485 namespaceExt.prefix.index = htodl(strings.offsetForString(mNamespacePrefix));
1486 namespaceExt.uri.index = htodl(strings.offsetForString(mNamespaceUri));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 LOG_ALWAYS_FATAL_IF(NA != 0, "Namespace nodes can't have attributes!");
1489 } else if (type == TYPE_CDATA) {
1490 node.header.type = htods(RES_XML_CDATA_TYPE);
1491 extData = &cdataExt;
1492 extSize = sizeof(cdataExt);
1493 memset(&cdataExt, 0, sizeof(cdataExt));
1494 cdataExt.data.index = htodl(strings.offsetForString(mChars));
1495 cdataExt.typedData.size = htods(sizeof(cdataExt.typedData));
1496 cdataExt.typedData.res0 = 0;
1497 cdataExt.typedData.dataType = mCharsValue.dataType;
1498 cdataExt.typedData.data = htodl(mCharsValue.data);
1499 LOG_ALWAYS_FATAL_IF(NA != 0, "CDATA nodes can't have attributes!");
1500 }
1501
1502 node.header.size = htodl(sizeof(node) + extSize + (sizeof(attr)*NA));
1503
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001504 if (writeCurrentNode) {
1505 dest->writeData(&node, sizeof(node));
1506 if (extSize > 0) {
1507 dest->writeData(extData, extSize);
1508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510
1511 for (i=0; i<NA; i++) {
1512 ssize_t idx = mAttributeOrder.valueAt(i);
1513 const attribute_entry& ae = mAttributes.itemAt(idx);
1514 if (ae.ns.size() > 0) {
1515 attr.ns.index = htodl(strings.offsetForString(ae.ns));
1516 } else {
1517 attr.ns.index = htodl((uint32_t)-1);
1518 }
1519 attr.name.index = htodl(ae.namePoolIdx);
1520
1521 if (!stripRawValues || ae.needStringValue()) {
1522 attr.rawValue.index = htodl(strings.offsetForString(ae.string));
1523 } else {
1524 attr.rawValue.index = htodl((uint32_t)-1);
1525 }
1526 attr.typedValue.size = htods(sizeof(attr.typedValue));
1527 if (ae.value.dataType == Res_value::TYPE_NULL
1528 || ae.value.dataType == Res_value::TYPE_STRING) {
1529 attr.typedValue.res0 = 0;
1530 attr.typedValue.dataType = Res_value::TYPE_STRING;
1531 attr.typedValue.data = htodl(strings.offsetForString(ae.string));
1532 } else {
1533 attr.typedValue.res0 = 0;
1534 attr.typedValue.dataType = ae.value.dataType;
1535 attr.typedValue.data = htodl(ae.value.data);
1536 }
1537 dest->writeData(&attr, sizeof(attr));
1538 }
1539
1540 for (i=0; i<NC; i++) {
1541 status_t err = mChildren.itemAt(i)->flatten_node(strings, dest,
1542 stripComments, stripRawValues);
1543 if (err != NO_ERROR) {
1544 return err;
1545 }
1546 }
1547
1548 if (type == TYPE_ELEMENT) {
1549 ResXMLTree_endElementExt endElementExt;
1550 memset(&endElementExt, 0, sizeof(endElementExt));
1551 node.header.type = htods(RES_XML_END_ELEMENT_TYPE);
1552 node.header.size = htodl(sizeof(node)+sizeof(endElementExt));
1553 node.lineNumber = htodl(getEndLineNumber());
1554 node.comment.index = htodl((uint32_t)-1);
1555 endElementExt.ns.index = attrExt.ns.index;
1556 endElementExt.name.index = attrExt.name.index;
1557 dest->writeData(&node, sizeof(node));
1558 dest->writeData(&endElementExt, sizeof(endElementExt));
1559 } else if (type == TYPE_NAMESPACE) {
Xavier Ducrohetf8aea992012-02-02 17:18:18 -08001560 if (writeCurrentNode) {
1561 node.header.type = htods(RES_XML_END_NAMESPACE_TYPE);
1562 node.lineNumber = htodl(getEndLineNumber());
1563 node.comment.index = htodl((uint32_t)-1);
1564 node.header.size = htodl(sizeof(node)+extSize);
1565 dest->writeData(&node, sizeof(node));
1566 dest->writeData(extData, extSize);
1567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569
1570 return NO_ERROR;
1571}