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