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