2 // Copyright 2006 The Android Open Source Project
4 // Build resource files from raw assets.
8 #include "ResourceTable.h"
10 #include <host/pseudolocalize.h>
11 #include <utils/ByteOrder.h>
15 #ifndef HAVE_MS_C_RUNTIME
20 #define NOISY_PARSE(x) //x
22 const char* const RESOURCES_ROOT_NAMESPACE
= "http://schemas.android.com/apk/res/";
23 const char* const RESOURCES_ANDROID_NAMESPACE
= "http://schemas.android.com/apk/res/android";
24 const char* const RESOURCES_ROOT_PRV_NAMESPACE
= "http://schemas.android.com/apk/prv/res/";
26 const char* const XLIFF_XMLNS
= "urn:oasis:names:tc:xliff:document:1.2";
27 const char* const ALLOWED_XLIFF_ELEMENTS
[] = {
38 bool isWhitespace(const char16_t* str
)
40 while (*str
!= 0 && *str
< 128 && isspace(*str
)) {
46 static const String16
RESOURCES_PREFIX(RESOURCES_ROOT_NAMESPACE
);
47 static const String16
RESOURCES_PRV_PREFIX(RESOURCES_ROOT_PRV_NAMESPACE
);
49 String16
getNamespaceResourcePackage(String16 namespaceUri
, bool* outIsPublic
)
51 //printf("%s starts with %s?\n", String8(namespaceUri).string(),
52 // String8(RESOURCES_PREFIX).string());
55 if (namespaceUri
.startsWith(RESOURCES_PREFIX
)) {
56 prefixSize
= RESOURCES_PREFIX
.size();
57 } else if (namespaceUri
.startsWith(RESOURCES_PRV_PREFIX
)) {
59 prefixSize
= RESOURCES_PRV_PREFIX
.size();
61 if (outIsPublic
) *outIsPublic
= isPublic
; // = true
66 //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).string());
67 if (outIsPublic
) *outIsPublic
= isPublic
;
68 return String16(namespaceUri
, namespaceUri
.size()-prefixSize
, prefixSize
);
71 status_t
hasSubstitutionErrors(const char* fileName
,
75 const char16_t* str
= str16
.string();
76 const char16_t* p
= str
;
77 const char16_t* end
= str
+ str16
.size();
79 bool nonpositional
= false;
84 * Look for the start of a Java-style substitution sequence.
86 if (*p
== '%' && p
+ 1 < end
) {
89 // A literal percent sign represented by %%
97 if (*p
>= '0' && *p
<= '9') {
100 } while (*p
>= '0' && *p
<= '9');
102 // This must be a size specification instead of position.
103 nonpositional
= true;
105 } else if (*p
== '<') {
106 // Reusing last argument; bad idea since it can be re-arranged.
107 nonpositional
= true;
110 // Optionally '$' can be specified at the end.
111 if (p
< end
&& *p
== '$') {
115 nonpositional
= true;
118 // Ignore flags and widths
119 while (p
< end
&& (*p
== '-' ||
125 (*p
>= '0' && *p
<= '9'))) {
130 * This is a shortcut to detect strings that are going to Time.format()
131 * instead of String.format()
133 * Comparison of String.format() and Time.format() args:
135 * String: ABC E GH ST X abcdefgh nost x
136 * Time: DEFGHKMS W Za d hkm s w yz
138 * Therefore we know it's definitely Time if we have:
163 * If we have more than one substitution in this string and any of them
164 * are not in positional form, give the user an error.
166 if (argCount
> 1 && nonpositional
) {
167 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
168 "Multiple substitutions specified in non-positional format; "
169 "did you mean to add the formatted=\"false\" attribute?\n");
170 return NOT_ENOUGH_DATA
;
176 status_t
parseStyledString(Bundle
* bundle
,
177 const char* fileName
,
179 const String16
& endTag
,
181 Vector
<StringPool::entry_style_span
>* outSpans
,
185 Vector
<StringPool::entry_style_span
> spanStack
;
188 const char* errorMsg
;
190 bool firstTime
= true;
193 ResXMLTree::event_code_t code
;
194 while ((code
=inXml
->next()) != ResXMLTree::END_DOCUMENT
&& code
!= ResXMLTree::BAD_DOCUMENT
) {
196 if (code
== ResXMLTree::TEXT
) {
197 String16
text(inXml
->getText(&len
));
198 if (firstTime
&& text
.size() > 0) {
200 if (text
.string()[0] == '@') {
201 // If this is a resource reference, don't do the pseudoloc.
202 pseudolocalize
= false;
205 if (xliffDepth
== 0 && pseudolocalize
) {
206 std::string
orig(String8(text
).string());
207 std::string pseudo
= pseudolocalize_string(orig
);
208 curString
.append(String16(String8(pseudo
.c_str())));
210 if (isFormatted
&& hasSubstitutionErrors(fileName
, inXml
, text
) != NO_ERROR
) {
211 return UNKNOWN_ERROR
;
213 curString
.append(text
);
216 } else if (code
== ResXMLTree::START_TAG
) {
217 const String16
element16(inXml
->getElementName(&len
));
218 const String8
element8(element16
);
221 const uint16_t* ns
= inXml
->getElementNamespace(&nslen
);
223 ns
= (const uint16_t*)"\0\0";
226 const String8
nspace(String16(ns
, nslen
));
227 if (nspace
== XLIFF_XMLNS
) {
228 const int N
= sizeof(ALLOWED_XLIFF_ELEMENTS
)/sizeof(ALLOWED_XLIFF_ELEMENTS
[0]);
229 for (int i
=0; i
<N
; i
++) {
230 if (element8
== ALLOWED_XLIFF_ELEMENTS
[i
]) {
232 // in this case, treat it like it was just text, in other words, do nothing
233 // here and silently drop this element
238 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
239 "Found unsupported XLIFF tag <%s>\n",
241 return UNKNOWN_ERROR
;
247 if (outSpans
== NULL
) {
248 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
249 "Found style tag <%s> where styles are not allowed\n", element8
.string());
250 return UNKNOWN_ERROR
;
253 if (!ResTable::collectString(outString
, curString
.string(),
254 curString
.size(), false, &errorMsg
, true)) {
255 SourcePos(String8(fileName
), inXml
->getLineNumber()).error("%s (in %s)\n",
256 errorMsg
, String8(curString
).string());
257 return UNKNOWN_ERROR
;
259 rawString
.append(curString
);
260 curString
= String16();
262 StringPool::entry_style_span span
;
263 span
.name
= element16
;
264 for (size_t ai
=0; ai
<inXml
->getAttributeCount(); ai
++) {
265 span
.name
.append(String16(";"));
266 const char16_t* str
= inXml
->getAttributeName(ai
, &len
);
267 span
.name
.append(str
, len
);
268 span
.name
.append(String16("="));
269 str
= inXml
->getAttributeStringValue(ai
, &len
);
270 span
.name
.append(str
, len
);
272 //printf("Span: %s\n", String8(span.name).string());
273 span
.span
.firstChar
= span
.span
.lastChar
= outString
->size();
274 spanStack
.push(span
);
276 } else if (code
== ResXMLTree::END_TAG
) {
278 const uint16_t* ns
= inXml
->getElementNamespace(&nslen
);
280 ns
= (const uint16_t*)"\0\0";
283 const String8
nspace(String16(ns
, nslen
));
284 if (nspace
== XLIFF_XMLNS
) {
288 if (!ResTable::collectString(outString
, curString
.string(),
289 curString
.size(), false, &errorMsg
, true)) {
290 SourcePos(String8(fileName
), inXml
->getLineNumber()).error("%s (in %s)\n",
291 errorMsg
, String8(curString
).string());
292 return UNKNOWN_ERROR
;
294 rawString
.append(curString
);
295 curString
= String16();
297 if (spanStack
.size() == 0) {
298 if (strcmp16(inXml
->getElementName(&len
), endTag
.string()) != 0) {
299 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
300 "Found tag %s where <%s> close is expected\n",
301 String8(inXml
->getElementName(&len
)).string(),
302 String8(endTag
).string());
303 return UNKNOWN_ERROR
;
307 StringPool::entry_style_span span
= spanStack
.top();
309 ssize_t semi
= span
.name
.findFirst(';');
311 spanTag
.setTo(span
.name
.string(), semi
);
313 spanTag
.setTo(span
.name
);
315 if (strcmp16(inXml
->getElementName(&len
), spanTag
.string()) != 0) {
316 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
317 "Found close tag %s where close tag %s is expected\n",
318 String8(inXml
->getElementName(&len
)).string(),
319 String8(spanTag
).string());
320 return UNKNOWN_ERROR
;
323 if (outString
->size() > 0) {
324 span
.span
.lastChar
= outString
->size()-1;
325 if (span
.span
.lastChar
>= span
.span
.firstChar
) {
333 * This warning seems to be just an irritation to most people,
334 * since it is typically introduced by translators who then never
338 fprintf(stderr
, "%s:%d: warning: empty '%s' span found in text '%s'\n",
339 fileName
, inXml
->getLineNumber(),
340 String8(spanTag
).string(), String8(*outString
).string());
343 } else if (code
== ResXMLTree::START_NAMESPACE
) {
348 if (code
== ResXMLTree::BAD_DOCUMENT
) {
349 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
350 "Error parsing XML\n");
353 if (outSpans
!= NULL
&& outSpans
->size() > 0) {
354 if (curString
.size() > 0) {
355 if (!ResTable::collectString(outString
, curString
.string(),
356 curString
.size(), false, &errorMsg
, true)) {
357 SourcePos(String8(fileName
), inXml
->getLineNumber()).error(
359 errorMsg
, String8(curString
).string());
360 return UNKNOWN_ERROR
;
364 // There is no style information, so string processing will happen
365 // later as part of the overall type conversion. Return to the
366 // client the raw unprocessed text.
367 rawString
.append(curString
);
368 outString
->setTo(rawString
);
374 struct namespace_entry
{
379 static String8
make_prefix(int depth
)
383 for (i
=0; i
<depth
; i
++) {
389 static String8
build_namespace(const Vector
<namespace_entry
>& namespaces
,
395 const size_t N
= namespaces
.size();
396 for (size_t i
=0; i
<N
; i
++) {
397 const namespace_entry
& ne
= namespaces
.itemAt(i
);
408 void printXMLBlock(ResXMLTree
* block
)
412 Vector
<namespace_entry
> namespaces
;
414 ResXMLTree::event_code_t code
;
416 while ((code
=block
->next()) != ResXMLTree::END_DOCUMENT
&& code
!= ResXMLTree::BAD_DOCUMENT
) {
417 String8 prefix
= make_prefix(depth
);
419 if (code
== ResXMLTree::START_TAG
) {
421 const uint16_t* ns16
= block
->getElementNamespace(&len
);
422 String8 elemNs
= build_namespace(namespaces
, ns16
);
423 const uint16_t* com16
= block
->getComment(&len
);
425 printf("%s <!-- %s -->\n", prefix
.string(), String8(com16
).string());
427 printf("%sE: %s%s (line=%d)\n", prefix
.string(), elemNs
.string(),
428 String8(block
->getElementName(&len
)).string(),
429 block
->getLineNumber());
430 int N
= block
->getAttributeCount();
432 prefix
= make_prefix(depth
);
433 for (i
=0; i
<N
; i
++) {
434 uint32_t res
= block
->getAttributeNameResID(i
);
435 ns16
= block
->getAttributeNamespace(i
, &len
);
436 String8 ns
= build_namespace(namespaces
, ns16
);
437 String8
name(block
->getAttributeName(i
, &len
));
438 printf("%sA: ", prefix
.string());
440 printf("%s%s(0x%08x)", ns
.string(), name
.string(), res
);
442 printf("%s%s", ns
.string(), name
.string());
445 block
->getAttributeValue(i
, &value
);
446 if (value
.dataType
== Res_value::TYPE_NULL
) {
448 } else if (value
.dataType
== Res_value::TYPE_REFERENCE
) {
449 printf("=@0x%x", (int)value
.data
);
450 } else if (value
.dataType
== Res_value::TYPE_ATTRIBUTE
) {
451 printf("=?0x%x", (int)value
.data
);
452 } else if (value
.dataType
== Res_value::TYPE_STRING
) {
454 ResTable::normalizeForOutput(String8(block
->getAttributeStringValue(i
,
455 &len
)).string()).string());
457 printf("=(type 0x%x)0x%x", (int)value
.dataType
, (int)value
.data
);
459 const char16_t* val
= block
->getAttributeStringValue(i
, &len
);
461 printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val
).string()).
466 } else if (code
== ResXMLTree::END_TAG
) {
468 } else if (code
== ResXMLTree::START_NAMESPACE
) {
471 const uint16_t* prefix16
= block
->getNamespacePrefix(&len
);
473 ns
.prefix
= String8(prefix16
);
477 ns
.uri
= String8(block
->getNamespaceUri(&len
));
479 printf("%sN: %s=%s\n", prefix
.string(), ns
.prefix
.string(),
482 } else if (code
== ResXMLTree::END_NAMESPACE
) {
484 const namespace_entry
& ns
= namespaces
.top();
486 const uint16_t* prefix16
= block
->getNamespacePrefix(&len
);
489 pr
= String8(prefix16
);
493 if (ns
.prefix
!= pr
) {
494 prefix
= make_prefix(depth
);
495 printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
496 prefix
.string(), pr
.string(), ns
.prefix
.string());
498 String8 uri
= String8(block
->getNamespaceUri(&len
));
500 prefix
= make_prefix(depth
);
501 printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
502 prefix
.string(), uri
.string(), ns
.uri
.string());
505 } else if (code
== ResXMLTree::TEXT
) {
507 printf("%sC: \"%s\"\n", prefix
.string(), ResTable::normalizeForOutput(
508 String8(block
->getText(&len
)).string()).string());
515 status_t
parseXMLResource(const sp
<AaptFile
>& file
, ResXMLTree
* outTree
,
516 bool stripAll
, bool keepComments
,
517 const char** cDataTags
)
519 sp
<XMLNode
> root
= XMLNode::parse(file
);
521 return UNKNOWN_ERROR
;
523 root
->removeWhitespace(stripAll
, cDataTags
);
525 NOISY(printf("Input XML from %s:\n", (const char*)file
->getPrintableSource()));
526 NOISY(root
->print());
527 sp
<AaptFile
> rsc
= new AaptFile(String8(), AaptGroupEntry(), String8());
528 status_t err
= root
->flatten(rsc
, !keepComments
, false);
529 if (err
!= NO_ERROR
) {
532 err
= outTree
->setTo(rsc
->getData(), rsc
->getSize(), true);
533 if (err
!= NO_ERROR
) {
537 NOISY(printf("Output XML:\n"));
538 NOISY(printXMLBlock(outTree
));
543 sp
<XMLNode
> XMLNode::parse(const sp
<AaptFile
>& file
)
546 int fd
= open(file
->getSourceFile().string(), O_RDONLY
| O_BINARY
);
548 SourcePos(file
->getSourceFile(), -1).error("Unable to open file for read: %s",
553 XML_Parser parser
= XML_ParserCreateNS(NULL
, 1);
555 state
.filename
= file
->getPrintableSource();
556 state
.parser
= parser
;
557 XML_SetUserData(parser
, &state
);
558 XML_SetElementHandler(parser
, startElement
, endElement
);
559 XML_SetNamespaceDeclHandler(parser
, startNamespace
, endNamespace
);
560 XML_SetCharacterDataHandler(parser
, characterData
);
561 XML_SetCommentHandler(parser
, commentData
);
566 len
= read(fd
, buf
, sizeof(buf
));
567 done
= len
< (ssize_t
)sizeof(buf
);
569 SourcePos(file
->getSourceFile(), -1).error("Error reading file: %s\n", strerror(errno
));
573 if (XML_Parse(parser
, buf
, len
, done
) == XML_STATUS_ERROR
) {
574 SourcePos(file
->getSourceFile(), (int)XML_GetCurrentLineNumber(parser
)).error(
575 "Error parsing XML: %s\n", XML_ErrorString(XML_GetErrorCode(parser
)));
581 XML_ParserFree(parser
);
582 if (state
.root
== NULL
) {
583 SourcePos(file
->getSourceFile(), -1).error("No XML data generated when parsing");
589 XMLNode::XMLNode(const String8
& filename
, const String16
& s1
, const String16
& s2
, bool isNamespace
)
590 : mNextAttributeIndex(0x80000000)
591 , mFilename(filename
)
592 , mStartLineNumber(0)
597 mNamespacePrefix
= s1
;
605 XMLNode::XMLNode(const String8
& filename
)
606 : mFilename(filename
)
608 memset(&mCharsValue
, 0, sizeof(mCharsValue
));
611 XMLNode::type
XMLNode::getType() const
613 if (mElementName
.size() != 0) {
616 if (mNamespaceUri
.size() != 0) {
617 return TYPE_NAMESPACE
;
622 const String16
& XMLNode::getNamespacePrefix() const
624 return mNamespacePrefix
;
627 const String16
& XMLNode::getNamespaceUri() const
629 return mNamespaceUri
;
632 const String16
& XMLNode::getElementNamespace() const
634 return mNamespaceUri
;
637 const String16
& XMLNode::getElementName() const
642 const Vector
<sp
<XMLNode
> >& XMLNode::getChildren() const
647 const String8
& XMLNode::getFilename() const
652 const Vector
<XMLNode::attribute_entry
>&
653 XMLNode::getAttributes() const
658 const XMLNode::attribute_entry
* XMLNode::getAttribute(const String16
& ns
,
659 const String16
& name
) const
661 for (size_t i
=0; i
<mAttributes
.size(); i
++) {
662 const attribute_entry
& ae(mAttributes
.itemAt(i
));
663 if (ae
.ns
== ns
&& ae
.name
== name
) {
671 XMLNode::attribute_entry
* XMLNode::editAttribute(const String16
& ns
,
672 const String16
& name
)
674 for (size_t i
=0; i
<mAttributes
.size(); i
++) {
675 attribute_entry
* ae
= &mAttributes
.editItemAt(i
);
676 if (ae
->ns
== ns
&& ae
->name
== name
) {
684 const String16
& XMLNode::getCData() const
689 const String16
& XMLNode::getComment() const
694 int32_t XMLNode::getStartLineNumber() const
696 return mStartLineNumber
;
699 int32_t XMLNode::getEndLineNumber() const
701 return mEndLineNumber
;
704 sp
<XMLNode
> XMLNode::searchElement(const String16
& tagNamespace
, const String16
& tagName
)
706 if (getType() == XMLNode::TYPE_ELEMENT
707 && mNamespaceUri
== tagNamespace
708 && mElementName
== tagName
) {
712 for (size_t i
=0; i
<mChildren
.size(); i
++) {
713 sp
<XMLNode
> found
= mChildren
.itemAt(i
)->searchElement(tagNamespace
, tagName
);
722 sp
<XMLNode
> XMLNode::getChildElement(const String16
& tagNamespace
, const String16
& tagName
)
724 for (size_t i
=0; i
<mChildren
.size(); i
++) {
725 sp
<XMLNode
> child
= mChildren
.itemAt(i
);
726 if (child
->getType() == XMLNode::TYPE_ELEMENT
727 && child
->mNamespaceUri
== tagNamespace
728 && child
->mElementName
== tagName
) {
736 status_t
XMLNode::addChild(const sp
<XMLNode
>& child
)
738 if (getType() == TYPE_CDATA
) {
739 SourcePos(mFilename
, child
->getStartLineNumber()).error("Child to CDATA node.");
740 return UNKNOWN_ERROR
;
742 //printf("Adding child %p to parent %p\n", child.get(), this);
743 mChildren
.add(child
);
747 status_t
XMLNode::insertChildAt(const sp
<XMLNode
>& child
, size_t index
)
749 if (getType() == TYPE_CDATA
) {
750 SourcePos(mFilename
, child
->getStartLineNumber()).error("Child to CDATA node.");
751 return UNKNOWN_ERROR
;
753 //printf("Adding child %p to parent %p\n", child.get(), this);
754 mChildren
.insertAt(child
, index
);
758 status_t
XMLNode::addAttribute(const String16
& ns
, const String16
& name
,
759 const String16
& value
)
761 if (getType() == TYPE_CDATA
) {
762 SourcePos(mFilename
, getStartLineNumber()).error("Child to CDATA node.");
763 return UNKNOWN_ERROR
;
766 e
.index
= mNextAttributeIndex
++;
771 mAttributeOrder
.add(e
.index
, mAttributes
.size()-1);
775 void XMLNode::setAttributeResID(size_t attrIdx
, uint32_t resId
)
777 attribute_entry
& e
= mAttributes
.editItemAt(attrIdx
);
779 mAttributeOrder
.removeItem(e
.nameResId
);
781 mAttributeOrder
.removeItem(e
.index
);
783 NOISY(printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
784 String8(getElementName()).string(),
785 String8(mAttributes
.itemAt(attrIdx
).name
).string(),
786 String8(mAttributes
.itemAt(attrIdx
).string
).string(),
788 mAttributes
.editItemAt(attrIdx
).nameResId
= resId
;
789 mAttributeOrder
.add(resId
, attrIdx
);
792 status_t
XMLNode::appendChars(const String16
& chars
)
794 if (getType() != TYPE_CDATA
) {
795 SourcePos(mFilename
, getStartLineNumber()).error("Adding characters to element node.");
796 return UNKNOWN_ERROR
;
798 mChars
.append(chars
);
802 status_t
XMLNode::appendComment(const String16
& comment
)
804 if (mComment
.size() > 0) {
805 mComment
.append(String16("\n"));
807 mComment
.append(comment
);
811 void XMLNode::setStartLineNumber(int32_t line
)
813 mStartLineNumber
= line
;
816 void XMLNode::setEndLineNumber(int32_t line
)
818 mEndLineNumber
= line
;
821 void XMLNode::removeWhitespace(bool stripAll
, const char** cDataTags
)
823 //printf("Removing whitespace in %s\n", String8(mElementName).string());
824 size_t N
= mChildren
.size();
826 String8
tag(mElementName
);
827 const char** p
= cDataTags
;
835 for (size_t i
=0; i
<N
; i
++) {
836 sp
<XMLNode
> node
= mChildren
.itemAt(i
);
837 if (node
->getType() == TYPE_CDATA
) {
838 // This is a CDATA node...
839 const char16_t* p
= node
->mChars
.string();
840 while (*p
!= 0 && *p
< 128 && isspace(*p
)) {
843 //printf("Space ends at %d in \"%s\"\n",
844 // (int)(p-node->mChars.string()),
845 // String8(node->mChars).string());
849 mChildren
.removeAt(i
);
853 node
->mChars
= String16(" ");
856 // Compact leading/trailing whitespace.
857 const char16_t* e
= node
->mChars
.string()+node
->mChars
.size()-1;
858 while (e
> p
&& *e
< 128 && isspace(*e
)) {
861 if (p
> node
->mChars
.string()) {
864 if (e
< (node
->mChars
.string()+node
->mChars
.size()-1)) {
867 if (p
> node
->mChars
.string() ||
868 e
< (node
->mChars
.string()+node
->mChars
.size()-1)) {
869 String16
tmp(p
, e
-p
+1);
874 node
->removeWhitespace(stripAll
, cDataTags
);
879 status_t
XMLNode::parseValues(const sp
<AaptAssets
>& assets
,
880 ResourceTable
* table
)
882 bool hasErrors
= false;
884 if (getType() == TYPE_ELEMENT
) {
885 const size_t N
= mAttributes
.size();
886 String16
defPackage(assets
->getPackage());
887 for (size_t i
=0; i
<N
; i
++) {
888 attribute_entry
& e
= mAttributes
.editItemAt(i
);
889 AccessorCookie
ac(SourcePos(mFilename
, getStartLineNumber()), String8(e
.name
),
891 table
->setCurrentXmlPos(SourcePos(mFilename
, getStartLineNumber()));
892 if (!assets
->getIncludedResources()
893 .stringToValue(&e
.value
, &e
.string
,
894 e
.string
.string(), e
.string
.size(), true, true,
895 e
.nameResId
, NULL
, &defPackage
, table
, &ac
)) {
898 NOISY(printf("Attr %s: type=0x%x, str=%s\n",
899 String8(e
.name
).string(), e
.value
.dataType
,
900 String8(e
.string
).string()));
903 const size_t N
= mChildren
.size();
904 for (size_t i
=0; i
<N
; i
++) {
905 status_t err
= mChildren
.itemAt(i
)->parseValues(assets
, table
);
906 if (err
!= NO_ERROR
) {
910 return hasErrors
? UNKNOWN_ERROR
: NO_ERROR
;
913 status_t
XMLNode::assignResourceIds(const sp
<AaptAssets
>& assets
,
914 const ResourceTable
* table
)
916 bool hasErrors
= false;
918 if (getType() == TYPE_ELEMENT
) {
919 String16
attr("attr");
920 const char* errorMsg
;
921 const size_t N
= mAttributes
.size();
922 for (size_t i
=0; i
<N
; i
++) {
923 const attribute_entry
& e
= mAttributes
.itemAt(i
);
924 if (e
.ns
.size() <= 0) continue;
926 String16
pkg(getNamespaceResourcePackage(e
.ns
, &nsIsPublic
));
927 NOISY(printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
928 String8(getElementName()).string(),
929 String8(e
.name
).string(),
930 String8(e
.string
).string(),
931 String8(e
.ns
).string(),
932 (nsIsPublic
) ? "public" : "private",
933 String8(pkg
).string()));
934 if (pkg
.size() <= 0) continue;
935 uint32_t res
= table
!= NULL
936 ? table
->getResId(e
.name
, &attr
, &pkg
, &errorMsg
, nsIsPublic
)
937 : assets
->getIncludedResources().
938 identifierForName(e
.name
.string(), e
.name
.size(),
939 attr
.string(), attr
.size(),
940 pkg
.string(), pkg
.size());
942 NOISY(printf("XML attribute name %s: resid=0x%08x\n",
943 String8(e
.name
).string(), res
));
944 setAttributeResID(i
, res
);
946 SourcePos(mFilename
, getStartLineNumber()).error(
947 "No resource identifier found for attribute '%s' in package '%s'\n",
948 String8(e
.name
).string(), String8(pkg
).string());
953 const size_t N
= mChildren
.size();
954 for (size_t i
=0; i
<N
; i
++) {
955 status_t err
= mChildren
.itemAt(i
)->assignResourceIds(assets
, table
);
956 if (err
< NO_ERROR
) {
961 return hasErrors
? UNKNOWN_ERROR
: NO_ERROR
;
964 status_t
XMLNode::flatten(const sp
<AaptFile
>& dest
,
965 bool stripComments
, bool stripRawValues
) const
967 StringPool strings
= StringPool(false, mUTF8
);
968 Vector
<uint32_t> resids
;
970 // First collect just the strings for attribute names that have a
971 // resource ID assigned to them. This ensures that the resource ID
972 // array is compact, and makes it easier to deal with attribute names
973 // in different namespaces (and thus with different resource IDs).
974 collect_resid_strings(&strings
, &resids
);
976 // Next collect all remainibng strings.
977 collect_strings(&strings
, &resids
, stripComments
, stripRawValues
);
979 #if 0 // No longer compiles
980 NOISY(printf("Found strings:\n");
981 const size_t N
= strings
.size();
982 for (size_t i
=0; i
<N
; i
++) {
983 printf("%s\n", String8(strings
.entryAt(i
).string
).string());
988 sp
<AaptFile
> stringPool
= strings
.createStringBlock();
989 NOISY(aout
<< "String pool:"
990 << HexDump(stringPool
->getData(), stringPool
->getSize()) << endl
);
992 ResXMLTree_header header
;
993 memset(&header
, 0, sizeof(header
));
994 header
.header
.type
= htods(RES_XML_TYPE
);
995 header
.header
.headerSize
= htods(sizeof(header
));
997 const size_t basePos
= dest
->getSize();
998 dest
->writeData(&header
, sizeof(header
));
999 dest
->writeData(stringPool
->getData(), stringPool
->getSize());
1001 // If we have resource IDs, write them.
1002 if (resids
.size() > 0) {
1003 const size_t resIdsPos
= dest
->getSize();
1004 const size_t resIdsSize
=
1005 sizeof(ResChunk_header
)+(sizeof(uint32_t)*resids
.size());
1006 ResChunk_header
* idsHeader
= (ResChunk_header
*)
1007 (((const uint8_t*)dest
->editData(resIdsPos
+resIdsSize
))+resIdsPos
);
1008 idsHeader
->type
= htods(RES_XML_RESOURCE_MAP_TYPE
);
1009 idsHeader
->headerSize
= htods(sizeof(*idsHeader
));
1010 idsHeader
->size
= htodl(resIdsSize
);
1011 uint32_t* ids
= (uint32_t*)(idsHeader
+1);
1012 for (size_t i
=0; i
<resids
.size(); i
++) {
1013 *ids
++ = htodl(resids
[i
]);
1017 flatten_node(strings
, dest
, stripComments
, stripRawValues
);
1019 void* data
= dest
->editData();
1020 ResXMLTree_header
* hd
= (ResXMLTree_header
*)(((uint8_t*)data
)+basePos
);
1021 size_t size
= dest
->getSize()-basePos
;
1022 hd
->header
.size
= htodl(dest
->getSize()-basePos
);
1024 NOISY(aout
<< "XML resource:"
1025 << HexDump(dest
->getData(), dest
->getSize()) << endl
);
1027 #if PRINT_STRING_METRICS
1028 fprintf(stderr
, "**** total xml size: %d / %d%% strings (in %s)\n",
1029 dest
->getSize(), (stringPool
->getSize()*100)/dest
->getSize(),
1030 dest
->getPath().string());
1036 void XMLNode::print(int indent
)
1040 for (i
=0; i
<indent
; i
++) {
1043 if (getType() == TYPE_ELEMENT
) {
1044 String8
elemNs(getNamespaceUri());
1045 if (elemNs
.size() > 0) {
1048 printf("%s E: %s%s", prefix
.string(),
1049 elemNs
.string(), String8(getElementName()).string());
1050 int N
= mAttributes
.size();
1051 for (i
=0; i
<N
; i
++) {
1052 ssize_t idx
= mAttributeOrder
.valueAt(i
);
1058 const attribute_entry
& attr
= mAttributes
.itemAt(idx
);
1059 String8
attrNs(attr
.ns
);
1060 if (attrNs
.size() > 0) {
1063 if (attr
.nameResId
) {
1064 printf("%s%s(0x%08x)", attrNs
.string(),
1065 String8(attr
.name
).string(), attr
.nameResId
);
1067 printf("%s%s", attrNs
.string(), String8(attr
.name
).string());
1069 printf("=%s", String8(attr
.string
).string());
1072 } else if (getType() == TYPE_NAMESPACE
) {
1073 printf("%s N: %s=%s\n", prefix
.string(),
1074 getNamespacePrefix().size() > 0
1075 ? String8(getNamespacePrefix()).string() : "<DEF>",
1076 String8(getNamespaceUri()).string());
1078 printf("%s C: \"%s\"\n", prefix
.string(), String8(getCData()).string());
1080 int N
= mChildren
.size();
1081 for (i
=0; i
<N
; i
++) {
1082 mChildren
.itemAt(i
)->print(indent
+1);
1086 static void splitName(const char* name
, String16
* outNs
, String16
* outName
)
1088 const char* p
= name
;
1089 while (*p
!= 0 && *p
!= 1) {
1093 *outNs
= String16();
1094 *outName
= String16(name
);
1096 *outNs
= String16(name
, (p
-name
));
1097 *outName
= String16(p
+1);
1102 XMLNode::startNamespace(void *userData
, const char *prefix
, const char *uri
)
1104 NOISY_PARSE(printf("Start Namespace: %s %s\n", prefix
, uri
));
1105 ParseState
* st
= (ParseState
*)userData
;
1106 sp
<XMLNode
> node
= XMLNode::newNamespace(st
->filename
,
1107 String16(prefix
!= NULL
? prefix
: ""), String16(uri
));
1108 node
->setStartLineNumber(XML_GetCurrentLineNumber(st
->parser
));
1109 if (st
->stack
.size() > 0) {
1110 st
->stack
.itemAt(st
->stack
.size()-1)->addChild(node
);
1114 st
->stack
.push(node
);
1118 XMLNode::startElement(void *userData
, const char *name
, const char **atts
)
1120 NOISY_PARSE(printf("Start Element: %s\n", name
));
1121 ParseState
* st
= (ParseState
*)userData
;
1122 String16 ns16
, name16
;
1123 splitName(name
, &ns16
, &name16
);
1124 sp
<XMLNode
> node
= XMLNode::newElement(st
->filename
, ns16
, name16
);
1125 node
->setStartLineNumber(XML_GetCurrentLineNumber(st
->parser
));
1126 if (st
->pendingComment
.size() > 0) {
1127 node
->appendComment(st
->pendingComment
);
1128 st
->pendingComment
= String16();
1130 if (st
->stack
.size() > 0) {
1131 st
->stack
.itemAt(st
->stack
.size()-1)->addChild(node
);
1135 st
->stack
.push(node
);
1137 for (int i
= 0; atts
[i
]; i
+= 2) {
1138 splitName(atts
[i
], &ns16
, &name16
);
1139 node
->addAttribute(ns16
, name16
, String16(atts
[i
+1]));
1144 XMLNode::characterData(void *userData
, const XML_Char
*s
, int len
)
1146 NOISY_PARSE(printf("CDATA: \"%s\"\n", String8(s
, len
).string()));
1147 ParseState
* st
= (ParseState
*)userData
;
1148 sp
<XMLNode
> node
= NULL
;
1149 if (st
->stack
.size() == 0) {
1152 sp
<XMLNode
> parent
= st
->stack
.itemAt(st
->stack
.size()-1);
1153 if (parent
!= NULL
&& parent
->getChildren().size() > 0) {
1154 node
= parent
->getChildren()[parent
->getChildren().size()-1];
1155 if (node
->getType() != TYPE_CDATA
) {
1156 // Last node is not CDATA, need to make a new node.
1162 node
= XMLNode::newCData(st
->filename
);
1163 node
->setStartLineNumber(XML_GetCurrentLineNumber(st
->parser
));
1164 parent
->addChild(node
);
1167 node
->appendChars(String16(s
, len
));
1171 XMLNode::endElement(void *userData
, const char *name
)
1173 NOISY_PARSE(printf("End Element: %s\n", name
));
1174 ParseState
* st
= (ParseState
*)userData
;
1175 sp
<XMLNode
> node
= st
->stack
.itemAt(st
->stack
.size()-1);
1176 node
->setEndLineNumber(XML_GetCurrentLineNumber(st
->parser
));
1177 if (st
->pendingComment
.size() > 0) {
1178 node
->appendComment(st
->pendingComment
);
1179 st
->pendingComment
= String16();
1181 String16 ns16
, name16
;
1182 splitName(name
, &ns16
, &name16
);
1183 LOG_ALWAYS_FATAL_IF(node
->getElementNamespace() != ns16
1184 || node
->getElementName() != name16
,
1185 "Bad end element %s", name
);
1190 XMLNode::endNamespace(void *userData
, const char *prefix
)
1192 const char* nonNullPrefix
= prefix
!= NULL
? prefix
: "";
1193 NOISY_PARSE(printf("End Namespace: %s\n", prefix
));
1194 ParseState
* st
= (ParseState
*)userData
;
1195 sp
<XMLNode
> node
= st
->stack
.itemAt(st
->stack
.size()-1);
1196 node
->setEndLineNumber(XML_GetCurrentLineNumber(st
->parser
));
1197 LOG_ALWAYS_FATAL_IF(node
->getNamespacePrefix() != String16(nonNullPrefix
),
1198 "Bad end namespace %s", prefix
);
1203 XMLNode::commentData(void *userData
, const char *comment
)
1205 NOISY_PARSE(printf("Comment: %s\n", comment
));
1206 ParseState
* st
= (ParseState
*)userData
;
1207 if (st
->pendingComment
.size() > 0) {
1208 st
->pendingComment
.append(String16("\n"));
1210 st
->pendingComment
.append(String16(comment
));
1213 status_t
XMLNode::collect_strings(StringPool
* dest
, Vector
<uint32_t>* outResIds
,
1214 bool stripComments
, bool stripRawValues
) const
1216 collect_attr_strings(dest
, outResIds
, true);
1219 if (mNamespacePrefix
.size() > 0) {
1220 dest
->add(mNamespacePrefix
, true);
1222 if (mNamespaceUri
.size() > 0) {
1223 dest
->add(mNamespaceUri
, true);
1225 if (mElementName
.size() > 0) {
1226 dest
->add(mElementName
, true);
1229 if (!stripComments
&& mComment
.size() > 0) {
1230 dest
->add(mComment
, true);
1233 const int NA
= mAttributes
.size();
1235 for (i
=0; i
<NA
; i
++) {
1236 const attribute_entry
& ae
= mAttributes
.itemAt(i
);
1237 if (ae
.ns
.size() > 0) {
1238 dest
->add(ae
.ns
, true);
1240 if (!stripRawValues
|| ae
.needStringValue()) {
1241 dest
->add(ae
.string
, true);
1244 if (ae.value.dataType == Res_value::TYPE_NULL
1245 || ae.value.dataType == Res_value::TYPE_STRING) {
1246 dest->add(ae.string, true);
1251 if (mElementName
.size() == 0) {
1252 // If not an element, include the CDATA, even if it is empty.
1253 dest
->add(mChars
, true);
1256 const int NC
= mChildren
.size();
1258 for (i
=0; i
<NC
; i
++) {
1259 mChildren
.itemAt(i
)->collect_strings(dest
, outResIds
,
1260 stripComments
, stripRawValues
);
1266 status_t
XMLNode::collect_attr_strings(StringPool
* outPool
,
1267 Vector
<uint32_t>* outResIds
, bool allAttrs
) const {
1268 const int NA
= mAttributes
.size();
1270 for (int i
=0; i
<NA
; i
++) {
1271 const attribute_entry
& attr
= mAttributes
.itemAt(i
);
1272 uint32_t id
= attr
.nameResId
;
1273 if (id
|| allAttrs
) {
1274 // See if we have already assigned this resource ID to a pooled
1276 const Vector
<size_t>* indices
= outPool
->offsetsForString(attr
.name
);
1278 if (indices
!= NULL
) {
1279 const int NJ
= indices
->size();
1280 const size_t NR
= outResIds
->size();
1281 for (int j
=0; j
<NJ
; j
++) {
1282 size_t strIdx
= indices
->itemAt(j
);
1285 // We don't need to assign a resource ID for this one.
1289 // Just ignore strings that are out of range of
1290 // the currently assigned resource IDs... we add
1291 // strings as we assign the first ID.
1292 } else if (outResIds
->itemAt(strIdx
) == id
) {
1299 idx
= outPool
->add(attr
.name
);
1300 NOISY(printf("Adding attr %s (resid 0x%08x) to pool: idx=%d\n",
1301 String8(attr
.name
).string(), id
, idx
));
1303 while ((ssize_t
)outResIds
->size() <= idx
) {
1306 outResIds
->replaceAt(id
, idx
);
1309 attr
.namePoolIdx
= idx
;
1310 NOISY(printf("String %s offset=0x%08x\n",
1311 String8(attr
.name
).string(), idx
));
1318 status_t
XMLNode::collect_resid_strings(StringPool
* outPool
,
1319 Vector
<uint32_t>* outResIds
) const
1321 collect_attr_strings(outPool
, outResIds
, false);
1323 const int NC
= mChildren
.size();
1325 for (int i
=0; i
<NC
; i
++) {
1326 mChildren
.itemAt(i
)->collect_resid_strings(outPool
, outResIds
);
1332 status_t
XMLNode::flatten_node(const StringPool
& strings
, const sp
<AaptFile
>& dest
,
1333 bool stripComments
, bool stripRawValues
) const
1335 ResXMLTree_node node
;
1336 ResXMLTree_cdataExt cdataExt
;
1337 ResXMLTree_namespaceExt namespaceExt
;
1338 ResXMLTree_attrExt attrExt
;
1339 const void* extData
= NULL
;
1341 ResXMLTree_attribute attr
;
1343 const size_t NA
= mAttributes
.size();
1344 const size_t NC
= mChildren
.size();
1347 LOG_ALWAYS_FATAL_IF(NA
!= mAttributeOrder
.size(), "Attributes messed up!");
1349 const String16
id16("id");
1350 const String16
class16("class");
1351 const String16
style16("style");
1353 const type type
= getType();
1355 memset(&node
, 0, sizeof(node
));
1356 memset(&attr
, 0, sizeof(attr
));
1357 node
.header
.headerSize
= htods(sizeof(node
));
1358 node
.lineNumber
= htodl(getStartLineNumber());
1359 if (!stripComments
) {
1360 node
.comment
.index
= htodl(
1361 mComment
.size() > 0 ? strings
.offsetForString(mComment
) : -1);
1362 //if (mComment.size() > 0) {
1363 // printf("Flattening comment: %s\n", String8(mComment).string());
1366 node
.comment
.index
= htodl((uint32_t)-1);
1368 if (type
== TYPE_ELEMENT
) {
1369 node
.header
.type
= htods(RES_XML_START_ELEMENT_TYPE
);
1371 extSize
= sizeof(attrExt
);
1372 memset(&attrExt
, 0, sizeof(attrExt
));
1373 if (mNamespaceUri
.size() > 0) {
1374 attrExt
.ns
.index
= htodl(strings
.offsetForString(mNamespaceUri
));
1376 attrExt
.ns
.index
= htodl((uint32_t)-1);
1378 attrExt
.name
.index
= htodl(strings
.offsetForString(mElementName
));
1379 attrExt
.attributeStart
= htods(sizeof(attrExt
));
1380 attrExt
.attributeSize
= htods(sizeof(attr
));
1381 attrExt
.attributeCount
= htods(NA
);
1382 attrExt
.idIndex
= htods(0);
1383 attrExt
.classIndex
= htods(0);
1384 attrExt
.styleIndex
= htods(0);
1385 for (i
=0; i
<NA
; i
++) {
1386 ssize_t idx
= mAttributeOrder
.valueAt(i
);
1387 const attribute_entry
& ae
= mAttributes
.itemAt(idx
);
1388 if (ae
.ns
.size() == 0) {
1389 if (ae
.name
== id16
) {
1390 attrExt
.idIndex
= htods(i
+1);
1391 } else if (ae
.name
== class16
) {
1392 attrExt
.classIndex
= htods(i
+1);
1393 } else if (ae
.name
== style16
) {
1394 attrExt
.styleIndex
= htods(i
+1);
1398 } else if (type
== TYPE_NAMESPACE
) {
1399 node
.header
.type
= htods(RES_XML_START_NAMESPACE_TYPE
);
1400 extData
= &namespaceExt
;
1401 extSize
= sizeof(namespaceExt
);
1402 memset(&namespaceExt
, 0, sizeof(namespaceExt
));
1403 if (mNamespacePrefix
.size() > 0) {
1404 namespaceExt
.prefix
.index
= htodl(strings
.offsetForString(mNamespacePrefix
));
1406 namespaceExt
.prefix
.index
= htodl((uint32_t)-1);
1408 namespaceExt
.prefix
.index
= htodl(strings
.offsetForString(mNamespacePrefix
));
1409 namespaceExt
.uri
.index
= htodl(strings
.offsetForString(mNamespaceUri
));
1410 LOG_ALWAYS_FATAL_IF(NA
!= 0, "Namespace nodes can't have attributes!");
1411 } else if (type
== TYPE_CDATA
) {
1412 node
.header
.type
= htods(RES_XML_CDATA_TYPE
);
1413 extData
= &cdataExt
;
1414 extSize
= sizeof(cdataExt
);
1415 memset(&cdataExt
, 0, sizeof(cdataExt
));
1416 cdataExt
.data
.index
= htodl(strings
.offsetForString(mChars
));
1417 cdataExt
.typedData
.size
= htods(sizeof(cdataExt
.typedData
));
1418 cdataExt
.typedData
.res0
= 0;
1419 cdataExt
.typedData
.dataType
= mCharsValue
.dataType
;
1420 cdataExt
.typedData
.data
= htodl(mCharsValue
.data
);
1421 LOG_ALWAYS_FATAL_IF(NA
!= 0, "CDATA nodes can't have attributes!");
1424 node
.header
.size
= htodl(sizeof(node
) + extSize
+ (sizeof(attr
)*NA
));
1426 dest
->writeData(&node
, sizeof(node
));
1428 dest
->writeData(extData
, extSize
);
1431 for (i
=0; i
<NA
; i
++) {
1432 ssize_t idx
= mAttributeOrder
.valueAt(i
);
1433 const attribute_entry
& ae
= mAttributes
.itemAt(idx
);
1434 if (ae
.ns
.size() > 0) {
1435 attr
.ns
.index
= htodl(strings
.offsetForString(ae
.ns
));
1437 attr
.ns
.index
= htodl((uint32_t)-1);
1439 attr
.name
.index
= htodl(ae
.namePoolIdx
);
1441 if (!stripRawValues
|| ae
.needStringValue()) {
1442 attr
.rawValue
.index
= htodl(strings
.offsetForString(ae
.string
));
1444 attr
.rawValue
.index
= htodl((uint32_t)-1);
1446 attr
.typedValue
.size
= htods(sizeof(attr
.typedValue
));
1447 if (ae
.value
.dataType
== Res_value::TYPE_NULL
1448 || ae
.value
.dataType
== Res_value::TYPE_STRING
) {
1449 attr
.typedValue
.res0
= 0;
1450 attr
.typedValue
.dataType
= Res_value::TYPE_STRING
;
1451 attr
.typedValue
.data
= htodl(strings
.offsetForString(ae
.string
));
1453 attr
.typedValue
.res0
= 0;
1454 attr
.typedValue
.dataType
= ae
.value
.dataType
;
1455 attr
.typedValue
.data
= htodl(ae
.value
.data
);
1457 dest
->writeData(&attr
, sizeof(attr
));
1460 for (i
=0; i
<NC
; i
++) {
1461 status_t err
= mChildren
.itemAt(i
)->flatten_node(strings
, dest
,
1462 stripComments
, stripRawValues
);
1463 if (err
!= NO_ERROR
) {
1468 if (type
== TYPE_ELEMENT
) {
1469 ResXMLTree_endElementExt endElementExt
;
1470 memset(&endElementExt
, 0, sizeof(endElementExt
));
1471 node
.header
.type
= htods(RES_XML_END_ELEMENT_TYPE
);
1472 node
.header
.size
= htodl(sizeof(node
)+sizeof(endElementExt
));
1473 node
.lineNumber
= htodl(getEndLineNumber());
1474 node
.comment
.index
= htodl((uint32_t)-1);
1475 endElementExt
.ns
.index
= attrExt
.ns
.index
;
1476 endElementExt
.name
.index
= attrExt
.name
.index
;
1477 dest
->writeData(&node
, sizeof(node
));
1478 dest
->writeData(&endElementExt
, sizeof(endElementExt
));
1479 } else if (type
== TYPE_NAMESPACE
) {
1480 node
.header
.type
= htods(RES_XML_END_NAMESPACE_TYPE
);
1481 node
.lineNumber
= htodl(getEndLineNumber());
1482 node
.comment
.index
= htodl((uint32_t)-1);
1483 node
.header
.size
= htodl(sizeof(node
)+extSize
);
1484 dest
->writeData(&node
, sizeof(node
));
1485 dest
->writeData(extData
, extSize
);