2 * Copyright (C) 2000 Peter Kelly <pmk@post.com>
3 * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org>
5 * Copyright (C) 2007 Samuel Weinig <sam@webkit.org>
6 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
7 * Copyright (C) 2008 Holger Hans Peter Freyther
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9 * Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
28 #include "XMLDocumentParser.h"
30 #include "CDATASection.h"
31 #include "CachedScript.h"
33 #include "CachedResourceLoader.h"
35 #include "DocumentFragment.h"
36 #include "DocumentType.h"
38 #include "FrameLoader.h"
39 #include "FrameView.h"
40 #include "HTMLEntityParser.h"
41 #include "HTMLHtmlElement.h"
42 #include "HTMLLinkElement.h"
43 #include "HTMLNames.h"
44 #include "HTMLStyleElement.h"
45 #include "ProcessingInstruction.h"
46 #include "ResourceError.h"
47 #include "ResourceHandle.h"
48 #include "ResourceRequest.h"
49 #include "ResourceResponse.h"
50 #include "ScriptElement.h"
51 #include "ScriptSourceCode.h"
52 #include "ScriptValue.h"
53 #include "TextResourceDecoder.h"
54 #include "TransformSource.h"
55 #include "XMLNSNames.h"
56 #include "XMLDocumentParserScope.h"
57 #include <libxml/parser.h>
58 #include <libxml/parserInternals.h>
59 #include <wtf/text/CString.h>
60 #include <wtf/StringExtras.h>
61 #include <wtf/Threading.h>
62 #include <wtf/UnusedParam.h>
63 #include <wtf/Vector.h>
66 #include <libxslt/xslt.h>
70 #include "HTMLNames.h"
71 #include "HTMLScriptElement.h"
78 class PendingCallbacks : public Noncopyable {
82 deleteAllValues(m_callbacks);
85 void appendStartElementNSCallback(const xmlChar* xmlLocalName, const xmlChar* xmlPrefix, const xmlChar* xmlURI, int nb_namespaces,
86 const xmlChar** namespaces, int nb_attributes, int nb_defaulted, const xmlChar** attributes)
88 PendingStartElementNSCallback* callback = new PendingStartElementNSCallback;
90 callback->xmlLocalName = xmlStrdup(xmlLocalName);
91 callback->xmlPrefix = xmlStrdup(xmlPrefix);
92 callback->xmlURI = xmlStrdup(xmlURI);
93 callback->nb_namespaces = nb_namespaces;
94 callback->namespaces = static_cast<xmlChar**>(xmlMalloc(sizeof(xmlChar*) * nb_namespaces * 2));
95 for (int i = 0; i < nb_namespaces * 2 ; i++)
96 callback->namespaces[i] = xmlStrdup(namespaces[i]);
97 callback->nb_attributes = nb_attributes;
98 callback->nb_defaulted = nb_defaulted;
99 callback->attributes = static_cast<xmlChar**>(xmlMalloc(sizeof(xmlChar*) * nb_attributes * 5));
100 for (int i = 0; i < nb_attributes; i++) {
101 // Each attribute has 5 elements in the array:
102 // name, prefix, uri, value and an end pointer.
104 for (int j = 0; j < 3; j++)
105 callback->attributes[i * 5 + j] = xmlStrdup(attributes[i * 5 + j]);
107 int len = attributes[i * 5 + 4] - attributes[i * 5 + 3];
109 callback->attributes[i * 5 + 3] = xmlStrndup(attributes[i * 5 + 3], len);
110 callback->attributes[i * 5 + 4] = callback->attributes[i * 5 + 3] + len;
113 m_callbacks.append(callback);
116 void appendEndElementNSCallback()
118 PendingEndElementNSCallback* callback = new PendingEndElementNSCallback;
120 m_callbacks.append(callback);
123 void appendCharactersCallback(const xmlChar* s, int len)
125 PendingCharactersCallback* callback = new PendingCharactersCallback;
127 callback->s = xmlStrndup(s, len);
130 m_callbacks.append(callback);
133 void appendProcessingInstructionCallback(const xmlChar* target, const xmlChar* data)
135 PendingProcessingInstructionCallback* callback = new PendingProcessingInstructionCallback;
137 callback->target = xmlStrdup(target);
138 callback->data = xmlStrdup(data);
140 m_callbacks.append(callback);
143 void appendCDATABlockCallback(const xmlChar* s, int len)
145 PendingCDATABlockCallback* callback = new PendingCDATABlockCallback;
147 callback->s = xmlStrndup(s, len);
150 m_callbacks.append(callback);
153 void appendCommentCallback(const xmlChar* s)
155 PendingCommentCallback* callback = new PendingCommentCallback;
157 callback->s = xmlStrdup(s);
159 m_callbacks.append(callback);
162 void appendInternalSubsetCallback(const xmlChar* name, const xmlChar* externalID, const xmlChar* systemID)
164 PendingInternalSubsetCallback* callback = new PendingInternalSubsetCallback;
166 callback->name = xmlStrdup(name);
167 callback->externalID = xmlStrdup(externalID);
168 callback->systemID = xmlStrdup(systemID);
170 m_callbacks.append(callback);
173 void appendErrorCallback(XMLDocumentParser::ErrorType type, const xmlChar* message, int lineNumber, int columnNumber)
175 PendingErrorCallback* callback = new PendingErrorCallback;
177 callback->message = xmlStrdup(message);
178 callback->type = type;
179 callback->lineNumber = lineNumber;
180 callback->columnNumber = columnNumber;
182 m_callbacks.append(callback);
185 void callAndRemoveFirstCallback(XMLDocumentParser* parser)
187 OwnPtr<PendingCallback> callback(m_callbacks.takeFirst());
188 callback->call(parser);
191 bool isEmpty() const { return m_callbacks.isEmpty(); }
194 struct PendingCallback {
195 virtual ~PendingCallback() { }
196 virtual void call(XMLDocumentParser* parser) = 0;
199 struct PendingStartElementNSCallback : public PendingCallback {
200 virtual ~PendingStartElementNSCallback()
202 xmlFree(xmlLocalName);
205 for (int i = 0; i < nb_namespaces * 2; i++)
206 xmlFree(namespaces[i]);
208 for (int i = 0; i < nb_attributes; i++)
209 for (int j = 0; j < 4; j++)
210 xmlFree(attributes[i * 5 + j]);
214 virtual void call(XMLDocumentParser* parser)
216 parser->startElementNs(xmlLocalName, xmlPrefix, xmlURI,
217 nb_namespaces, const_cast<const xmlChar**>(namespaces),
218 nb_attributes, nb_defaulted, const_cast<const xmlChar**>(attributes));
221 xmlChar* xmlLocalName;
225 xmlChar** namespaces;
228 xmlChar** attributes;
231 struct PendingEndElementNSCallback : public PendingCallback {
232 virtual void call(XMLDocumentParser* parser)
234 parser->endElementNs();
238 struct PendingCharactersCallback : public PendingCallback {
239 virtual ~PendingCharactersCallback()
244 virtual void call(XMLDocumentParser* parser)
246 parser->characters(s, len);
253 struct PendingProcessingInstructionCallback : public PendingCallback {
254 virtual ~PendingProcessingInstructionCallback()
260 virtual void call(XMLDocumentParser* parser)
262 parser->processingInstruction(target, data);
269 struct PendingCDATABlockCallback : public PendingCallback {
270 virtual ~PendingCDATABlockCallback()
275 virtual void call(XMLDocumentParser* parser)
277 parser->cdataBlock(s, len);
284 struct PendingCommentCallback : public PendingCallback {
285 virtual ~PendingCommentCallback()
290 virtual void call(XMLDocumentParser* parser)
298 struct PendingInternalSubsetCallback : public PendingCallback {
299 virtual ~PendingInternalSubsetCallback()
306 virtual void call(XMLDocumentParser* parser)
308 parser->internalSubset(name, externalID, systemID);
316 struct PendingErrorCallback: public PendingCallback {
317 virtual ~PendingErrorCallback()
322 virtual void call(XMLDocumentParser* parser)
324 parser->handleError(type, reinterpret_cast<char*>(message), lineNumber, columnNumber);
327 XMLDocumentParser::ErrorType type;
333 Deque<PendingCallback*> m_callbacks;
335 // --------------------------------
337 static int globalDescriptor = 0;
338 static ThreadIdentifier libxmlLoaderThread = 0;
340 static int matchFunc(const char*)
342 // Only match loads initiated due to uses of libxml2 from within XMLDocumentParser to avoid
343 // interfering with client applications that also use libxml2. http://bugs.webkit.org/show_bug.cgi?id=17353
344 return XMLDocumentParserScope::currentCachedResourceLoader && currentThread() == libxmlLoaderThread;
349 OffsetBuffer(const Vector<char>& b) : m_buffer(b), m_currentOffset(0) { }
351 int readOutBytes(char* outputBuffer, unsigned askedToRead)
353 unsigned bytesLeft = m_buffer.size() - m_currentOffset;
354 unsigned lenToCopy = min(askedToRead, bytesLeft);
356 memcpy(outputBuffer, m_buffer.data() + m_currentOffset, lenToCopy);
357 m_currentOffset += lenToCopy;
363 Vector<char> m_buffer;
364 unsigned m_currentOffset;
367 static void switchToUTF16(xmlParserCtxtPtr ctxt)
369 // Hack around libxml2's lack of encoding overide support by manually
370 // resetting the encoding to UTF-16 before every chunk. Otherwise libxml
371 // will detect <?xml version="1.0" encoding="<encoding name>"?> blocks
372 // and switch encodings, causing the parse to fail.
373 const UChar BOM = 0xFEFF;
374 const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
375 xmlSwitchEncoding(ctxt, BOMHighByte == 0xFF ? XML_CHAR_ENCODING_UTF16LE : XML_CHAR_ENCODING_UTF16BE);
378 static bool shouldAllowExternalLoad(const KURL& url)
380 String urlString = url.string();
382 // On non-Windows platforms libxml asks for this URL, the
383 // "XML_XML_DEFAULT_CATALOG", on initialization.
384 if (urlString == "file:///etc/xml/catalog")
387 // On Windows, libxml computes a URL relative to where its DLL resides.
388 if (urlString.startsWith("file:///", false) && urlString.endsWith("/etc/catalog", false))
391 // The most common DTD. There isn't much point in hammering www.w3c.org
392 // by requesting this URL for every XHTML document.
393 if (urlString.startsWith("http://www.w3.org/TR/xhtml", false))
396 // Similarly, there isn't much point in requesting the SVG DTD.
397 if (urlString.startsWith("http://www.w3.org/Graphics/SVG", false))
400 // The libxml doesn't give us a lot of context for deciding whether to
401 // allow this request. In the worst case, this load could be for an
402 // external entity and the resulting document could simply read the
403 // retrieved content. If we had more context, we could potentially allow
404 // the parser to load a DTD. As things stand, we take the conservative
405 // route and allow same-origin requests only.
406 if (!XMLDocumentParserScope::currentCachedResourceLoader->doc()->securityOrigin()->canRequest(url)) {
407 XMLDocumentParserScope::currentCachedResourceLoader->printAccessDeniedMessage(url);
414 static void* openFunc(const char* uri)
416 ASSERT(XMLDocumentParserScope::currentCachedResourceLoader);
417 ASSERT(currentThread() == libxmlLoaderThread);
419 KURL url(KURL(), uri);
421 if (!shouldAllowExternalLoad(url))
422 return &globalDescriptor;
425 ResourceResponse response;
430 CachedResourceLoader* cachedResourceLoader = XMLDocumentParserScope::currentCachedResourceLoader;
431 XMLDocumentParserScope scope(0);
432 // FIXME: We should restore the original global error handler as well.
434 if (cachedResourceLoader->frame())
435 cachedResourceLoader->frame()->loader()->loadResourceSynchronously(url, AllowStoredCredentials, error, response, data);
438 // We have to check the URL again after the load to catch redirects.
439 // See <https://bugs.webkit.org/show_bug.cgi?id=21963>.
440 if (!shouldAllowExternalLoad(response.url()))
441 return &globalDescriptor;
443 return new OffsetBuffer(data);
446 static int readFunc(void* context, char* buffer, int len)
448 // Do 0-byte reads in case of a null descriptor
449 if (context == &globalDescriptor)
452 OffsetBuffer* data = static_cast<OffsetBuffer*>(context);
453 return data->readOutBytes(buffer, len);
456 static int writeFunc(void*, const char*, int)
458 // Always just do 0-byte writes
462 static int closeFunc(void* context)
464 if (context != &globalDescriptor) {
465 OffsetBuffer* data = static_cast<OffsetBuffer*>(context);
472 static void errorFunc(void*, const char*, ...)
474 // FIXME: It would be nice to display error messages somewhere.
478 static bool didInit = false;
480 PassRefPtr<XMLParserContext> XMLParserContext::createStringParser(xmlSAXHandlerPtr handlers, void* userData)
484 xmlRegisterInputCallbacks(matchFunc, openFunc, readFunc, closeFunc);
485 xmlRegisterOutputCallbacks(matchFunc, openFunc, writeFunc, closeFunc);
486 libxmlLoaderThread = currentThread();
490 xmlParserCtxtPtr parser = xmlCreatePushParserCtxt(handlers, 0, 0, 0, 0);
491 parser->_private = userData;
492 parser->replaceEntities = true;
493 switchToUTF16(parser);
495 return adoptRef(new XMLParserContext(parser));
499 // Chunk should be encoded in UTF-8
500 PassRefPtr<XMLParserContext> XMLParserContext::createMemoryParser(xmlSAXHandlerPtr handlers, void* userData, const char* chunk)
504 xmlRegisterInputCallbacks(matchFunc, openFunc, readFunc, closeFunc);
505 xmlRegisterOutputCallbacks(matchFunc, openFunc, writeFunc, closeFunc);
506 libxmlLoaderThread = currentThread();
510 xmlParserCtxtPtr parser = xmlCreateMemoryParserCtxt(chunk, xmlStrlen((const xmlChar*)chunk));
515 // Copy the sax handler
516 memcpy(parser->sax, handlers, sizeof(xmlSAXHandler));
518 // Set parser options.
519 // XML_PARSE_NODICT: default dictionary option.
520 // XML_PARSE_NOENT: force entities substitutions.
521 xmlCtxtUseOptions(parser, XML_PARSE_NODICT | XML_PARSE_NOENT);
523 // Internal initialization
525 parser->instate = XML_PARSER_CONTENT; // We are parsing a CONTENT
527 parser->str_xml = xmlDictLookup(parser->dict, BAD_CAST "xml", 3);
528 parser->str_xmlns = xmlDictLookup(parser->dict, BAD_CAST "xmlns", 5);
529 parser->str_xml_ns = xmlDictLookup(parser->dict, XML_XML_NAMESPACE, 36);
530 parser->_private = userData;
532 return adoptRef(new XMLParserContext(parser));
535 // --------------------------------
537 bool XMLDocumentParser::supportsXMLVersion(const String& version)
539 return version == "1.0";
542 XMLDocumentParser::XMLDocumentParser(Document* document, FrameView* frameView)
543 : ScriptableDocumentParser(document)
546 , m_pendingCallbacks(new PendingCallbacks)
547 , m_currentNode(document)
549 , m_sawXSLTransform(false)
550 , m_sawFirstElement(false)
551 , m_isXHTMLDocument(false)
553 , m_isXHTMLMPDocument(false)
554 , m_hasDocTypeDeclaration(false)
556 , m_parserPaused(false)
557 , m_requestingScript(false)
558 , m_finishCalled(false)
561 , m_lastErrorColumn(0)
563 , m_scriptStartPosition(TextPosition1::belowRangePosition())
564 , m_parsingFragment(false)
565 , m_scriptingPermission(FragmentScriptingAllowed)
569 XMLDocumentParser::XMLDocumentParser(DocumentFragment* fragment, Element* parentElement, FragmentScriptingPermission scriptingPermission)
570 : ScriptableDocumentParser(fragment->document())
573 , m_pendingCallbacks(new PendingCallbacks)
574 , m_currentNode(fragment)
576 , m_sawXSLTransform(false)
577 , m_sawFirstElement(false)
578 , m_isXHTMLDocument(false)
580 , m_isXHTMLMPDocument(false)
581 , m_hasDocTypeDeclaration(false)
583 , m_parserPaused(false)
584 , m_requestingScript(false)
585 , m_finishCalled(false)
588 , m_lastErrorColumn(0)
590 , m_scriptStartPosition(TextPosition1::belowRangePosition())
591 , m_parsingFragment(true)
592 , m_scriptingPermission(scriptingPermission)
596 // Add namespaces based on the parent node
597 Vector<Element*> elemStack;
598 while (parentElement) {
599 elemStack.append(parentElement);
601 ContainerNode* n = parentElement->parentNode();
602 if (!n || !n->isElementNode())
604 parentElement = static_cast<Element*>(n);
607 if (elemStack.isEmpty())
610 for (Element* element = elemStack.last(); !elemStack.isEmpty(); elemStack.removeLast()) {
611 if (NamedNodeMap* attrs = element->attributes()) {
612 for (unsigned i = 0; i < attrs->length(); i++) {
613 Attribute* attr = attrs->attributeItem(i);
614 if (attr->localName() == xmlnsAtom)
615 m_defaultNamespaceURI = attr->value();
616 else if (attr->prefix() == xmlnsAtom)
617 m_prefixToNamespaceMap.set(attr->localName(), attr->value());
622 // If the parent element is not in document tree, there may be no xmlns attribute; just default to the parent's namespace.
623 if (m_defaultNamespaceURI.isNull() && !parentElement->inDocument())
624 m_defaultNamespaceURI = parentElement->namespaceURI();
627 XMLParserContext::~XMLParserContext()
629 if (m_context->myDoc)
630 xmlFreeDoc(m_context->myDoc);
631 xmlFreeParserCtxt(m_context);
634 XMLDocumentParser::~XMLDocumentParser()
636 // The XMLDocumentParser will always be detached before being destroyed.
637 ASSERT(m_currentNodeStack.isEmpty());
638 ASSERT(!m_currentNode);
640 // FIXME: m_pendingScript handling should be moved into XMLDocumentParser.cpp!
642 m_pendingScript->removeClient(this);
645 void XMLDocumentParser::doWrite(const String& parseString)
647 ASSERT(!isDetached());
649 initializeParserContext();
651 // Protect the libxml context from deletion during a callback
652 RefPtr<XMLParserContext> context = m_context;
654 // libXML throws an error if you try to switch the encoding for an empty string.
655 if (parseString.length()) {
656 // JavaScript may cause the parser to detach during xmlParseChunk
657 // keep this alive until this function is done.
658 RefPtr<XMLDocumentParser> protect(this);
660 switchToUTF16(context->context());
661 XMLDocumentParserScope scope(document()->cachedResourceLoader());
662 xmlParseChunk(context->context(), reinterpret_cast<const char*>(parseString.characters()), sizeof(UChar) * parseString.length(), 0);
664 // JavaScript (which may be run under the xmlParseChunk callstack) may
665 // cause the parser to be stopped or detached.
670 // FIXME: Why is this here? And why is it after we process the passed source?
671 if (document()->decoder() && document()->decoder()->sawError()) {
672 // If the decoder saw an error, report it as fatal (stops parsing)
673 handleError(fatal, "Encoding error", context->context()->input->line, context->context()->input->col);
677 static inline String toString(const xmlChar* string, size_t size)
679 return String::fromUTF8(reinterpret_cast<const char*>(string), size);
682 static inline String toString(const xmlChar* string)
684 return String::fromUTF8(reinterpret_cast<const char*>(string));
687 static inline AtomicString toAtomicString(const xmlChar* string, size_t size)
689 // FIXME: Use AtomicString::fromUTF8.
690 return AtomicString(toString(string, size));
693 static inline AtomicString toAtomicString(const xmlChar* string)
695 // FIXME: Use AtomicString::fromUTF8.
696 return AtomicString(toString(string));
699 struct _xmlSAX2Namespace {
700 const xmlChar* prefix;
703 typedef struct _xmlSAX2Namespace xmlSAX2Namespace;
705 static inline void handleElementNamespaces(Element* newElement, const xmlChar** libxmlNamespaces, int nb_namespaces, ExceptionCode& ec, FragmentScriptingPermission scriptingPermission)
707 xmlSAX2Namespace* namespaces = reinterpret_cast<xmlSAX2Namespace*>(libxmlNamespaces);
708 for (int i = 0; i < nb_namespaces; i++) {
709 AtomicString namespaceQName = xmlnsAtom;
710 AtomicString namespaceURI = toAtomicString(namespaces[i].uri);
711 if (namespaces[i].prefix)
712 namespaceQName = "xmlns:" + toString(namespaces[i].prefix);
713 newElement->setAttributeNS(XMLNSNames::xmlnsNamespaceURI, namespaceQName, namespaceURI, ec, scriptingPermission);
714 if (ec) // exception setting attributes
719 struct _xmlSAX2Attributes {
720 const xmlChar* localname;
721 const xmlChar* prefix;
723 const xmlChar* value;
726 typedef struct _xmlSAX2Attributes xmlSAX2Attributes;
728 static inline void handleElementAttributes(Element* newElement, const xmlChar** libxmlAttributes, int nb_attributes, ExceptionCode& ec, FragmentScriptingPermission scriptingPermission)
730 xmlSAX2Attributes* attributes = reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes);
731 for (int i = 0; i < nb_attributes; i++) {
732 int valueLength = static_cast<int>(attributes[i].end - attributes[i].value);
733 AtomicString attrValue = toAtomicString(attributes[i].value, valueLength);
734 String attrPrefix = toString(attributes[i].prefix);
735 AtomicString attrURI = attrPrefix.isEmpty() ? AtomicString() : toAtomicString(attributes[i].uri);
736 AtomicString attrQName = attrPrefix.isEmpty() ? toAtomicString(attributes[i].localname) : AtomicString(attrPrefix + ":" + toString(attributes[i].localname));
738 newElement->setAttributeNS(attrURI, attrQName, attrValue, ec, scriptingPermission);
739 if (ec) // exception setting attributes
744 void XMLDocumentParser::startElementNs(const xmlChar* xmlLocalName, const xmlChar* xmlPrefix, const xmlChar* xmlURI, int nb_namespaces,
745 const xmlChar** libxmlNamespaces, int nb_attributes, int nb_defaulted, const xmlChar** libxmlAttributes)
750 if (m_parserPaused) {
751 m_pendingCallbacks->appendStartElementNSCallback(xmlLocalName, xmlPrefix, xmlURI, nb_namespaces, libxmlNamespaces,
752 nb_attributes, nb_defaulted, libxmlAttributes);
757 // check if the DOCTYPE Declaration of XHTMLMP document exists
758 if (!m_hasDocTypeDeclaration && document()->isXHTMLMPDocument()) {
759 handleError(fatal, "DOCTYPE declaration lost.", lineNumber(), columnNumber());
766 AtomicString localName = toAtomicString(xmlLocalName);
767 AtomicString uri = toAtomicString(xmlURI);
768 AtomicString prefix = toAtomicString(xmlPrefix);
770 if (m_parsingFragment && uri.isNull()) {
771 if (!prefix.isNull())
772 uri = m_prefixToNamespaceMap.get(prefix);
774 uri = m_defaultNamespaceURI;
778 if (!m_sawFirstElement && isXHTMLMPDocument()) {
779 // As per the section 7.1 of OMA-WAP-XHTMLMP-V1_1-20061020-A.pdf,
780 // we should make sure that the root element MUST be 'html' and
781 // ensure the name of the default namespace on the root elment 'html'
782 // MUST be 'http://www.w3.org/1999/xhtml'
783 if (localName != HTMLNames::htmlTag.localName()) {
784 handleError(fatal, "XHTMLMP document expects 'html' as root element.", lineNumber(), columnNumber());
789 m_defaultNamespaceURI = HTMLNames::xhtmlNamespaceURI;
790 uri = m_defaultNamespaceURI;
795 bool isFirstElement = !m_sawFirstElement;
796 m_sawFirstElement = true;
798 QualifiedName qName(prefix, localName, uri);
799 RefPtr<Element> newElement = document()->createElement(qName, true);
805 ExceptionCode ec = 0;
806 handleElementNamespaces(newElement.get(), libxmlNamespaces, nb_namespaces, ec, m_scriptingPermission);
812 handleElementAttributes(newElement.get(), libxmlAttributes, nb_attributes, ec, m_scriptingPermission);
818 newElement->beginParsingChildren();
820 ScriptElement* scriptElement = toScriptElement(newElement.get());
822 m_scriptStartPosition = textPositionOneBased();
824 m_currentNode->deprecatedParserAddChild(newElement.get());
826 pushCurrentNode(newElement.get());
827 if (m_view && !newElement->attached())
828 newElement->attach();
830 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
831 if (newElement->hasTagName(HTMLNames::htmlTag))
832 static_cast<HTMLHtmlElement*>(newElement.get())->insertedByParser();
835 if (!m_parsingFragment && isFirstElement && document()->frame())
836 document()->frame()->loader()->dispatchDocumentElementAvailable();
839 void XMLDocumentParser::endElementNs()
844 if (m_parserPaused) {
845 m_pendingCallbacks->appendEndElementNSCallback();
851 Node* n = m_currentNode;
852 n->finishParsingChildren();
854 if (m_scriptingPermission == FragmentScriptingNotAllowed && n->isElementNode() && toScriptElement(static_cast<Element*>(n))) {
861 if (!n->isElementNode() || !m_view) {
866 Element* element = static_cast<Element*>(n);
868 // The element's parent may have already been removed from document.
869 // Parsing continues in this case, but scripts aren't executed.
870 if (!element->inDocument()) {
875 ScriptElement* scriptElement = toScriptElement(element);
876 if (!scriptElement) {
881 // Don't load external scripts for standalone documents (for now).
882 ASSERT(!m_pendingScript);
883 m_requestingScript = true;
886 if (!scriptElement->shouldExecuteAsJavaScript())
887 document()->setShouldProcessNoscriptElement(true);
891 // FIXME: Script execution should be shared should be shared between
892 // the libxml2 and Qt XMLDocumentParser implementations.
894 // JavaScript can detach the parser. Make sure this is not released
895 // before the end of this method.
896 RefPtr<XMLDocumentParser> protect(this);
898 String scriptHref = scriptElement->sourceAttributeValue();
899 if (!scriptHref.isEmpty()) {
900 // we have a src attribute
901 String scriptCharset = scriptElement->scriptCharset();
902 if (element->dispatchBeforeLoadEvent(scriptHref) &&
903 (m_pendingScript = document()->cachedResourceLoader()->requestScript(scriptHref, scriptCharset))) {
904 m_scriptElement = element;
905 m_pendingScript->addClient(this);
907 // m_pendingScript will be 0 if script was already loaded and ref() executed it
913 m_view->frame()->script()->executeScript(ScriptSourceCode(scriptElement->scriptContent(), document()->url(), m_scriptStartPosition));
915 // JavaScript may have detached the parser
919 m_requestingScript = false;
923 void XMLDocumentParser::characters(const xmlChar* s, int len)
928 if (m_parserPaused) {
929 m_pendingCallbacks->appendCharactersCallback(s, len);
933 if (!m_currentNode->isTextNode())
935 m_bufferedText.append(s, len);
938 void XMLDocumentParser::error(ErrorType type, const char* message, va_list args)
943 #if COMPILER(MSVC) || COMPILER(RVCT)
945 vsnprintf(m, sizeof(m) - 1, message, args);
948 if (vasprintf(&m, message, args) == -1)
953 m_pendingCallbacks->appendErrorCallback(type, reinterpret_cast<const xmlChar*>(m), lineNumber(), columnNumber());
955 handleError(type, m, lineNumber(), columnNumber());
957 #if !COMPILER(MSVC) && !COMPILER(RVCT)
962 void XMLDocumentParser::processingInstruction(const xmlChar* target, const xmlChar* data)
967 if (m_parserPaused) {
968 m_pendingCallbacks->appendProcessingInstructionCallback(target, data);
974 // ### handle exceptions
976 RefPtr<ProcessingInstruction> pi = document()->createProcessingInstruction(
977 toString(target), toString(data), exception);
981 pi->setCreatedByParser(true);
983 m_currentNode->deprecatedParserAddChild(pi.get());
984 if (m_view && !pi->attached())
987 pi->finishParsingChildren();
990 m_sawXSLTransform = !m_sawFirstElement && pi->isXSL();
991 if (m_sawXSLTransform && !document()->transformSourceDocument())
996 void XMLDocumentParser::cdataBlock(const xmlChar* s, int len)
1001 if (m_parserPaused) {
1002 m_pendingCallbacks->appendCDATABlockCallback(s, len);
1008 RefPtr<Node> newNode = CDATASection::create(document(), toString(s, len));
1009 m_currentNode->deprecatedParserAddChild(newNode.get());
1010 if (m_view && !newNode->attached())
1014 void XMLDocumentParser::comment(const xmlChar* s)
1019 if (m_parserPaused) {
1020 m_pendingCallbacks->appendCommentCallback(s);
1026 RefPtr<Node> newNode = Comment::create(document(), toString(s));
1027 m_currentNode->deprecatedParserAddChild(newNode.get());
1028 if (m_view && !newNode->attached())
1032 void XMLDocumentParser::startDocument(const xmlChar* version, const xmlChar* encoding, int standalone)
1034 ExceptionCode ec = 0;
1037 document()->setXMLVersion(toString(version), ec);
1038 document()->setXMLStandalone(standalone == 1, ec); // possible values are 0, 1, and -1
1040 document()->setXMLEncoding(toString(encoding));
1043 void XMLDocumentParser::endDocument()
1047 m_hasDocTypeDeclaration = false;
1051 void XMLDocumentParser::internalSubset(const xmlChar* name, const xmlChar* externalID, const xmlChar* systemID)
1056 if (m_parserPaused) {
1057 m_pendingCallbacks->appendInternalSubsetCallback(name, externalID, systemID);
1062 #if ENABLE(WML) || ENABLE(XHTMLMP)
1063 String extId = toString(externalID);
1067 && extId != "-//WAPFORUM//DTD WML 1.3//EN"
1068 && extId != "-//WAPFORUM//DTD WML 1.2//EN"
1069 && extId != "-//WAPFORUM//DTD WML 1.1//EN"
1070 && extId != "-//WAPFORUM//DTD WML 1.0//EN")
1071 handleError(fatal, "Invalid DTD Public ID", lineNumber(), columnNumber());
1074 String dtdName = toString(name);
1075 if (extId == "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
1076 || extId == "-//WAPFORUM//DTD XHTML Mobile 1.1//EN") {
1077 if (dtdName != HTMLNames::htmlTag.localName()) {
1078 handleError(fatal, "Invalid DOCTYPE declaration, expected 'html' as root element.", lineNumber(), columnNumber());
1082 if (document()->isXHTMLMPDocument())
1083 setIsXHTMLMPDocument(true);
1085 setIsXHTMLDocument(true);
1087 m_hasDocTypeDeclaration = true;
1091 document()->parserAddChild(DocumentType::create(document(), toString(name), toString(externalID), toString(systemID)));
1095 static inline XMLDocumentParser* getParser(void* closure)
1097 xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(closure);
1098 return static_cast<XMLDocumentParser*>(ctxt->_private);
1101 // This is a hack around http://bugzilla.gnome.org/show_bug.cgi?id=159219
1102 // Otherwise libxml seems to call all the SAX callbacks twice for any replaced entity.
1103 static inline bool hackAroundLibXMLEntityBug(void* closure)
1105 #if LIBXML_VERSION >= 20627
1106 UNUSED_PARAM(closure);
1108 // This bug has been fixed in libxml 2.6.27.
1111 return static_cast<xmlParserCtxtPtr>(closure)->node;
1115 static void startElementNsHandler(void* closure, const xmlChar* localname, const xmlChar* prefix, const xmlChar* uri, int nb_namespaces, const xmlChar** namespaces, int nb_attributes, int nb_defaulted, const xmlChar** libxmlAttributes)
1117 if (hackAroundLibXMLEntityBug(closure))
1120 getParser(closure)->startElementNs(localname, prefix, uri, nb_namespaces, namespaces, nb_attributes, nb_defaulted, libxmlAttributes);
1123 static void endElementNsHandler(void* closure, const xmlChar*, const xmlChar*, const xmlChar*)
1125 if (hackAroundLibXMLEntityBug(closure))
1128 getParser(closure)->endElementNs();
1131 static void charactersHandler(void* closure, const xmlChar* s, int len)
1133 if (hackAroundLibXMLEntityBug(closure))
1136 getParser(closure)->characters(s, len);
1139 static void processingInstructionHandler(void* closure, const xmlChar* target, const xmlChar* data)
1141 if (hackAroundLibXMLEntityBug(closure))
1144 getParser(closure)->processingInstruction(target, data);
1147 static void cdataBlockHandler(void* closure, const xmlChar* s, int len)
1149 if (hackAroundLibXMLEntityBug(closure))
1152 getParser(closure)->cdataBlock(s, len);
1155 static void commentHandler(void* closure, const xmlChar* comment)
1157 if (hackAroundLibXMLEntityBug(closure))
1160 getParser(closure)->comment(comment);
1163 WTF_ATTRIBUTE_PRINTF(2, 3)
1164 static void warningHandler(void* closure, const char* message, ...)
1167 va_start(args, message);
1168 getParser(closure)->error(XMLDocumentParser::warning, message, args);
1172 WTF_ATTRIBUTE_PRINTF(2, 3)
1173 static void fatalErrorHandler(void* closure, const char* message, ...)
1176 va_start(args, message);
1177 getParser(closure)->error(XMLDocumentParser::fatal, message, args);
1181 WTF_ATTRIBUTE_PRINTF(2, 3)
1182 static void normalErrorHandler(void* closure, const char* message, ...)
1185 va_start(args, message);
1186 getParser(closure)->error(XMLDocumentParser::nonFatal, message, args);
1190 // Using a static entity and marking it XML_INTERNAL_PREDEFINED_ENTITY is
1191 // a hack to avoid malloc/free. Using a global variable like this could cause trouble
1192 // if libxml implementation details were to change
1193 static xmlChar sharedXHTMLEntityResult[5] = {0, 0, 0, 0, 0};
1195 static xmlEntityPtr sharedXHTMLEntity()
1197 static xmlEntity entity;
1199 entity.type = XML_ENTITY_DECL;
1200 entity.orig = sharedXHTMLEntityResult;
1201 entity.content = sharedXHTMLEntityResult;
1202 entity.etype = XML_INTERNAL_PREDEFINED_ENTITY;
1207 static xmlEntityPtr getXHTMLEntity(const xmlChar* name)
1209 UChar c = decodeNamedEntity(reinterpret_cast<const char*>(name));
1213 CString value = String(&c, 1).utf8();
1214 ASSERT(value.length() < 5);
1215 xmlEntityPtr entity = sharedXHTMLEntity();
1216 entity->length = value.length();
1217 entity->name = name;
1218 memcpy(sharedXHTMLEntityResult, value.data(), entity->length + 1);
1223 static xmlEntityPtr getEntityHandler(void* closure, const xmlChar* name)
1225 xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(closure);
1226 xmlEntityPtr ent = xmlGetPredefinedEntity(name);
1228 ent->etype = XML_INTERNAL_PREDEFINED_ENTITY;
1232 ent = xmlGetDocEntity(ctxt->myDoc, name);
1233 if (!ent && (getParser(closure)->isXHTMLDocument()
1235 || getParser(closure)->isXHTMLMPDocument()
1238 || getParser(closure)->isWMLDocument()
1241 ent = getXHTMLEntity(name);
1243 ent->etype = XML_INTERNAL_GENERAL_ENTITY;
1249 static void startDocumentHandler(void* closure)
1251 xmlParserCtxt* ctxt = static_cast<xmlParserCtxt*>(closure);
1252 switchToUTF16(ctxt);
1253 getParser(closure)->startDocument(ctxt->version, ctxt->encoding, ctxt->standalone);
1254 xmlSAX2StartDocument(closure);
1257 static void endDocumentHandler(void* closure)
1259 getParser(closure)->endDocument();
1260 xmlSAX2EndDocument(closure);
1263 static void internalSubsetHandler(void* closure, const xmlChar* name, const xmlChar* externalID, const xmlChar* systemID)
1265 getParser(closure)->internalSubset(name, externalID, systemID);
1266 xmlSAX2InternalSubset(closure, name, externalID, systemID);
1269 static void externalSubsetHandler(void* closure, const xmlChar*, const xmlChar* externalId, const xmlChar*)
1271 String extId = toString(externalId);
1272 if ((extId == "-//W3C//DTD XHTML 1.0 Transitional//EN")
1273 || (extId == "-//W3C//DTD XHTML 1.1//EN")
1274 || (extId == "-//W3C//DTD XHTML 1.0 Strict//EN")
1275 || (extId == "-//W3C//DTD XHTML 1.0 Frameset//EN")
1276 || (extId == "-//W3C//DTD XHTML Basic 1.0//EN")
1277 || (extId == "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN")
1278 || (extId == "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN")
1279 || (extId == "-//WAPFORUM//DTD XHTML Mobile 1.0//EN")
1281 getParser(closure)->setIsXHTMLDocument(true); // controls if we replace entities or not.
1284 static void ignorableWhitespaceHandler(void*, const xmlChar*, int)
1286 // nothing to do, but we need this to work around a crasher
1287 // http://bugzilla.gnome.org/show_bug.cgi?id=172255
1288 // http://bugs.webkit.org/show_bug.cgi?id=5792
1291 void XMLDocumentParser::initializeParserContext(const char* chunk)
1294 memset(&sax, 0, sizeof(sax));
1296 sax.error = normalErrorHandler;
1297 sax.fatalError = fatalErrorHandler;
1298 sax.characters = charactersHandler;
1299 sax.processingInstruction = processingInstructionHandler;
1300 sax.cdataBlock = cdataBlockHandler;
1301 sax.comment = commentHandler;
1302 sax.warning = warningHandler;
1303 sax.startElementNs = startElementNsHandler;
1304 sax.endElementNs = endElementNsHandler;
1305 sax.getEntity = getEntityHandler;
1306 sax.startDocument = startDocumentHandler;
1307 sax.endDocument = endDocumentHandler;
1308 sax.internalSubset = internalSubsetHandler;
1309 sax.externalSubset = externalSubsetHandler;
1310 sax.ignorableWhitespace = ignorableWhitespaceHandler;
1311 sax.entityDecl = xmlSAX2EntityDecl;
1312 sax.initialized = XML_SAX2_MAGIC;
1313 DocumentParser::startParsing();
1315 m_sawXSLTransform = false;
1316 m_sawFirstElement = false;
1318 XMLDocumentParserScope scope(document()->cachedResourceLoader());
1319 if (m_parsingFragment)
1320 m_context = XMLParserContext::createMemoryParser(&sax, this, chunk);
1323 m_context = XMLParserContext::createStringParser(&sax, this);
1327 void XMLDocumentParser::doEnd()
1330 if (m_sawXSLTransform) {
1331 void* doc = xmlDocPtrForString(document()->cachedResourceLoader(), m_originalSourceForTransform, document()->url().string());
1332 document()->setTransformSource(new TransformSource(doc));
1334 document()->setParsing(false); // Make the doc think it's done, so it will apply xsl sheets.
1335 document()->styleSelectorChanged(RecalcStyleImmediately);
1336 document()->setParsing(true);
1337 DocumentParser::stopParsing();
1345 // Tell libxml we're done.
1347 XMLDocumentParserScope scope(document()->cachedResourceLoader());
1348 xmlParseChunk(context(), 0, 0, 1);
1356 void* xmlDocPtrForString(CachedResourceLoader* cachedResourceLoader, const String& source, const String& url)
1358 if (source.isEmpty())
1361 // Parse in a single chunk into an xmlDocPtr
1362 // FIXME: Hook up error handlers so that a failure to parse the main document results in
1363 // good error messages.
1364 const UChar BOM = 0xFEFF;
1365 const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
1367 XMLDocumentParserScope scope(cachedResourceLoader, errorFunc, 0);
1368 xmlDocPtr sourceDoc = xmlReadMemory(reinterpret_cast<const char*>(source.characters()),
1369 source.length() * sizeof(UChar),
1370 url.latin1().data(),
1371 BOMHighByte == 0xFF ? "UTF-16LE" : "UTF-16BE",
1372 XSLT_PARSE_OPTIONS);
1377 int XMLDocumentParser::lineNumber() const
1379 // FIXME: The implementation probably returns 1-based int, but method should return 0-based.
1380 return context() ? context()->input->line : 1;
1383 int XMLDocumentParser::columnNumber() const
1385 // FIXME: The implementation probably returns 1-based int, but method should return 0-based.
1386 return context() ? context()->input->col : 1;
1389 TextPosition0 XMLDocumentParser::textPosition() const
1391 xmlParserCtxtPtr context = this->context();
1393 return TextPosition0::minimumPosition();
1394 // FIXME: The context probably contains 1-based numbers, but we treat them as 0-based,
1395 // to be consistent with fixme's in lineNumber() and columnNumber
1397 return TextPosition0(WTF::ZeroBasedNumber::fromZeroBasedInt(context->input->line),
1398 WTF::ZeroBasedNumber::fromZeroBasedInt(context->input->col));
1401 // This method has a correct implementation, in contrast to textPosition() method.
1402 // It should replace textPosition().
1403 TextPosition1 XMLDocumentParser::textPositionOneBased() const
1405 xmlParserCtxtPtr context = this->context();
1407 return TextPosition1::minimumPosition();
1408 return TextPosition1(WTF::OneBasedNumber::fromOneBasedInt(context->input->line),
1409 WTF::OneBasedNumber::fromOneBasedInt(context->input->col));
1412 void XMLDocumentParser::stopParsing()
1414 DocumentParser::stopParsing();
1416 xmlStopParser(context());
1419 void XMLDocumentParser::resumeParsing()
1421 ASSERT(!isDetached());
1422 ASSERT(m_parserPaused);
1424 m_parserPaused = false;
1426 // First, execute any pending callbacks
1427 while (!m_pendingCallbacks->isEmpty()) {
1428 m_pendingCallbacks->callAndRemoveFirstCallback(this);
1430 // A callback paused the parser
1435 // Then, write any pending data
1436 SegmentedString rest = m_pendingSrc;
1437 m_pendingSrc.clear();
1440 // Finally, if finish() has been called and write() didn't result
1441 // in any further callbacks being queued, call end()
1442 if (m_finishCalled && m_pendingCallbacks->isEmpty())
1446 bool XMLDocumentParser::appendFragmentSource(const String& chunk)
1449 ASSERT(m_parsingFragment);
1451 CString chunkAsUtf8 = chunk.utf8();
1452 initializeParserContext(chunkAsUtf8.data());
1453 xmlParseContent(context());
1454 endDocument(); // Close any open text nodes.
1456 // FIXME: If this code is actually needed, it should probably move to finish()
1457 // XMLDocumentParserQt has a similar check (m_stream.error() == QXmlStreamReader::PrematureEndOfDocumentError) in doEnd().
1458 // Check if all the chunk has been processed.
1459 long bytesProcessed = xmlByteConsumed(context());
1460 if (bytesProcessed == -1 || ((unsigned long)bytesProcessed) != chunkAsUtf8.length()) {
1461 // FIXME: I don't believe we can hit this case without also having seen an error.
1462 // If we hit this ASSERT, we've found a test case which demonstrates the need for this code.
1467 // No error if the chunk is well formed or it is not but we have no error.
1468 return context()->wellFormed || !xmlCtxtGetLastError(context());
1471 // --------------------------------
1473 struct AttributeParseState {
1474 HashMap<String, String> attributes;
1478 static void attributesStartElementNsHandler(void* closure, const xmlChar* xmlLocalName, const xmlChar* /*xmlPrefix*/,
1479 const xmlChar* /*xmlURI*/, int /*nb_namespaces*/, const xmlChar** /*namespaces*/,
1480 int nb_attributes, int /*nb_defaulted*/, const xmlChar** libxmlAttributes)
1482 if (strcmp(reinterpret_cast<const char*>(xmlLocalName), "attrs") != 0)
1485 xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(closure);
1486 AttributeParseState* state = static_cast<AttributeParseState*>(ctxt->_private);
1488 state->gotAttributes = true;
1490 xmlSAX2Attributes* attributes = reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes);
1491 for (int i = 0; i < nb_attributes; i++) {
1492 String attrLocalName = toString(attributes[i].localname);
1493 int valueLength = (int) (attributes[i].end - attributes[i].value);
1494 String attrValue = toString(attributes[i].value, valueLength);
1495 String attrPrefix = toString(attributes[i].prefix);
1496 String attrQName = attrPrefix.isEmpty() ? attrLocalName : attrPrefix + ":" + attrLocalName;
1498 state->attributes.set(attrQName, attrValue);
1502 HashMap<String, String> parseAttributes(const String& string, bool& attrsOK)
1504 AttributeParseState state;
1505 state.gotAttributes = false;
1508 memset(&sax, 0, sizeof(sax));
1509 sax.startElementNs = attributesStartElementNsHandler;
1510 sax.initialized = XML_SAX2_MAGIC;
1511 RefPtr<XMLParserContext> parser = XMLParserContext::createStringParser(&sax, &state);
1512 String parseString = "<?xml version=\"1.0\"?><attrs " + string + " />";
1513 xmlParseChunk(parser->context(), reinterpret_cast<const char*>(parseString.characters()), parseString.length() * sizeof(UChar), 1);
1514 attrsOK = state.gotAttributes;
1515 return state.attributes;