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