Roll libxml to f93ca3e140a371b26366f747a408588c631e0fd1

add-fuzz-target.patch was merged upstream in 1bde1040

chromium-issue-1138555.patch was fixed upstream in b516ed18

Bug: 934413
Change-Id: I168c16d6882eea4d3523576126c2542d5d861be2
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2665758
Reviewed-by: Stephen Chenney <schenney@chromium.org>
Commit-Queue: Joey Arhar <jarhar@chromium.org>
Cr-Commit-Position: refs/heads/master@{#849631}
GitOrigin-RevId: 295c408e29eb7fcb0a15d26f7e4941b35201f59c
diff --git a/README.chromium b/README.chromium
index 8da443a..367462e 100644
--- a/README.chromium
+++ b/README.chromium
@@ -1,6 +1,6 @@
 Name: libxml
 URL: http://xmlsoft.org
-Version: 0b3c64d9f2f3e9ce1a98d8f19ee7a763c87e27d5
+Version: f93ca3e140a371b26366f747a408588c631e0fd1
 CPEPrefix: cpe:/a:xmlsoft:libxml2:2.9.9
 License: MIT
 License File: src/Copyright
@@ -22,8 +22,6 @@
 - chromium-issue-708434.patch: Guard against input counter overflow.
 - revert-non-recursive-xml-parsing.patch: Making parts of the XML parser
     non-recursive broke a few web platform tests.
-- add-fuzz-target.patch: Prevents autoreconf from failing on mac due to a
-    missing makefile for fuzz.
 - chromium-issue-1138555.patch: Change TRUE to 1 for ICU68 which remove the
   #define of TRUE.
 - Add helper classes in the chromium/ subdirectory.
diff --git a/chromium/add-fuzz-target.patch b/chromium/add-fuzz-target.patch
deleted file mode 100644
index 420d5c7..0000000
--- a/chromium/add-fuzz-target.patch
+++ /dev/null
@@ -1,13 +0,0 @@
-diff --git a/Makefile.am b/Makefile.am
-index 76a834ef..4ef0eb92 100644
---- a/Makefile.am
-+++ b/Makefile.am
-@@ -4,7 +4,7 @@ ACLOCAL_AMFLAGS = -I m4
- 
- SUBDIRS = include . doc example fuzz xstc $(PYTHON_SUBDIR)
- 
--DIST_SUBDIRS = include . doc example python xstc
-+DIST_SUBDIRS = include . doc example python xstc fuzz
- 
- AM_CPPFLAGS = -I$(top_builddir)/include -I$(srcdir)/include
- 
diff --git a/chromium/chromium-issue-1138555.patch b/chromium/chromium-issue-1138555.patch
deleted file mode 100644
index a5e1694..0000000
--- a/chromium/chromium-issue-1138555.patch
+++ /dev/null
@@ -1,31 +0,0 @@
-diff --git a/encoding.c b/encoding.c
-index c34aca44663c..47be560ede47 100644
---- a/encoding.c
-+++ b/encoding.c
-@@ -1858,7 +1858,7 @@ xmlIconvWrapper(iconv_t cd, unsigned char *out, int *outlen,
-  * @outlen:  the length of @out
-  * @in:  a pointer to an array of input bytes
-  * @inlen:  the length of @in
-- * @flush: if true, indicates end of input
-+ * @flush: if 1, indicates end of input
-  *
-  * Returns 0 if success, or
-  *     -1 by lack of space, or
-@@ -1898,7 +1898,7 @@ xmlUconvWrapper(uconv_t *cd, int toUnicode, unsigned char *out, int *outlen,
-     *inlen = ucv_in - (const char*) in;
-     *outlen = ucv_out - (char *) out;
-     if (U_SUCCESS(err)) {
--        /* reset pivot buf if this is the last call for input (flush==TRUE) */
-+        /* reset pivot buf if this is the last call for input (flush==1) */
-         if (flush)
-             cd->pivot_source = cd->pivot_target = cd->pivot_buf;
-         return 0;
-@@ -2004,7 +2004,7 @@ xmlEncOutputChunk(xmlCharEncodingHandler *handler, unsigned char *out,
- #ifdef LIBXML_ICU_ENABLED
-     else if (handler->uconv_out != NULL) {
-         ret = xmlUconvWrapper(handler->uconv_out, 0, out, outlen, in, inlen,
--                              TRUE);
-+                              1);
-     }
- #endif /* LIBXML_ICU_ENABLED */
-     else {
diff --git a/chromium/roll.py b/chromium/roll.py
index ce8e91f..90928be 100755
--- a/chromium/roll.py
+++ b/chromium/roll.py
@@ -72,9 +72,6 @@
     'chromium-issue-628581.patch',
     'libxml2-2.9.4-security-xpath-nodetab-uaf.patch',
     'chromium-issue-708434.patch',
-    # TODO(jarhar): Merge this back upstream.
-    'add-fuzz-target.patch',
-    'chromium-issue-1138555.patch',
 ]
 
 
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644
index 0000000..da0e5a9
--- /dev/null
+++ b/src/CMakeLists.txt
@@ -0,0 +1,765 @@
+cmake_minimum_required(VERSION 3.15)
+
+project(libxml2 C)
+
+include(CheckCSourceCompiles)
+include(CheckFunctionExists)
+include(CheckIncludeFiles)
+include(CheckLibraryExists)
+include(CheckStructHasMember)
+include(CheckSymbolExists)
+include(CMakePackageConfigHelpers)
+include(GNUInstallDirs)
+
+set(LIBXML_MAJOR_VERSION 2)
+set(LIBXML_MINOR_VERSION 9)
+set(LIBXML_MICRO_VERSION 10)
+
+set(VERSION "${LIBXML_MAJOR_VERSION}.${LIBXML_MINOR_VERSION}.${LIBXML_MICRO_VERSION}")
+set(LIBXML_VERSION ${LIBXML_MAJOR_VERSION}0${LIBXML_MINOR_VERSION}0${LIBXML_MICRO_VERSION})
+set(LIBXML_VERSION_STRING "${LIBXML_VERSION}")
+set(LIBXML_VERSION_EXTRA "")
+set(LIBXML_VERSION_NUMBER ${LIBXML_VERSION})
+
+option(BUILD_SHARED_LIBS "Build shared libraries" ON)
+set(LIBXML2_WITH_AUTOMATA ON)
+option(LIBXML2_WITH_C14N "Add the Canonicalization support" ON)
+option(LIBXML2_WITH_CATALOG "Add the Catalog support" ON)
+option(LIBXML2_WITH_DEBUG "Add the debugging module" ON)
+option(LIBXML2_WITH_DOCB "Add Docbook SGML support" ON)
+set(LIBXML2_WITH_EXPR ON)
+option(LIBXML2_WITH_FTP "Add the FTP support" ON)
+option(LIBXML2_WITH_HTML "Add the HTML support" ON)
+option(LIBXML2_WITH_HTTP "Add the HTTP support" ON)
+option(LIBXML2_WITH_ICONV "Add ICONV support" ON)
+option(LIBXML2_WITH_ICU "Add ICU support" OFF)
+option(LIBXML2_WITH_ISO8859X "Add ISO8859X support if no iconv" ON)
+option(LIBXML2_WITH_LEGACY "Add deprecated APIs for compatibility" ON)
+option(LIBXML2_WITH_LZMA "Use liblzma" ON)
+option(LIBXML2_WITH_MEM_DEBUG "Add the memory debugging module" OFF)
+option(LIBXML2_WITH_MODULES "Add the dynamic modules support" ON)
+option(LIBXML2_WITH_OUTPUT "Add the serialization support" ON)
+option(LIBXML2_WITH_PATTERN "Add the xmlPattern selection interface" ON)
+option(LIBXML2_WITH_PROGRAMS "Build programs" ON)
+option(LIBXML2_WITH_PUSH "Add the PUSH parser interfaces" ON)
+option(LIBXML2_WITH_PYTHON "Build Python bindings" ON)
+option(LIBXML2_WITH_READER "Add the xmlReader parsing interface" ON)
+option(LIBXML2_WITH_REGEXPS "Add Regular Expressions support" ON)
+option(LIBXML2_WITH_RUN_DEBUG "Add the runtime debugging module" OFF)
+option(LIBXML2_WITH_SAX1 "Add the older SAX1 interface" ON)
+option(LIBXML2_WITH_SCHEMAS "Add Relax-NG and Schemas support" ON)
+option(LIBXML2_WITH_SCHEMATRON "Add Schematron support" ON)
+option(LIBXML2_WITH_TESTS "Build tests" ON)
+option(LIBXML2_WITH_THREADS "Add multithread support" ON)
+option(LIBXML2_WITH_THREAD_ALLOC "Add per-thread memory" OFF)
+option(LIBXML2_WITH_TREE "Add the DOM like tree manipulation APIs" ON)
+set(LIBXML2_WITH_TRIO OFF)
+set(LIBXML2_WITH_UNICODE ON)
+option(LIBXML2_WITH_VALID "Add the DTD validation support" ON)
+option(LIBXML2_WITH_WRITER "Add the xmlWriter saving interface" ON)
+option(LIBXML2_WITH_XINCLUDE "Add the XInclude support" ON)
+option(LIBXML2_WITH_XPATH "Add the XPATH support" ON)
+option(LIBXML2_WITH_XPTR "Add the XPointer support" ON)
+option(LIBXML2_WITH_ZLIB "Use libz" ON)
+set(LIBXML2_XMLCONF_WORKING_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Working directory for XML Conformance Test Suite")
+
+if(LIBXML2_WITH_ICONV)
+	find_package(Iconv REQUIRED)
+endif()
+
+if(LIBXML2_WITH_ICU)
+	find_package(ICU REQUIRED COMPONENTS data i18n uc)
+endif()
+
+if(LIBXML2_WITH_LZMA)
+	find_package(LibLZMA REQUIRED)
+endif()
+
+if(LIBXML2_WITH_PYTHON)
+	check_include_files(unistd.h HAVE_UNISTD_H)
+	check_symbol_exists(F_GETFL fcntl.h HAVE_F_GETFL)
+	if(HAVE_UNISTD_H AND HAVE_F_GETFL)
+		find_package(Python COMPONENTS Interpreter Development REQUIRED)
+	else()
+		find_package(Python2 COMPONENTS Interpreter Development REQUIRED)
+		add_library(Python::Python ALIAS Python2::Python)
+		set(Python_EXECUTABLE ${Python2_EXECUTABLE})
+		set(Python_SITEARCH ${Python2_SITEARCH})
+	endif()
+	set(LIBXML2_PYTHON_INSTALL_DIR ${Python_SITEARCH} CACHE PATH "Python bindings install directory")
+endif()
+
+if(LIBXML2_WITH_THREADS)
+	find_package(Threads REQUIRED)
+endif()
+
+if(LIBXML2_WITH_ZLIB)
+	find_package(ZLIB REQUIRED)
+endif()
+
+foreach(VARIABLE IN ITEMS WITH_AUTOMATA WITH_C14N WITH_CATALOG WITH_DEBUG WITH_DOCB WITH_EXPR WITH_FTP WITH_HTML WITH_HTTP WITH_ICONV WITH_ICU WITH_ISO8859X WITH_LEGACY WITH_LZMA WITH_MEM_DEBUG WITH_MODULES WITH_OUTPUT WITH_PATTERN WITH_PUSH WITH_READER WITH_REGEXPS WITH_RUN_DEBUG WITH_SAX1 WITH_SCHEMAS WITH_SCHEMATRON WITH_THREADS WITH_THREAD_ALLOC WITH_TREE WITH_TRIO WITH_UNICODE WITH_VALID WITH_WRITER WITH_XINCLUDE WITH_XPATH WITH_XPTR WITH_ZLIB)
+	if(LIBXML2_${VARIABLE})
+		set(${VARIABLE} 1)
+	else()
+		set(${VARIABLE} 0)
+	endif()
+endforeach()
+
+set(MODULE_EXTENSION "${CMAKE_SHARED_LIBRARY_SUFFIX}")
+
+set(PACKAGE "libxml2")
+set(PACKAGE_BUGREPORT "xml@gnome.org")
+set(PACKAGE_NAME "libxml2")
+set(PACKAGE_STRING "libxml2 ${VERSION}")
+set(PACKAGE_TARNAME "libxml2")
+set(PACKAGE_URL "http://www.xmlsoft.org/")
+set(PACKAGE_VERSION ${VERSION})
+
+if(LIBLZMA_FOUND)
+	list(APPEND CMAKE_REQUIRED_LIBRARIES LibLZMA::LibLZMA)
+endif()
+
+if(Threads_FOUND)
+	list(APPEND CMAKE_REQUIRED_LIBRARIES Threads::Threads)
+endif()
+
+if(ZLIB_FOUND)
+	list(APPEND CMAKE_REQUIRED_LIBRARIES ZLIB::ZLIB)
+endif()
+
+if(MSVC)
+	configure_file(include/win32config.h config.h COPYONLY)
+else()
+	check_c_source_compiles("
+		void __attribute__((destructor))
+		f(void) {}
+		int main(void) { return 0; }
+	" ATTRIBUTE_DESTRUCTOR)
+	check_c_source_compiles("
+		#include <netdb.h>
+		int main() { (void) gethostbyname((const char*) \"\"); return 0; }
+	" GETHOSTBYNAME_ARG_CAST_CONST)
+	if(NOT GETHOSTBYNAME_ARG_CAST_CONST)
+		set(GETHOSTBYNAME_ARG_CAST "(char *)")
+	else()
+		set(GETHOSTBYNAME_ARG_CAST "/**/")
+	endif()
+	check_include_files(arpa/inet.h HAVE_ARPA_INET_H)
+	check_include_files(arpa/nameser.h HAVE_ARPA_NAMESER_H)
+	check_struct_has_member("struct sockaddr_storage" ss_family "sys/socket.h;sys/types.h" HAVE_SS_FAMILY)
+	check_struct_has_member("struct sockaddr_storage" __ss_family "sys/socket.h;sys/types.h" HAVE_BROKEN_SS_FAMILY)
+	if(HAVE_BROKEN_SS_FAMILY)
+		set(ss_family __ss_family)
+	endif()
+	check_function_exists(class HAVE_CLASS)
+	check_include_files(ctype.h HAVE_CTYPE_H)
+	check_include_files(dirent.h HAVE_DIRENT_H)
+	check_include_files(dlfcn.h HAVE_DLFCN_H)
+	check_library_exists(dl dlopen "" HAVE_DLOPEN)
+	check_include_files(dl.h HAVE_DL_H)
+	check_include_files(errno.h HAVE_ERRNO_H)
+	check_include_files(fcntl.h HAVE_FCNTL_H)
+	check_function_exists(finite HAVE_FINITE)
+	check_include_files(float.h HAVE_FLOAT_H)
+	check_function_exists(fpclass HAVE_FPCLASS)
+	check_function_exists(fprintf HAVE_FPRINTF)
+	check_function_exists(fp_class HAVE_FP_CLASS)
+	check_function_exists(ftime HAVE_FTIME)
+	check_function_exists(getaddrinfo HAVE_GETADDRINFO)
+	check_function_exists(gettimeofday HAVE_GETTIMEOFDAY)
+	check_include_files(inttypes.h HAVE_INTTYPES_H)
+	check_function_exists(isascii HAVE_ISASCII)
+	check_function_exists(isinf HAVE_ISINF)
+	check_function_exists(isnan HAVE_ISNAN)
+	check_function_exists(isnand HAVE_ISNAND)
+	check_library_exists(history append_history "" HAVE_LIBHISTORY)
+	check_library_exists(lzma lzma_code "" HAVE_LIBLZMA)
+	check_library_exists(pthread pthread_join "" HAVE_LIBPTHREAD)
+	check_library_exists(readline readline "" HAVE_LIBREADLINE)
+	check_library_exists(z gzread "" HAVE_LIBZ)
+	check_include_files(limits.h HAVE_LIMITS_H)
+	check_function_exists(localtime HAVE_LOCALTIME)
+	check_include_files(lzma.h HAVE_LZMA_H)
+	check_include_files(malloc.h HAVE_MALLOC_H)
+	check_include_files(math.h HAVE_MATH_H)
+	check_include_files(memory.h HAVE_MEMORY_H)
+	check_function_exists(mmap HAVE_MMAP)
+	check_function_exists(munmap HAVE_MUNMAP)
+	check_symbol_exists(DIR ndir.h HAVE_NDIR_H)
+	check_include_files(netdb.h HAVE_NETDB_H)
+	check_include_files(netinet/in.h HAVE_NETINET_IN_H)
+	check_include_files(poll.h HAVE_POLL_H)
+	check_function_exists(printf HAVE_PRINTF)
+	check_include_files(pthread.h HAVE_PTHREAD_H)
+	check_function_exists(putenv HAVE_PUTENV)
+	check_function_exists(rand HAVE_RAND)
+	check_function_exists(rand_r HAVE_RAND_R)
+	check_include_files(resolv.h HAVE_RESOLV_H)
+	check_library_exists(dld shl_load "" HAVE_SHLLOAD)
+	check_function_exists(signal HAVE_SIGNAL)
+	check_include_files(signal.h HAVE_SIGNAL_H)
+	check_function_exists(snprintf HAVE_SNPRINTF)
+	check_function_exists(sprintf HAVE_SPRINTF)
+	check_function_exists(srand HAVE_SRAND)
+	check_function_exists(sscanf HAVE_SSCANF)
+	check_function_exists(stat HAVE_STAT)
+	check_include_files(stdarg.h HAVE_STDARG_H)
+	check_include_files(stdint.h HAVE_STDINT_H)
+	check_include_files(stdlib.h HAVE_STDLIB_H)
+	check_function_exists(strftime HAVE_STRFTIME)
+	check_include_files(strings.h HAVE_STRINGS_H)
+	check_include_files(string.h HAVE_STRING_H)
+	check_symbol_exists(DIR sys/dir.h HAVE_SYS_DIR_H)
+	check_include_files(sys/mman.h HAVE_SYS_MMAN_H)
+	check_symbol_exists(DIR sys/ndir.h HAVE_SYS_NDIR_H)
+	check_include_files(sys/select.h HAVE_SYS_SELECT_H)
+	check_include_files(sys/socket.h HAVE_SYS_SOCKET_H)
+	check_include_files(sys/stat.h HAVE_SYS_STAT_H)
+	check_include_files(sys/timeb.h HAVE_SYS_TIMEB_H)
+	check_include_files(sys/time.h HAVE_SYS_TIME_H)
+	check_include_files(sys/types.h HAVE_SYS_TYPES_H)
+	check_function_exists(time HAVE_TIME)
+	check_include_files(time.h HAVE_TIME_H)
+	check_include_files(unistd.h HAVE_UNISTD_H)
+	check_function_exists(va_copy HAVE_VA_COPY)
+	check_function_exists(vfprintf HAVE_VFPRINTF)
+	check_function_exists(vsnprintf HAVE_VSNPRINTF)
+	check_function_exists(vsprintf HAVE_VSPRINTF)
+	check_function_exists(__va_copy HAVE___VA_COPY)
+	check_c_source_compiles("
+		#include <stdlib.h>
+		#include <iconv.h>
+		extern
+		#ifdef __cplusplus
+		\"C\"
+		#endif
+		#if defined(__STDC__) || defined(__cplusplus)
+		size_t iconv(iconv_t cd, char** inbuf, size_t* inbytesleft, char** outbuf, size_t* outbytesleft);
+		#else
+		size_t iconv();
+		#endif
+		int main() { return 0; }
+	" ICONV_CONST_TEST)
+	if(NOT ICONV_CONST_TEST)
+		set(ICONV_CONST "const")
+	endif()
+	set(LT_OBJDIR ".libs/")
+	check_c_source_compiles("
+		#include <sys/socket.h>
+		#include <sys/types.h>
+		int main() { (void) send(1, (const char*) \"\", 1, 1); return 0; }
+	" SEND_ARG2_CAST_CONST)
+	if(NOT SEND_ARG2_CAST_CONST)
+		set(SEND_ARG2_CAST "(char *)")
+	else()
+		set(SEND_ARG2_CAST "/**/")
+	endif()
+	check_include_files("float.h;stdarg.h;stdlib.h;string.h" STDC_HEADERS)
+	check_c_source_compiles("
+		#include <stdarg.h>
+		void a(va_list* ap) {};
+		int main() { va_list ap1, ap2; a(&ap1); ap2 = (va_list) ap1; return 0; }
+	" VA_LIST_IS_ARRAY_TEST)
+	if(VA_LIST_IS_ARRAY_TEST)
+		set(VA_LIST_IS_ARRAY FALSE)
+	else()
+		set(VA_LIST_IS_ARRAY TRUE)
+	endif()
+	check_c_source_compiles("
+		#include <stddef.h>
+		#include <sys/socket.h>
+		#include <sys/types.h>
+		int main() { (void) getsockopt(1, 1, 1, NULL, (socklen_t*) NULL); return 0; }
+	" XML_SOCKLEN_T_SOCKLEN_T)
+	if(XML_SOCKLEN_T_SOCKLEN_T)
+		set(XML_SOCKLEN_T socklen_t)
+	else()
+		check_c_source_compiles("
+			#include <stddef.h>
+			#include <sys/socket.h>
+			#include <sys/types.h>
+			int main() { (void) getsockopt(1, 1, 1, NULL, (size_t*) NULL); return 0; }
+		" XML_SOCKLEN_T_SIZE_T)
+		if(XML_SOCKLEN_T_SIZE_T)
+			set(XML_SOCKLEN_T size_t)
+		else()
+			check_c_source_compiles("
+				#include <stddef.h>
+				#include <sys/socket.h>
+				#include <sys/types.h>
+				int main() { (void) getsockopt (1, 1, 1, NULL, (int*) NULL); return 0; }
+			" XML_SOCKLEN_T_INT)
+			set(XML_SOCKLEN_T int)
+		endif()
+	endif()
+	configure_file(config.h.cmake.in config.h)
+endif()
+
+set(
+	LIBXML2_HDRS
+	include/libxml/c14n.h
+	include/libxml/catalog.h
+	include/libxml/chvalid.h
+	include/libxml/debugXML.h
+	include/libxml/dict.h
+	include/libxml/DOCBparser.h
+	include/libxml/encoding.h
+	include/libxml/entities.h
+	include/libxml/globals.h
+	include/libxml/hash.h
+	include/libxml/HTMLparser.h
+	include/libxml/HTMLtree.h
+	include/libxml/list.h
+	include/libxml/nanoftp.h
+	include/libxml/nanohttp.h
+	include/libxml/parser.h
+	include/libxml/parserInternals.h
+	include/libxml/pattern.h
+	include/libxml/relaxng.h
+	include/libxml/SAX.h
+	include/libxml/SAX2.h
+	include/libxml/schemasInternals.h
+	include/libxml/schematron.h
+	include/libxml/threads.h
+	include/libxml/tree.h
+	include/libxml/uri.h
+	include/libxml/valid.h
+	include/libxml/xinclude.h
+	include/libxml/xlink.h
+	include/libxml/xmlIO.h
+	include/libxml/xmlautomata.h
+	include/libxml/xmlerror.h
+	include/libxml/xmlexports.h
+	include/libxml/xmlmemory.h
+	include/libxml/xmlmodule.h
+	include/libxml/xmlreader.h
+	include/libxml/xmlregexp.h
+	include/libxml/xmlsave.h
+	include/libxml/xmlschemas.h
+	include/libxml/xmlschemastypes.h
+	include/libxml/xmlstring.h
+	include/libxml/xmlunicode.h
+	include/libxml/xmlwriter.h
+	include/libxml/xpath.h
+	include/libxml/xpathInternals.h
+	include/libxml/xpointer.h
+)
+
+set(
+	LIBXML2_SRCS
+	buf.c
+	c14n.c
+	catalog.c
+	chvalid.c
+	debugXML.c
+	dict.c
+	encoding.c
+	entities.c
+	error.c
+	globals.c
+	hash.c
+	HTMLparser.c
+	HTMLtree.c
+	legacy.c
+	list.c
+	nanoftp.c
+	nanohttp.c
+	parser.c
+	parserInternals.c
+	pattern.c
+	relaxng.c
+	SAX.c
+	SAX2.c
+	schematron.c
+	threads.c
+	tree.c
+	uri.c
+	valid.c
+	xinclude.c
+	xlink.c
+	xmlIO.c
+	xmlmemory.c
+	xmlmodule.c
+	xmlreader.c
+	xmlregexp.c
+	xmlsave.c
+	xmlschemas.c
+	xmlschemastypes.c
+	xmlstring.c
+	xmlunicode.c
+	xmlwriter.c
+	xpath.c
+	xpointer.c
+	xzlib.c
+)
+
+if(WIN32)
+	list(APPEND LIBXML2_SRCS win32/libxml2.rc)
+	file(
+		WRITE
+		${CMAKE_CURRENT_BINARY_DIR}/rcVersion.h
+		"#define LIBXML_MAJOR_VERSION ${LIBXML_MAJOR_VERSION}\n"
+		"#define LIBXML_MINOR_VERSION ${LIBXML_MINOR_VERSION}\n"
+		"#define LIBXML_MICRO_VERSION ${LIBXML_MICRO_VERSION}\n"
+		"#define LIBXML_DOTTED_VERSION \"${VERSION}\"\n"
+	)
+endif()
+
+if(LIBXML2_WITH_SAX1)
+	list(APPEND LIBXML2_SRCS DOCBparser.c)
+endif()
+
+if(LIBXML2_WITH_TRIO)
+	list(APPEND LIBXML2_SRCS trio.c triostr.c)
+endif()
+
+add_library(LibXml2 ${LIBXML2_HDRS} ${LIBXML2_SRCS})
+
+if(NOT BUILD_SHARED_LIBS)
+	target_compile_definitions(LibXml2 INTERFACE LIBXML_STATIC)
+	set(XML_CFLAGS "-DLIBXML_STATIC")
+endif()
+
+if(LIBXML2_WITH_THREADS)
+	target_compile_definitions(LibXml2 PRIVATE _REENTRANT)
+	if(WIN32)
+		target_compile_definitions(LibXml2 PRIVATE HAVE_WIN32_THREADS)
+	endif()
+endif()
+
+target_include_directories(
+	LibXml2
+	PUBLIC
+	$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
+	$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+	$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}/libxml2>
+)
+
+if(HAVE_DLOPEN)
+	target_link_libraries(LibXml2 PRIVATE dl)
+	set(MODULE_PLATFORM_LIBS "-ldl")
+endif()
+
+if(HAVE_SHLLOAD)
+	target_link_libraries(LibXml2 PRIVATE dld)
+	set(MODULE_PLATFORM_LIBS "-ldld")
+endif()
+
+if(UNIX)
+	target_link_libraries(LibXml2 PRIVATE m)
+	set(M_LIBS "-lm")
+endif()
+
+if(WIN32)
+	target_link_libraries(LibXml2 PRIVATE ws2_32)
+	set(WIN32_EXTRA_LIBADD "-lws2_32")
+endif()
+
+if(LIBXML2_WITH_ICONV)
+	target_link_libraries(LibXml2 PUBLIC Iconv::Iconv)
+	if(NOT Iconv_IS_BUILT_IN)
+		set(ICONV_LIBS "-liconv")
+	endif()
+endif()
+
+if(LIBXML2_WITH_ICU)
+	target_link_libraries(LibXml2 PRIVATE ICU::data ICU::i18n ICU::uc)
+	if(WIN32)
+		set(ICU_LIBS "-licudt -licuin -licuuc")
+	else()
+		set(ICU_LIBS "-licudata -licui18n -licuuc")
+	endif()
+endif()
+
+if(LIBXML2_WITH_LZMA)
+	target_link_libraries(LibXml2 PRIVATE LibLZMA::LibLZMA)
+	set(LZMA_LIBS "-llzma")
+endif()
+
+if(LIBXML2_WITH_THREADS)
+	target_link_libraries(LibXml2 PRIVATE Threads::Threads)
+	set(THREAD_LIBS ${CMAKE_THREAD_LIBS_INIT})
+endif()
+
+if(LIBXML2_WITH_ZLIB)
+	target_link_libraries(LibXml2 PRIVATE ZLIB::ZLIB)
+	set(Z_LIBS "-lz")
+endif()
+
+set_target_properties(
+	LibXml2
+	PROPERTIES
+	IMPORT_PREFIX lib
+	OUTPUT_NAME xml2
+	POSITION_INDEPENDENT_CODE ON
+	PREFIX lib
+	VERSION ${VERSION}
+)
+
+if(WIN32)
+	if(BUILD_SHARED_LIBS)
+		set_target_properties(
+			LibXml2
+			PROPERTIES
+			DEBUG_POSTFIX d
+		)
+	else()
+		set_target_properties(
+			LibXml2
+			PROPERTIES
+			DEBUG_POSTFIX sd
+			MINSIZEREL_POSTFIX s
+			RELEASE_POSTFIX s
+			RELWITHDEBINFO_POSTFIX s
+		)
+	endif()
+endif()
+
+install(FILES ${LIBXML2_HDRS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libxml2/libxml COMPONENT development)
+
+install(
+	TARGETS	LibXml2
+	EXPORT LibXml2
+	ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT development
+	LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT runtime NAMELINK_COMPONENT development
+	RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime
+)
+
+if(MSVC AND BUILD_SHARED_LIBS)
+	install(FILES $<TARGET_PDB_FILE:LibXml2> DESTINATION ${CMAKE_INSTALL_BINDIR} CONFIGURATIONS Debug RelWithDebInfo COMPONENT debug)
+endif()
+
+if(LIBXML2_WITH_PROGRAMS)
+	set(
+		PROGRAMS
+		xmlcatalog
+		xmllint
+	)
+	foreach(PROGRAM ${PROGRAMS})
+		add_executable(${PROGRAM} ${PROGRAM}.c)
+		target_link_libraries(${PROGRAM} LibXml2)
+		if(HAVE_LIBHISTORY)
+			target_link_libraries(${PROGRAM} history)
+		endif()
+		if(HAVE_LIBREADLINE)
+			target_link_libraries(${PROGRAM} readline)
+		endif()
+		install(TARGETS	${PROGRAM} EXPORT LibXml2 RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT programs)
+	endforeach()
+endif()
+
+if(LIBXML2_WITH_TESTS)
+	enable_testing()
+	set(
+		TESTS
+		runxmlconf
+		runsuite
+		testapi
+		testAutomata
+		testC14N
+		testchar
+		testdict
+		testHTML
+		testModule
+		testlimits
+		testReader
+		testrecurse
+		testRegexp
+		testRelax
+		testSAX
+		testSchemas
+		testURI
+		testXPath
+	)
+	foreach(TEST ${TESTS})
+		add_executable(${TEST} ${TEST}.c)
+		target_link_libraries(${TEST} LibXml2)
+	endforeach()
+	if(EXISTS ${LIBXML2_XMLCONF_WORKING_DIR}/xmlconf/xmlconf.xml)
+		add_test(NAME runxmlconf COMMAND runxmlconf WORKING_DIRECTORY ${LIBXML2_XMLCONF_WORKING_DIR})
+	endif()
+	if(NOT WIN32)
+		add_test(NAME testapi COMMAND testapi)
+	endif()
+	add_test(NAME testchar COMMAND testchar)
+	add_test(NAME testdict COMMAND testdict)
+	add_test(NAME testrecurse COMMAND testrecurse WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
+	if(Threads_FOUND)
+		set(
+			TESTS_THREADS
+			runtest
+			testThreads
+		)
+		foreach(TEST ${TESTS_THREADS})
+			add_executable(${TEST} ${TEST}.c)
+			if(WIN32)
+				target_compile_definitions(${TEST} PRIVATE HAVE_WIN32_THREADS)
+			endif()
+			target_link_libraries(${TEST} LibXml2 Threads::Threads)
+		endforeach()
+		add_test(NAME runtest COMMAND runtest --out ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
+		add_test(NAME testThreads COMMAND testThreads WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
+	endif()
+endif()
+
+if(LIBXML2_WITH_PYTHON)
+	execute_process(
+		COMMAND
+		${Python_EXECUTABLE}
+		${CMAKE_CURRENT_SOURCE_DIR}/python/generator.py
+		${CMAKE_CURRENT_SOURCE_DIR}/doc/libxml2-api.xml
+		${CMAKE_CURRENT_SOURCE_DIR}/python/libxml2-python-api.xml
+		WORKING_DIRECTORY
+		${CMAKE_CURRENT_BINARY_DIR}
+	)
+	file(READ python/libxml.py LIBXML_PY)
+	file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/libxml2.py.in "${LIBXML_PY}")
+	file(READ ${CMAKE_CURRENT_BINARY_DIR}/libxml2class.py LIBXML2CLASS_PY)
+	file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/libxml2.py.in "${LIBXML2CLASS_PY}")
+	configure_file(${CMAKE_CURRENT_BINARY_DIR}/libxml2.py.in libxml2.py COPYONLY)
+	add_library(
+		LibXml2Mod
+		libxml2-py.c
+		libxml2-py.h
+		python/libxml.c
+		python/libxml_wrap.h
+		python/types.c
+	)
+	target_include_directories(
+		LibXml2Mod
+		PUBLIC
+		$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/python>
+	)
+	target_link_libraries(LibXml2Mod LibXml2 Python::Python)
+	set_target_properties(
+		LibXml2Mod
+		PROPERTIES
+		IMPORT_PREFIX lib
+		OUTPUT_NAME xml2mod
+		PREFIX lib
+		VERSION ${VERSION}
+	)
+	install(
+		TARGETS	LibXml2Mod
+		ARCHIVE DESTINATION ${LIBXML2_PYTHON_INSTALL_DIR} COMPONENT development
+		LIBRARY DESTINATION ${LIBXML2_PYTHON_INSTALL_DIR} COMPONENT runtime NAMELINK_COMPONENT development
+		RUNTIME DESTINATION ${LIBXML2_PYTHON_INSTALL_DIR} COMPONENT runtime
+	)
+	if(MSVC AND BUILD_SHARED_LIBS)
+		install(FILES $<TARGET_PDB_FILE:LibXml2Mod> DESTINATION ${LIBXML2_PYTHON_INSTALL_DIR} CONFIGURATIONS Debug RelWithDebInfo COMPONENT debug)
+	endif()
+	install(FILES python/drv_libxml2.py DESTINATION ${LIBXML2_PYTHON_INSTALL_DIR} COMPONENT runtime)
+	install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libxml2.py DESTINATION ${LIBXML2_PYTHON_INSTALL_DIR} COMPONENT runtime)
+endif()
+
+install(FILES libxml.3 DESTINATION ${CMAKE_INSTALL_MANDIR}/man3 COMPONENT documentation)
+install(FILES doc/xmlcatalog.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 COMPONENT documentation)
+install(FILES doc/xmllint.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 COMPONENT documentation)
+install(DIRECTORY doc/ DESTINATION ${CMAKE_INSTALL_DATADIR}/doc/libxml2 COMPONENT documentation PATTERN Makefile.* EXCLUDE)
+
+configure_package_config_file(
+	libxml2-config.cmake.cmake.in libxml2-config.cmake
+	INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/libxml2-${VERSION}
+)
+
+install(
+	FILES ${CMAKE_CURRENT_BINARY_DIR}/libxml2-config.cmake
+	DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/libxml2-${VERSION}
+	COMPONENT development
+)
+
+write_basic_package_version_file(
+	${CMAKE_CURRENT_BINARY_DIR}/libxml2-config-version.cmake
+	VERSION ${VERSION}
+	COMPATIBILITY ExactVersion
+)
+
+install(
+	FILES ${CMAKE_CURRENT_BINARY_DIR}/libxml2-config-version.cmake
+	DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/libxml2-${VERSION}
+	COMPONENT development
+)
+
+install(
+	EXPORT LibXml2
+	DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/libxml2-${VERSION}
+	NAMESPACE LibXml2::
+	FILE libxml2-export.cmake
+	COMPONENT development
+)
+
+configure_file(include/libxml/xmlversion.h.in libxml/xmlversion.h)
+install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libxml/xmlversion.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libxml2/libxml COMPONENT development)
+
+if(MSVC)
+	configure_file(include/libxml/xmlwin32version.h.in libxml/xmlwin32version.h)
+	install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libxml/xmlwin32version.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libxml2/libxml COMPONENT development)
+endif()
+
+if(LIBXML2_WITH_PYTHON)
+	set(prefix "${CMAKE_INSTALL_PREFIX}")
+	configure_file(python/setup.py.in setup.py @ONLY)
+endif()
+
+set(XML_INCLUDEDIR "-I\${includedir}/libxml2")
+set(XML_LIBDIR "-L\${libdir}")
+set(XML_LIBS "-lxml2")
+set(XML_PRIVATE_LIBS "${Z_LIBS} ${LZMA_LIBS} ${THREAD_LIBS} ${ICONV_LIBS} ${ICU_LIBS} ${M_LIBS}")
+
+file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${CMAKE_INSTALL_FULL_LIBDIR}/pkgconfig" "${CMAKE_INSTALL_PREFIX}")
+string(REGEX REPLACE "/$" "" PACKAGE_RELATIVE_PATH "${PACKAGE_RELATIVE_PATH}")
+
+set(prefix "\${pcfiledir}/${PACKAGE_RELATIVE_PATH}")
+set(exec_prefix "\${prefix}")
+set(libdir "\${prefix}/${CMAKE_INSTALL_LIBDIR}")
+set(includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}")
+configure_file(libxml-2.0.pc.in libxml-2.0.pc @ONLY)
+install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libxml-2.0.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig COMPONENT development)
+
+set(prefix "\$(cd \"\$(dirname \"\$0\")\"; pwd -P)/..")
+configure_file(xml2-config.in xml2-config @ONLY)
+install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/xml2-config DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT development)
+
+set(XML_INCLUDEDIR "-I${CMAKE_INSTALL_FULL_INCLUDEDIR}/libxml2")
+set(XML_LIBDIR "-L${CMAKE_INSTALL_FULL_LIBDIR}")
+configure_file(xml2Conf.sh.in xml2Conf.sh @ONLY)
+install(FILES ${CMAKE_CURRENT_BINARY_DIR}/xml2Conf.sh DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT development)
+
+set(CPACK_COMPONENT_DEVELOPMENT_DEPENDS runtime)
+set(CPACK_COMPONENT_PROGRAMS_DEPENDS runtime)
+set(CPACK_DEB_COMPONENT_INSTALL ON)
+set(CPACK_DEBIAN_DEVELOPMENT_PACKAGE_DEPENDS "${PACKAGE_TARNAME}")
+set(CPACK_DEBIAN_DEVELOPMENT_PACKAGE_NAME "${PACKAGE_TARNAME}-dev")
+set(CPACK_DEBIAN_DEVELOPMENT_PACKAGE_SECTION "libdevel")
+set(CPACK_DEBIAN_PACKAGE_HOMEPAGE ${PACKAGE_URL})
+set(CPACK_DEBIAN_PACKAGE_NAME ${PACKAGE_TARNAME})
+set(CPACK_DEBIAN_PACKAGE_SECTION "devel")
+set(CPACK_DEBIAN_PROGRAMS_PACKAGE_DEPENDS "${PACKAGE_TARNAME}")
+set(CPACK_DEBIAN_PROGRAMS_PACKAGE_NAME "${PACKAGE_TARNAME}-utils")
+set(CPACK_DEBIAN_PROGRAMS_PACKAGE_SECTION "utils")
+set(CPACK_DEBIAN_RUNTIME_PACKAGE_NAME ${PACKAGE_TARNAME})
+set(CPACK_DEBIAN_RUNTIME_PACKAGE_RECOMMENDS "${PACKAGE_TARNAME}-utils")
+set(CPACK_DEBIAN_RUNTIME_PACKAGE_SECTION "libs")
+set(CPACK_NSIS_PACKAGE_NAME ${PACKAGE_STRING})
+set(CPACK_NSIS_URL_INFO_ABOUT ${PACKAGE_URL})
+set(CPACK_PACKAGE_CONTACT ${PACKAGE_BUGREPORT})
+set(CPACK_PACKAGE_DISPLAY_NAME ${PACKAGE_STRING})
+set(CPACK_PACKAGE_INSTALL_DIRECTORY "${PACKAGE_TARNAME}-${PACKAGE_VERSION}")
+set(CPACK_PACKAGE_NAME ${PACKAGE_TARNAME})
+set(CPACK_PACKAGE_VERSION ${PACKAGE_VERSION})
+set(CPACK_PACKAGE_VERSION_MAJOR ${LIBXML_MAJOR_VERSION})
+set(CPACK_PACKAGE_VERSION_MINOR ${LIBXML_MINOR_VERSION})
+set(CPACK_PACKAGE_VERSION_PATCH ${LIBXML_MICRO_VERSION})
+set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_CURRENT_SOURCE_DIR}/Copyright)
+set(CPACK_RPM_COMPONENT_INSTALL ON)
+set(CPACK_RPM_development_PACKAGE_NAME "${PACKAGE_NAME}-devel")
+set(CPACK_RPM_development_PACKAGE_REQUIRES "${PACKAGE_NAME}")
+set(CPACK_RPM_PACKAGE_GROUP "Development/Libraries")
+set(CPACK_RPM_PACKAGE_NAME ${PACKAGE_TARNAME})
+set(CPACK_RPM_PACKAGE_URL ${PACKAGE_URL})
+set(CPACK_RPM_programs_PACKAGE_NAME "${PACKAGE_NAME}-utils")
+set(CPACK_RPM_programs_PACKAGE_REQUIRES "${PACKAGE_NAME}")
+set(CPACK_RPM_runtime_PACKAGE_NAME "${PACKAGE_NAME}")
+set(CPACK_RPM_runtime_PACKAGE_SUGGESTS "${PACKAGE_NAME}-utils")
+
+include(CPack)
diff --git a/src/HTMLparser.c b/src/HTMLparser.c
index de624f8..2877f4b 100644
--- a/src/HTMLparser.c
+++ b/src/HTMLparser.c
@@ -3297,6 +3297,7 @@
     int q, ql;
     int r, rl;
     int cur, l;
+    int next, nl;
     xmlParserInputState state;
 
     /*
@@ -3329,6 +3330,21 @@
     while ((cur != 0) &&
            ((cur != '>') ||
 	    (r != '-') || (q != '-'))) {
+	NEXTL(l);
+	next = CUR_CHAR(nl);
+	if (next == 0) {
+	    SHRINK;
+	    GROW;
+	    next = CUR_CHAR(nl);
+	}
+
+	if ((q == '-') && (r == '-') && (cur == '!') && (next == '>')) {
+	  htmlParseErr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
+		       "Comment incorrectly closed by '--!>'", NULL, NULL);
+	  cur = '>';
+	  break;
+	}
+
 	if (len + 5 >= size) {
 	    xmlChar *tmp;
 
@@ -3348,17 +3364,13 @@
             htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
                             "Invalid char in comment 0x%X\n", q);
         }
+
 	q = r;
 	ql = rl;
 	r = cur;
 	rl = l;
-	NEXTL(l);
-	cur = CUR_CHAR(l);
-	if (cur == 0) {
-	    SHRINK;
-	    GROW;
-	    cur = CUR_CHAR(l);
-	}
+	cur = next;
+	l = nl;
     }
     buf[len] = 0;
     if (cur == '>') {
@@ -5209,6 +5221,39 @@
 }
 
 /**
+ * htmlParseLookupCommentEnd:
+ * @ctxt: an HTML parser context
+ *
+ * Try to find a comment end tag in the input stream
+ * The search includes "-->" as well as WHATWG-recommended incorrectly-closed tags.
+ * (See https://html.spec.whatwg.org/multipage/parsing.html#parse-error-incorrectly-closed-comment)
+ * This function has a side effect of (possibly) incrementing ctxt->checkIndex
+ * to avoid rescanning sequences of bytes, it DOES change the state of the
+ * parser, do not use liberally.
+ * This wraps to htmlParseLookupSequence()
+ *
+ * Returns the index to the current parsing point if the full sequence is available, -1 otherwise.
+ */
+static int
+htmlParseLookupCommentEnd(htmlParserCtxtPtr ctxt)
+{
+    int mark = 0;
+    int cur = CUR_PTR - BASE_PTR;
+
+    while (mark >= 0) {
+	mark = htmlParseLookupSequence(ctxt, '-', '-', 0, 0);
+	if ((mark < 0) ||
+	    (NXT(mark+2) == '>') ||
+	    ((NXT(mark+2) == '!') && (NXT(mark+3) == '>'))) {
+	    return mark;
+	}
+	ctxt->checkIndex = cur + mark + 1;
+    }
+    return mark;
+}
+
+
+/**
  * htmlParseTryOrFinish:
  * @ctxt:  an HTML parser context
  * @terminate:  last chunk indicator
@@ -5393,8 +5438,7 @@
 		cur = in->cur[0];
 	        if ((cur == '<') && (next == '!') &&
 		    (in->cur[2] == '-') && (in->cur[3] == '-')) {
-		    if ((!terminate) &&
-		        (htmlParseLookupSequence(ctxt, '-', '-', '>', 0) < 0))
+		    if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
 			goto done;
 #ifdef DEBUG_PUSH
 		    xmlGenericError(xmlGenericErrorContext,
@@ -5454,8 +5498,7 @@
 		next = in->cur[1];
 		if ((cur == '<') && (next == '!') &&
 		    (in->cur[2] == '-') && (in->cur[3] == '-')) {
-		    if ((!terminate) &&
-		        (htmlParseLookupSequence(ctxt, '-', '-', '>', 0) < 0))
+		    if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
 			goto done;
 #ifdef DEBUG_PUSH
 		    xmlGenericError(xmlGenericErrorContext,
@@ -5502,8 +5545,7 @@
 		next = in->cur[1];
 	        if ((cur == '<') && (next == '!') &&
 		    (in->cur[2] == '-') && (in->cur[3] == '-')) {
-		    if ((!terminate) &&
-		        (htmlParseLookupSequence(ctxt, '-', '-', '>', 0) < 0))
+		    if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
 			goto done;
 #ifdef DEBUG_PUSH
 		    xmlGenericError(xmlGenericErrorContext,
@@ -5757,9 +5799,7 @@
 			htmlParseDocTypeDecl(ctxt);
 		    } else if ((cur == '<') && (next == '!') &&
 			(in->cur[2] == '-') && (in->cur[3] == '-')) {
-			if ((!terminate) &&
-			    (htmlParseLookupSequence(
-				ctxt, '-', '-', '>', 0) < 0))
+			if ((!terminate) && (htmlParseLookupCommentEnd(ctxt) < 0))
 			    goto done;
 #ifdef DEBUG_PUSH
 			xmlGenericError(xmlGenericErrorContext,
@@ -5832,7 +5872,7 @@
 			xmlGenericError(xmlGenericErrorContext,
 				"HPP: Parsing char data\n");
 #endif
-                        while ((cur != '<') && (cur != 0)) {
+                        while ((cur != '<') && (in->cur < in->end)) {
                             if (cur == '&') {
 			        htmlParseReference(ctxt);
                             } else {
diff --git a/src/Makefile.am b/src/Makefile.am
index 4ef0eb9..a9284b9 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -4,7 +4,7 @@
 
 SUBDIRS = include . doc example fuzz xstc $(PYTHON_SUBDIR)
 
-DIST_SUBDIRS = include . doc example python xstc fuzz
+DIST_SUBDIRS = include . doc example fuzz python xstc
 
 AM_CPPFLAGS = -I$(top_builddir)/include -I$(srcdir)/include
 
@@ -1260,6 +1260,7 @@
 	     dbgen.pl dbgenattr.pl regressions.py regressions.xml \
 	     README.tests Makefile.tests libxml2.syms timsort.h \
 	     README.zOS \
+	     CMakeLists.txt config.h.cmake.in libxml2-config.cmake.cmake.in \
 	     $(CVS_EXTRA_DIST)
 
 
diff --git a/src/config.h.cmake.in b/src/config.h.cmake.in
new file mode 100644
index 0000000..22b3c92
--- /dev/null
+++ b/src/config.h.cmake.in
@@ -0,0 +1,288 @@
+/* config.h.  Generated from config.h.in by configure.  */
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define if __attribute__((destructor)) is accepted */
+#cmakedefine ATTRIBUTE_DESTRUCTOR 1
+
+/* Type cast for the gethostbyname() argument */
+#cmakedefine GETHOSTBYNAME_ARG_CAST @GETHOSTBYNAME_ARG_CAST@
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#cmakedefine HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the <arpa/nameser.h> header file. */
+#cmakedefine HAVE_ARPA_NAMESER_H 1
+
+/* Whether struct sockaddr::__ss_family exists */
+#cmakedefine HAVE_BROKEN_SS_FAMILY 1
+
+/* Define to 1 if you have the <ctype.h> header file. */
+#cmakedefine HAVE_CTYPE_H 1
+
+/* Define to 1 if you have the <dirent.h> header file. */
+#cmakedefine HAVE_DIRENT_H 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#cmakedefine HAVE_DLFCN_H 1
+
+/* Have dlopen based dso */
+#cmakedefine HAVE_DLOPEN 1
+
+/* Define to 1 if you have the <dl.h> header file. */
+#cmakedefine HAVE_DL_H 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#cmakedefine HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#cmakedefine HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the <float.h> header file. */
+#cmakedefine HAVE_FLOAT_H 1
+
+/* Define to 1 if you have the `fprintf' function. */
+#cmakedefine HAVE_FPRINTF 1
+
+/* Define to 1 if you have the `ftime' function. */
+#cmakedefine HAVE_FTIME 1
+
+/* Define if getaddrinfo is there */
+#cmakedefine HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#cmakedefine HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#cmakedefine HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `isascii' function. */
+#cmakedefine HAVE_ISASCII 1
+
+/* Define if isinf is there */
+#cmakedefine HAVE_ISINF 1
+
+/* Define if isnan is there */
+#cmakedefine HAVE_ISNAN 1
+
+/* Define if history library is there (-lhistory) */
+#cmakedefine HAVE_LIBHISTORY 1
+
+/* Define if pthread library is there (-lpthread) */
+#cmakedefine HAVE_LIBPTHREAD 1
+
+/* Define if readline library is there (-lreadline) */
+#cmakedefine HAVE_LIBREADLINE 1
+
+/* Define to 1 if you have the <limits.h> header file. */
+#cmakedefine HAVE_LIMITS_H 1
+
+/* Define to 1 if you have the `localtime' function. */
+#cmakedefine HAVE_LOCALTIME 1
+
+/* Define to 1 if you have the <lzma.h> header file. */
+#cmakedefine HAVE_LZMA_H 1
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#cmakedefine HAVE_MALLOC_H 1
+
+/* Define to 1 if you have the <math.h> header file. */
+#cmakedefine HAVE_MATH_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#cmakedefine HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#cmakedefine HAVE_MMAP 1
+
+/* Define to 1 if you have the `munmap' function. */
+#cmakedefine HAVE_MUNMAP 1
+
+/* mmap() is no good without munmap() */
+#if defined(HAVE_MMAP) && !defined(HAVE_MUNMAP)
+#  undef /**/ HAVE_MMAP
+#endif
+
+/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
+#cmakedefine HAVE_NDIR_H 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#cmakedefine HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#cmakedefine HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#cmakedefine HAVE_POLL_H 1
+
+/* Define to 1 if you have the `printf' function. */
+#cmakedefine HAVE_PRINTF 1
+
+/* Define if <pthread.h> is there */
+#cmakedefine HAVE_PTHREAD_H 1
+
+/* Define to 1 if you have the `putenv' function. */
+#cmakedefine HAVE_PUTENV 1
+
+/* Define to 1 if you have the `rand' function. */
+#cmakedefine HAVE_RAND 1
+
+/* Define to 1 if you have the `rand_r' function. */
+#cmakedefine HAVE_RAND_R 1
+
+/* Define to 1 if you have the <resolv.h> header file. */
+#cmakedefine HAVE_RESOLV_H 1
+
+/* Have shl_load based dso */
+#cmakedefine HAVE_SHLLOAD 1
+
+/* Define to 1 if you have the `signal' function. */
+#cmakedefine HAVE_SIGNAL 1
+
+/* Define to 1 if you have the <signal.h> header file. */
+#cmakedefine HAVE_SIGNAL_H 1
+
+/* Define to 1 if you have the `snprintf' function. */
+#cmakedefine HAVE_SNPRINTF 1
+
+/* Define to 1 if you have the `sprintf' function. */
+#cmakedefine HAVE_SPRINTF 1
+
+/* Define to 1 if you have the `srand' function. */
+#cmakedefine HAVE_SRAND 1
+
+/* Define to 1 if you have the `sscanf' function. */
+#cmakedefine HAVE_SSCANF 1
+
+/* Define to 1 if you have the `stat' function. */
+#cmakedefine HAVE_STAT 1
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#cmakedefine HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#cmakedefine HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#cmakedefine HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the `strftime' function. */
+#cmakedefine HAVE_STRFTIME 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#cmakedefine HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#cmakedefine HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
+   */
+#cmakedefine HAVE_SYS_DIR_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#cmakedefine HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
+   */
+#cmakedefine HAVE_SYS_NDIR_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#cmakedefine HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#cmakedefine HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#cmakedefine HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/timeb.h> header file. */
+#cmakedefine HAVE_SYS_TIMEB_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#cmakedefine HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#cmakedefine HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the `time' function. */
+#cmakedefine HAVE_TIME 1
+
+/* Define to 1 if you have the <time.h> header file. */
+#cmakedefine HAVE_TIME_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#cmakedefine HAVE_UNISTD_H 1
+
+/* Whether va_copy() is available */
+#cmakedefine HAVE_VA_COPY 1
+
+/* Define to 1 if you have the `vfprintf' function. */
+#cmakedefine HAVE_VFPRINTF 1
+
+/* Define to 1 if you have the `vsnprintf' function. */
+#cmakedefine HAVE_VSNPRINTF 1
+
+/* Define to 1 if you have the `vsprintf' function. */
+#cmakedefine HAVE_VSPRINTF 1
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#cmakedefine HAVE_ZLIB_H 1
+
+/* Whether __va_copy() is available */
+#cmakedefine HAVE___VA_COPY 1
+
+/* Define as const if the declaration of iconv() needs const. */
+#define ICONV_CONST @ICONV_CONST@
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#cmakedefine LT_OBJDIR "@LT_OBJDIR@"
+
+/* Name of package */
+#define PACKAGE "@PACKAGE@"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "@PACKAGE_BUGREPORT@"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "@PACKAGE_NAME@"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "@PACKAGE_STRING@"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "@PACKAGE_TARNAME@"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL "@PACKAGE_URL@"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "@PACKAGE_VERSION@"
+
+/* Type cast for the send() function 2nd arg */
+#cmakedefine SEND_ARG2_CAST @SEND_ARG2_CAST@
+
+/* Define to 1 if you have the ANSI C header files. */
+#cmakedefine STDC_HEADERS 1
+
+/* Support for IPv6 */
+#cmakedefine SUPPORT_IP6 1
+
+/* Define if va_list is an array type */
+#cmakedefine VA_LIST_IS_ARRAY 1
+
+/* Version number of package */
+#cmakedefine VERSION "@VERSION@"
+
+/* Determine what socket length (socklen_t) data type is */
+#cmakedefine XML_SOCKLEN_T @XML_SOCKLEN_T@
+
+/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
+   <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
+   #define below would cause a syntax error. */
+#cmakedefine _UINT32_T @_UINT32_T@
+
+/* ss_family is not defined here, use __ss_family instead */
+#cmakedefine ss_family @ss_family@
+
+/* Define to the type of an unsigned integer type of width exactly 32 bits if
+   such a type exists and the standard includes do not define it. */
+#cmakedefine uint32_t @uint32_t@
diff --git a/src/encoding.c b/src/encoding.c
index 47be560..d67c16d 100644
--- a/src/encoding.c
+++ b/src/encoding.c
@@ -1488,16 +1488,25 @@
     if ((handler == NULL) || (handlers == NULL)) {
         xmlEncodingErr(XML_I18N_NO_HANDLER,
 		"xmlRegisterCharEncodingHandler: NULL handler !\n", NULL);
-	return;
+        goto free_handler;
     }
 
     if (nbCharEncodingHandler >= MAX_ENCODING_HANDLERS) {
         xmlEncodingErr(XML_I18N_EXCESS_HANDLER,
 	"xmlRegisterCharEncodingHandler: Too many handler registered, see %s\n",
 	               "MAX_ENCODING_HANDLERS");
-	return;
+        goto free_handler;
     }
     handlers[nbCharEncodingHandler++] = handler;
+    return;
+
+free_handler:
+    if (handler != NULL) {
+        if (handler->name != NULL) {
+            xmlFree(handler->name);
+        }
+        xmlFree(handler);
+    }
 }
 
 /**
@@ -1858,7 +1867,7 @@
  * @outlen:  the length of @out
  * @in:  a pointer to an array of input bytes
  * @inlen:  the length of @in
- * @flush: if 1, indicates end of input
+ * @flush: if true, indicates end of input
  *
  * Returns 0 if success, or
  *     -1 by lack of space, or
@@ -1898,7 +1907,7 @@
     *inlen = ucv_in - (const char*) in;
     *outlen = ucv_out - (char *) out;
     if (U_SUCCESS(err)) {
-        /* reset pivot buf if this is the last call for input (flush==1) */
+        /* reset pivot buf if this is the last call for input (flush==TRUE) */
         if (flush)
             cd->pivot_source = cd->pivot_target = cd->pivot_buf;
         return 0;
diff --git a/src/fuzz/Makefile.am b/src/fuzz/Makefile.am
index 49b9554..2bbdbb1 100644
--- a/src/fuzz/Makefile.am
+++ b/src/fuzz/Makefile.am
@@ -1,6 +1,8 @@
 AUTOMAKE_OPTIONS = -Wno-syntax
 EXTRA_PROGRAMS = genSeed html regexp schema uri xml xpath
 check_PROGRAMS = testFuzzer
+EXTRA_DIST = html.dict regexp.dict schema.dict xml.dict xpath.dict \
+	     seed/uri
 CLEANFILES = $(EXTRA_PROGRAMS)
 AM_CPPFLAGS = -I$(top_srcdir)/include
 DEPENDENCIES = $(top_builddir)/libxml2.la
diff --git a/src/fuzz/Makefile.in b/src/fuzz/Makefile.in
index 4dd6eba..a688e96 100644
--- a/src/fuzz/Makefile.in
+++ b/src/fuzz/Makefile.in
@@ -489,6 +489,9 @@
 top_builddir = @top_builddir@
 top_srcdir = @top_srcdir@
 AUTOMAKE_OPTIONS = -Wno-syntax
+EXTRA_DIST = html.dict regexp.dict schema.dict xml.dict xpath.dict \
+	     seed/uri
+
 CLEANFILES = $(EXTRA_PROGRAMS)
 AM_CPPFLAGS = -I$(top_srcdir)/include
 DEPENDENCIES = $(top_builddir)/libxml2.la
diff --git a/src/fuzz/fuzz.c b/src/fuzz/fuzz.c
index b5dfa18..212136a 100644
--- a/src/fuzz/fuzz.c
+++ b/src/fuzz/fuzz.c
@@ -211,6 +211,8 @@
 
         if (xmlHashLookup(fuzzData.entities, (xmlChar *)url) == NULL) {
             entityInfo = xmlMalloc(sizeof(xmlFuzzEntityInfo));
+            if (entityInfo == NULL)
+                break;
             entityInfo->data = entity;
             entityInfo->size = entitySize;
 
@@ -271,6 +273,10 @@
     input->filename = NULL;
     input->buf = xmlParserInputBufferCreateMem(entity->data, entity->size,
                                                XML_CHAR_ENCODING_NONE);
+    if (input->buf == NULL) {
+        xmlFreeInputStream(input);
+        return(NULL);
+    }
     input->base = input->cur = xmlBufContent(input->buf->buffer);
     input->end = input->base + entity->size;
 
diff --git a/src/fuzz/html.dict b/src/fuzz/html.dict
new file mode 100644
index 0000000..801b7bb
--- /dev/null
+++ b/src/fuzz/html.dict
@@ -0,0 +1,111 @@
+elem_a="<a></a>"
+elem_abbr="<abbr></abbr>"
+elem_acronym="<acronym></acronym>"
+elem_address="<address></address>"
+elem_applet="<applet></applet>"
+elem_area="<area>"
+elem_b="<b></b>"
+elem_base="<base>"
+elem_basefont="<basefont>"
+elem_bdo="<bdo></bdo>"
+elem_big="<big></big>"
+elem_blockquote="<blockquote></blockquote>"
+elem_body="<body></body>"
+elem_br="<br>"
+elem_button="<button></button>"
+elem_caption="<caption></caption>"
+elem_center="<center></center>"
+elem_cite="<cite></cite>"
+elem_code="<code></code>"
+elem_col="<col>"
+elem_colgroup="<colgroup></colgroup>"
+elem_dd="<dd></dd>"
+elem_del="<del></del>"
+elem_dfn="<dfn></dfn>"
+elem_dir="<dir></dir>"
+elem_div="<div></div>"
+elem_dl="<dl></dl>"
+elem_dt="<dt></dt>"
+elem_em="<em></em>"
+elem_embed="<embed></embed>"
+elem_fieldset="<fieldset></fieldset>"
+elem_font="<font></font>"
+elem_form="<form></form>"
+elem_frame="<frame>"
+elem_frameset="<frameset></frameset>"
+elem_h1="<h1></h1>"
+elem_h2="<h2></h2>"
+elem_h3="<h3></h3>"
+elem_h4="<h4></h4>"
+elem_h5="<h5></h5>"
+elem_h6="<h6></h6>"
+elem_head="<head></head>"
+elem_hr="<hr>"
+elem_html="<html></html>"
+elem_i="<i></i>"
+elem_iframe="<iframe></iframe>"
+elem_img="<img>"
+elem_input="<input>"
+elem_ins="<ins></ins>"
+elem_isindex="<isindex>"
+elem_kbd="<kbd></kbd>"
+elem_label="<label></label>"
+elem_legend="<legend></legend>"
+elem_li="<li></li>"
+elem_link="<link>"
+elem_map="<map></map>"
+elem_menu="<menu></menu>"
+elem_meta="<meta>"
+elem_noframes="<noframes></noframes>"
+elem_noscript="<noscript></noscript>"
+elem_object="<object></object>"
+elem_ol="<ol></ol>"
+elem_optgroup="<optgroup></optgroup>"
+elem_option="<option></option>"
+elem_p="<p></p>"
+elem_param="<param>"
+elem_pre="<pre></pre>"
+elem_q="<q></q>"
+elem_s="<s></s>"
+elem_samp="<samp></samp>"
+elem_script="<script></script>"
+elem_select="<select></select>"
+elem_small="<small></small>"
+elem_span="<span></span>"
+elem_strike="<strike></strike>"
+elem_strong="<strong></strong>"
+elem_style="<style></style>"
+elem_sub="<sub></sub>"
+elem_sup="<sup></sup>"
+elem_table="<table></table>"
+elem_tbody="<tbody></tbody>"
+elem_td="<td></td>"
+elem_textarea="<textarea></textarea>"
+elem_tfoot="<tfoot></tfoot>"
+elem_th="<th></th>"
+elem_thead="<thead></thead>"
+elem_title="<title></title>"
+elem_tr="<tr></tr>"
+elem_tt="<tt></tt>"
+elem_u="<u></u>"
+elem_ul="<ul></ul>"
+elem_var="<var></var>"
+
+attr_id=" id=\"\""
+attr_style=" style=\"\""
+
+comment="<!-- -->"
+
+doctype="<!DOCTYPE d>"
+doctype_system="<!DOCTYPE s SYSTEM \"u\">"
+doctype_public="<!DOCTYPE p PUBLIC \"i\" \"u\">"
+
+pi="<?a?>"
+
+ref_lt="&lt;"
+ref_gt="&gt;"
+ref_amp="&amp;"
+ref_apos="&apos;"
+ref_quot="&quot;"
+ref_dec="&#9;"
+ref_hex="&#xA;"
diff --git a/src/fuzz/regexp.c b/src/fuzz/regexp.c
index 3b35671..cfffedd 100644
--- a/src/fuzz/regexp.c
+++ b/src/fuzz/regexp.c
@@ -21,6 +21,9 @@
     char *str[2] = { NULL, NULL };
     size_t numStrings;
 
+    if (size > 200)
+        return(0);
+
     numStrings = xmlFuzzExtractStrings(data, size, str, 2);
 
     /* CUR_SCHAR doesn't handle invalid UTF-8 and may cause infinite loops. */
diff --git a/src/fuzz/regexp.dict b/src/fuzz/regexp.dict
new file mode 100644
index 0000000..30d666d
--- /dev/null
+++ b/src/fuzz/regexp.dict
@@ -0,0 +1,155 @@
+quant_any="*"
+quant_opt="?"
+quant_some="+"
+quant_num="{1,2}"
+
+dot="."
+branch="|a"
+parens="()"
+parens_inner=")("
+pos_group="[a]"
+neg_group="[^a]"
+class_subtraction="[a-[b]]"
+
+esc_space="\\s"
+esc_initial="\\i"
+esc_name="\\c"
+esc_digit="\\d"
+esc_word="\\w"
+
+cat_letter="\\p{L}"
+cat_mark="\\p{M}"
+cat_number="\\p{N}"
+cat_punct="\\p{P}"
+cat_sym="\\p{S}"
+cat_sep="\\p{Z}"
+cat_other="\\p{C}"
+
+block_aegean_numbers="\\p{IsAegeanNumbers}"
+block_alphabetic_presentation_forms="\\p{IsAlphabeticPresentationForms}"
+block_arabic="\\p{IsArabic}"
+block_arabic_presentation_forms_a="\\p{IsArabicPresentationFormsA}"
+block_arabic_presentation_forms_b="\\p{IsArabicPresentationFormsB}"
+block_armenian="\\p{IsArmenian}"
+block_arrows="\\p{IsArrows}"
+block_basic_latin="\\p{IsBasicLatin}"
+block_bengali="\\p{IsBengali}"
+block_block_elements="\\p{IsBlockElements}"
+block_bopomofo="\\p{IsBopomofo}"
+block_bopomofo_extended="\\p{IsBopomofoExtended}"
+block_box_drawing="\\p{IsBoxDrawing}"
+block_braille_patterns="\\p{IsBraillePatterns}"
+block_buhid="\\p{IsBuhid}"
+block_byzantine_musical_symbols="\\p{IsByzantineMusicalSymbols}"
+block_c_j_k_compatibility="\\p{IsCJKCompatibility}"
+block_c_j_k_compatibility_forms="\\p{IsCJKCompatibilityForms}"
+block_c_j_k_compatibility_ideographs="\\p{IsCJKCompatibilityIdeographs}"
+block_c_j_k_compatibility_ideographs_supplement="\\p{IsCJKCompatibilityIdeographsSupplement}"
+block_c_j_k_radicals_supplement="\\p{IsCJKRadicalsSupplement}"
+block_c_j_k_symbolsand_punctuation="\\p{IsCJKSymbolsandPunctuation}"
+block_c_j_k_unified_ideographs="\\p{IsCJKUnifiedIdeographs}"
+block_c_j_k_unified_ideographs_extension_a="\\p{IsCJKUnifiedIdeographsExtensionA}"
+block_cjk_unified_ideographs_extension_b="\\p{IsCJKUnifiedIdeographsExtensionB}"
+block_cherokee="\\p{IsCherokee}"
+block_combining_diacritical_marks="\\p{IsCombiningDiacriticalMarks}"
+block_combining_diacritical_marksfor_symbols="\\p{IsCombiningDiacriticalMarksforSymbols}"
+block_combining_half_marks="\\p{IsCombiningHalfMarks}"
+block_combining_marksfor_symbols="\\p{IsCombiningMarksforSymbols}"
+block_control_pictures="\\p{IsControlPictures}"
+block_currency_symbols="\\p{IsCurrencySymbols}"
+block_cypriot_syllabary="\\p{IsCypriotSyllabary}"
+block_cyrillic="\\p{IsCyrillic}"
+block_cyrillic_supplement="\\p{IsCyrillicSupplement}"
+block_deseret="\\p{IsDeseret}"
+block_devanagari="\\p{IsDevanagari}"
+block_dingbats="\\p{IsDingbats}"
+block_enclosed_alphanumerics="\\p{IsEnclosedAlphanumerics}"
+block_enclosed_cjk_lettersand_months="\\p{IsEnclosedCJKLettersandMonths}"
+block_ethiopic="\\p{IsEthiopic}"
+block_general_punctuation="\\p{IsGeneralPunctuation}"
+block_geometric_shapes="\\p{IsGeometricShapes}"
+block_georgian="\\p{IsGeorgian}"
+block_gothic="\\p{IsGothic}"
+block_greek="\\p{IsGreek}"
+block_greek_extended="\\p{IsGreekExtended}"
+block_greekand_coptic="\\p{IsGreekandCoptic}"
+block_gujarati="\\p{IsGujarati}"
+block_gurmukhi="\\p{IsGurmukhi}"
+block_halfwidthand_fullwidth_forms="\\p{IsHalfwidthandFullwidthForms}"
+block_hangul_compatibility_jamo="\\p{IsHangulCompatibilityJamo}"
+block_hangul_jamo="\\p{IsHangulJamo}"
+block_hangul_syllables="\\p{IsHangulSyllables}"
+block_hanunoo="\\p{IsHanunoo}"
+block_hebrew="\\p{IsHebrew}"
+block_high_private_use_surrogates="\\p{IsHighPrivateUseSurrogates}"
+block_high_surrogates="\\p{IsHighSurrogates}"
+block_hiragana="\\p{IsHiragana}"
+block_ipa_extensions="\\p{IsIPAExtensions}"
+block_ideographic_description_characters="\\p{IsIdeographicDescriptionCharacters}"
+block_kanbun="\\p{IsKanbun}"
+block_kangxi_radicals="\\p{IsKangxiRadicals}"
+block_kannada="\\p{IsKannada}"
+block_katakana="\\p{IsKatakana}"
+block_katakana_phonetic_extensions="\\p{IsKatakanaPhoneticExtensions}"
+block_khmer="\\p{IsKhmer}"
+block_khmer_symbols="\\p{IsKhmerSymbols}"
+block_lao="\\p{IsLao}"
+block_latin1Supplement="\\p{IsLatin1Supplement}"
+block_latin_extended_a="\\p{IsLatinExtendedA}"
+block_latin_extended_b="\\p{IsLatinExtendedB}"
+block_latin_extended_additional="\\p{IsLatinExtendedAdditional}"
+block_letterlike_symbols="\\p{IsLetterlikeSymbols}"
+block_limbu="\\p{IsLimbu}"
+block_linear_b_ideograms="\\p{IsLinearBIdeograms}"
+block_linear_b_syllabary="\\p{IsLinearBSyllabary}"
+block_low_surrogates="\\p{IsLowSurrogates}"
+block_malayalam="\\p{IsMalayalam}"
+block_mathematical_alphanumeric_symbols="\\p{IsMathematicalAlphanumericSymbols}"
+block_mathematical_operators="\\p{IsMathematicalOperators}"
+block_miscellaneous_mathematical_symbols_a="\\p{IsMiscellaneousMathematicalSymbolsA}"
+block_miscellaneous_mathematical_symbols_b="\\p{IsMiscellaneousMathematicalSymbolsB}"
+block_miscellaneous_symbols="\\p{IsMiscellaneousSymbols}"
+block_miscellaneous_symbolsand_arrows="\\p{IsMiscellaneousSymbolsandArrows}"
+block_miscellaneous_technical="\\p{IsMiscellaneousTechnical}"
+block_mongolian="\\p{IsMongolian}"
+block_musical_symbols="\\p{IsMusicalSymbols}"
+block_myanmar="\\p{IsMyanmar}"
+block_number_forms="\\p{IsNumberForms}"
+block_ogham="\\p{IsOgham}"
+block_old_italic="\\p{IsOldItalic}"
+block_optical_character_recognition="\\p{IsOpticalCharacterRecognition}"
+block_oriya="\\p{IsOriya}"
+block_osmanya="\\p{IsOsmanya}"
+block_phonetic_extensions="\\p{IsPhoneticExtensions}"
+block_private_use="\\p{IsPrivateUse}"
+block_private_use_area="\\p{IsPrivateUseArea}"
+block_runic="\\p{IsRunic}"
+block_shavian="\\p{IsShavian}"
+block_sinhala="\\p{IsSinhala}"
+block_small_form_variants="\\p{IsSmallFormVariants}"
+block_spacing_modifier_letters="\\p{IsSpacingModifierLetters}"
+block_specials="\\p{IsSpecials}"
+block_superscriptsand_subscripts="\\p{IsSuperscriptsandSubscripts}"
+block_supplemental_arrows_a="\\p{IsSupplementalArrowsA}"
+block_supplemental_arrows_b="\\p{IsSupplementalArrowsB}"
+block_supplemental_mathematical_operators="\\p{IsSupplementalMathematicalOperators}"
+block_supplementary_private_use_area_a="\\p{IsSupplementaryPrivateUseAreaA}"
+block_supplementary_private_use_area_b="\\p{IsSupplementaryPrivateUseAreaB}"
+block_syriac="\\p{IsSyriac}"
+block_tagalog="\\p{IsTagalog}"
+block_tagbanwa="\\p{IsTagbanwa}"
+block_tags="\\p{IsTags}"
+block_tai_le="\\p{IsTaiLe}"
+block_tai_xuan_jing_symbols="\\p{IsTaiXuanJingSymbols}"
+block_tamil="\\p{IsTamil}"
+block_telugu="\\p{IsTelugu}"
+block_thaana="\\p{IsThaana}"
+block_thai="\\p{IsThai}"
+block_tibetan="\\p{IsTibetan}"
+block_ugaritic="\\p{IsUgaritic}"
+block_unified_canadian_aboriginal_syllabics="\\p{IsUnifiedCanadianAboriginalSyllabics}"
+block_variation_selectors="\\p{IsVariationSelectors}"
+block_variation_selectors_supplement="\\p{IsVariationSelectorsSupplement}"
+block_yi_radicals="\\p{IsYiRadicals}"
+block_yi_syllables="\\p{IsYiSyllables}"
+block_yijing_hexagram_symbols="\\p{IsYijingHexagramSymbols}"
diff --git a/src/fuzz/schema.c b/src/fuzz/schema.c
index f1ee938..7b034ec 100644
--- a/src/fuzz/schema.c
+++ b/src/fuzz/schema.c
@@ -21,6 +21,9 @@
 LLVMFuzzerTestOneInput(const char *data, size_t size) {
     xmlSchemaParserCtxtPtr pctxt;
 
+    if (size > 50000)
+        return(0);
+
     xmlFuzzDataInit(data, size);
     xmlFuzzReadEntities();
 
diff --git a/src/fuzz/schema.dict b/src/fuzz/schema.dict
new file mode 100644
index 0000000..9a8fd38
--- /dev/null
+++ b/src/fuzz/schema.dict
@@ -0,0 +1,55 @@
+# TODO: Add more language elements
+
+xs_annotation="<xs:annotation></xs:annotation>"
+
+xs_attribute="<xs:attribute name='a'></xs:attribute>"
+xs_attribute_required="<xs:attribute name='a' use='required'></xs:attribute>"
+xs_element="<xs:element name='e'></xs:element>"
+
+# Primitive datatypes
+type_string=" type='xs:string'"
+type_boolean=" type='xs:boolean'"
+type_decimal=" type='xs:decimal'"
+type_float=" type='xs:float'"
+type_double=" type='xs:double'"
+type_date_time=" type='xs:dateTime'"
+type_time=" type='xs:time'"
+type_date=" type='xs:date'"
+type_g_year_month=" type='xs:gYearMonth'"
+type_g_year=" type='xs:gYear'"
+type_g_month_day=" type='xs:gMonthDay'"
+type_g_day=" type='xs:gDay'"
+type_g_month=" type='xs:gMonth'"
+type_hex_binary=" type='xs:hexBinary'"
+type_base64_binary=" type='xs:base64Binary'"
+type_any_uri=" type='xs:anyURI'"
+type_qname=" type='xs:QName'"
+type_notation=" type='xs:NOTATION'"
+
+# Occurs
+occurs_min=" minOccurs='1'"
+occurs_max=" maxOccurs='9'"
+occurs_max_unbounded=" maxOccurs='unbounded'"
+
+# Simple type
+xs_restriction_integer="<xs:simpleType><xs:restriction base='xs:integer'></xs:restriction></xs:simpleType>"
+xs_restriction_string="<xs:simpleType><xs:restriction base='xs:string'></xs:restriction></xs:simpleType>"
+xs_list="<xs:simpleType><xs:list></xs:list></xs:simpleType>"
+xs_union="<xs:simpleType><xs:union></xs:union></xs:simpleType>"
+
+# Restrictions
+xs_min_exclusive="<xs:minExclusive value='0'/>"
+xs_min_inclusive="<xs:minInclusive value='0'/>"
+xs_max_exclusive="<xs:maxExclusive value='9'/>"
+xs_max_inclusive="<xs:maxInclusive value='9'/>"
+xs_total_digits="<xs:totalDigits value='3'/>"
+xs_fraction_digits="<xs:fractionDigits value='3'/>"
+xs_length="<xs:length value='3'/>"
+xs_min_length="<xs:minLength value='3'/>"
+xs_max_length="<xs:maxLength value='3'/>"
+xs_enumeration="<xs:enumeration value='a'/>"
+xs_white_space_collapse="<xs:whiteSpace value='collapse'/>"
+xs_white_space_preserve="<xs:whiteSpace value='preserve'/>"
+xs_white_space_replace="<xs:whiteSpace value='replace'/>"
+xs_pattern="<xs:pattern value='a'/>"
+
diff --git a/src/fuzz/seed/uri/dot b/src/fuzz/seed/uri/dot
new file mode 100644
index 0000000..945c9b4
--- /dev/null
+++ b/src/fuzz/seed/uri/dot
@@ -0,0 +1 @@
+.
\ No newline at end of file
diff --git a/src/fuzz/seed/uri/full b/src/fuzz/seed/uri/full
new file mode 100644
index 0000000..808e58a
--- /dev/null
+++ b/src/fuzz/seed/uri/full
Binary files differ
diff --git a/src/fuzz/uri.c b/src/fuzz/uri.c
index 69d0439..5e4c099 100644
--- a/src/fuzz/uri.c
+++ b/src/fuzz/uri.c
@@ -13,6 +13,9 @@
     char *str[2] = { NULL, NULL };
     size_t numStrings;
 
+    if (size > 10000)
+        return(0);
+
     numStrings = xmlFuzzExtractStrings(data, size, str, 2);
 
     uri = xmlParseURI(str[0]);
diff --git a/src/fuzz/xml.c b/src/fuzz/xml.c
index 09867cf..f0dcfcc 100644
--- a/src/fuzz/xml.c
+++ b/src/fuzz/xml.c
@@ -29,21 +29,22 @@
     xmlTextReaderPtr reader;
     xmlChar *out;
     const char *docBuffer, *docUrl;
-    size_t docSize, consumed, chunkSize;
+    size_t maxSize, docSize, consumed, chunkSize;
     int opts, outSize;
 
     xmlFuzzDataInit(data, size);
     opts = xmlFuzzReadInt();
-    /* XML_PARSE_HUGE still causes timeouts. */
-    opts &= ~XML_PARSE_HUGE;
+
+    /* Lower maximum size when processing entities for now. */
+    maxSize = opts & XML_PARSE_NOENT ? 50000 : 500000;
+    if (size > maxSize)
+        goto exit;
 
     xmlFuzzReadEntities();
     docBuffer = xmlFuzzMainEntity(&docSize);
     docUrl = xmlFuzzMainUrl();
-    if (docBuffer == NULL) {
-        xmlFuzzDataCleanup();
-        return(0);
-    }
+    if (docBuffer == NULL)
+        goto exit;
 
     /* Pull parser */
 
@@ -58,6 +59,8 @@
     /* Push parser */
 
     ctxt = xmlCreatePushParserCtxt(NULL, NULL, NULL, 0, docUrl);
+    if (ctxt == NULL)
+        goto exit;
     xmlCtxtUseOptions(ctxt, opts);
 
     for (consumed = 0; consumed < docSize; consumed += chunkSize) {
@@ -76,6 +79,8 @@
     /* Reader */
 
     reader = xmlReaderForMemory(docBuffer, docSize, NULL, NULL, opts);
+    if (reader == NULL)
+        goto exit;
     while (xmlTextReaderRead(reader) == 1) {
         if (xmlTextReaderNodeType(reader) == XML_ELEMENT_NODE) {
             int i, n = xmlTextReaderAttributeCount(reader);
@@ -87,10 +92,8 @@
     }
     xmlFreeTextReader(reader);
 
-    /* Cleanup */
-
+exit:
     xmlFuzzDataCleanup();
-
     return(0);
 }
 
diff --git a/src/fuzz/xml.dict b/src/fuzz/xml.dict
new file mode 100644
index 0000000..2573aea
--- /dev/null
+++ b/src/fuzz/xml.dict
@@ -0,0 +1,76 @@
+xml_decl="<?xml version='1.0'?>"
+xml_decl_latin1="<?xml version='1.0' encoding='ISO-8859-1'?>"
+
+elem_start_end="<a></a>"
+elem_empty="<a/>"
+elem_ns_start_end="<a:a xmlns:a='a'></a:a>"
+elem_ns_empty="<a:a xmlns:a='a'/>"
+
+attr=" a='a'"
+
+ns_decl=" xmlns:a='a'"
+ns_default=" xmlns='a'"
+ns_prefix="a:"
+
+cdata_section="<![CDATA[ ]]>"
+
+comment="<!-- -->"
+
+pi="<?a?>"
+
+elem_decl_any="<!ELEMENT a ANY>"
+elem_decl_empty="<!ELEMENT a EMPTY>"
+elem_decl_children="<!ELEMENT a (a)>"
+elem_decl_mixed="<!ELEMENT a (#PCDATA|a)>"
+elem_children_choice="|a"
+elem_children_seq=",a"
+elem_children_sub_choice="|(a)"
+elem_children_sub_seq=",(a)"
+elem_quant_any="*"
+elem_quant_opt="?"
+elem_quant_some="+"
+
+attlist_decl_cdata_req="<!ATTLIST a a CDATA #REQUIRED>"
+attlist_decl_cdata_imp="<!ATTLIST a a CDATA #IMPLIED>"
+attlist_decl_cdata_def="<!ATTLIST a a CDATA 'a'>"
+attlist_decl_cdata_fix="<!ATTLIST a a CDATA #FIXED 'a'>"
+attlist_decl_id="<!ATTLIST a a ID #IMPLIED>"
+attlist_decl_idref="<!ATTLIST a a IDREF #IMPLIED>"
+attlist_decl_idrefs="<!ATTLIST a a IDREFS #IMPLIED>"
+attlist_decl_entity="<!ATTLIST a a ENTITY #IMPLIED>"
+attlist_decl_entities="<!ATTLIST a a ENTITIES #IMPLIED>"
+attlist_decl_nmtoken="<!ATTLIST a a NMTOKEN #IMPLIED>"
+attlist_decl_nmtokens="<!ATTLIST a a NMTOKENS #IMPLIED>"
+attlist_decl_enum="<!ATTLIST a a (a) #IMPLIED>"
+attlist_decl_notation="<!ATTLIST a a NOTATION (a) #IMPLIED>"
+
+include_sect="<![INCLUDE[ ]]>"
+ignore_sect="<![IGNORE[ ]]>"
+
+ge_decl="<!ENTITY a 'a'>"
+ge_decl_system="<!ENTITY a SYSTEM 'a'>"
+ge_decl_system_ndata="<!ENTITY a SYSTEM 'a' NDATA a>"
+ge_decl_public="<!ENTITY a PUBLIC 'a' 'a'>"
+ge_decl_public_ndata="<!ENTITY a PUBLIC 'a' 'a' NDATA a>"
+
+pe_decl="<!ENTITY % a 'a'>"
+pe_decl_system="<!ENTITY % a SYSTEM 'a'>"
+pe_decl_public="<!ENTITY % a PUBLIC 'a' 'a'>"
+
+char_ref_dec="&#60;"
+char_ref_hex="&#x3c;"
+char_ref_quoted="&#38;#60;"
+
+ge_ref_lt="&lt;"
+ge_ref_gt="&gt;"
+ge_ref_amp="&amp;"
+ge_ref_apos="&apos;"
+ge_ref_quot="&quot;"
+ge_ref="&a;"
+ge_ref_quoted="&#38;a;"
+
+pe_ref="%a;"
+pe_ref_quoted="&#37;a;"
+
+notation_decl_public="<!NOTATION a PUBLIC 'a'>"
+notation_decl_system="<!NOTATION a SYSTEM 'a'>"
diff --git a/src/fuzz/xpath.c b/src/fuzz/xpath.c
index 767acb9..4cb29f6 100644
--- a/src/fuzz/xpath.c
+++ b/src/fuzz/xpath.c
@@ -23,6 +23,9 @@
     const char *expr, *xml;
     size_t exprSize, xmlSize;
 
+    if (size > 10000)
+        return(0);
+
     xmlFuzzDataInit(data, size);
 
     expr = xmlFuzzReadString(&exprSize);
diff --git a/src/fuzz/xpath.dict b/src/fuzz/xpath.dict
new file mode 100644
index 0000000..4fe375f
--- /dev/null
+++ b/src/fuzz/xpath.dict
@@ -0,0 +1,94 @@
+# XML
+
+elem_a="<a></a>"
+elem_b="<b></b>"
+elem_c="<c></c>"
+elem_d="<d></d>"
+elem_empty="<a/>"
+elem_ns_a="<a:a xmlns:a='a'></a:a>"
+elem_ns_b="<b:b xmlns:b='b'></b:b>"
+
+attr_a=" a='a'"
+attr_b=" b='b'"
+
+ns_decl=" xmlns:a='a'"
+ns_default=" xmlns='a'"
+ns_prefix_a="a:"
+ns_prefix_b="b:"
+
+cdata_section="<![CDATA[ ]]>"
+
+comment="<!-- -->"
+
+pi="<?a?>"
+
+# XPath
+
+axis_ancestor="ancestor::"
+axis_ancestor_or_self="ancestor-or-self::"
+axis_attribute="attribute::"
+axis_attribute_abbrev="@"
+axis_child="child::"
+axis_descendant="descendant::"
+axis_descendant_or_self="descendant-or-self::"
+axis_following="following::"
+axis_following_sibling="following-sibling::"
+axis_namespace="namespace::"
+axis_parent="parent::"
+axis_preceding="preceding::"
+axis_preceding_siblings="preceding-sibling::"
+axis_self="self::"
+
+node_test_ns="a:"
+
+val_num="=(1.0)"
+val_str_sq="=('a')"
+val_str_dq="=(\"a\")"
+val_node_set="=(*)"
+val_elem="=(b)"
+
+step_root="/"
+step_descendant="//"
+step_any="//*"
+step_any_l="*//"
+step_elem="//b"
+step_ns_elem="//a:a"
+step_comment="//comment()"
+step_node="//node()"
+step_node_l="node()//"
+step_pi="//processing-instruction()"
+step_text="//text()"
+step_parent="../"
+
+op_plus="+1"
+op_minus=" - 1"
+op_neg="-"
+op_mul="*1"
+op_div=" div 1"
+op_mod=" mod 1"
+op_and=" and 1"
+op_or=" or 1"
+op_ne="!=1"
+op_lt="<1"
+op_gt=">1"
+op_le="<=1"
+op_ge=">=1"
+op_predicate_num="[1]"
+op_predicate_last="[last()]"
+op_predicate_str="['a']"
+op_predicate="[1=1]"
+op_arg_num=",1"
+op_arg_str=",'a'"
+op_arg_node=",*"
+op_union="|//b"
+
+var_num="=$f"
+var_bool="=$b"
+var_str="=$s"
+var_node_set="=$n"
+
+# Unicode
+
+utf8_2="\xC3\x84"
+utf8_3="\xE2\x80\x9C"
+utf8_4="\xF0\x9F\x98\x80"
diff --git a/src/include/libxml/xmlexports.h b/src/include/libxml/xmlexports.h
index f03af0d..aceede5 100644
--- a/src/include/libxml/xmlexports.h
+++ b/src/include/libxml/xmlexports.h
@@ -3,43 +3,46 @@
  * Description: macros for marking symbols as exportable/importable.
  *
  * Copy: See Copyright for the status of this software.
- *
- * Author: Igor Zlatovic <igor@zlatkovic.com>
  */
 
 #ifndef __XML_EXPORTS_H__
 #define __XML_EXPORTS_H__
 
-/**
- * XMLPUBFUN, XMLPUBVAR, XMLCALL
- *
- * Macros which declare an exportable function, an exportable variable and
- * the calling convention used for functions.
- *
- * Please use an extra block for every platform/compiler combination when
- * modifying this, rather than overlong #ifdef lines. This helps
- * readability as well as the fact that different compilers on the same
- * platform might need different definitions.
- */
+#if defined(_WIN32) || defined(__CYGWIN__)
+/** DOC_DISABLE */
+
+#ifdef LIBXML_STATIC
+  #define XMLPUBLIC
+#elif defined(IN_LIBXML)
+  #define XMLPUBLIC __declspec(dllexport)
+#else
+  #define XMLPUBLIC __declspec(dllimport)
+#endif
+
+#if defined(LIBXML_FASTCALL)
+  #define XMLCALL __fastcall
+#else
+  #define XMLCALL __cdecl
+#endif
+#define XMLCDECL __cdecl
+
+/** DOC_ENABLE */
+#else /* not Windows */
 
 /**
- * XMLPUBFUN:
+ * XMLPUBLIC:
  *
- * Macros which declare an exportable function
+ * Macro which declares a public symbol
  */
-#define XMLPUBFUN
-/**
- * XMLPUBVAR:
- *
- * Macros which declare an exportable variable
- */
-#define XMLPUBVAR extern
+#define XMLPUBLIC
+
 /**
  * XMLCALL:
  *
- * Macros which declare the called convention for exported functions
+ * Macro which declares the calling convention for exported functions
  */
 #define XMLCALL
+
 /**
  * XMLCDECL:
  *
@@ -48,100 +51,21 @@
  */
 #define XMLCDECL
 
-/** DOC_DISABLE */
+#endif /* platform switch */
 
-/* Windows platform with MS compiler */
-#if defined(_WIN32) && defined(_MSC_VER)
-  #undef XMLPUBFUN
-  #undef XMLPUBVAR
-  #undef XMLCALL
-  #undef XMLCDECL
-  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
-    #define XMLPUBFUN __declspec(dllexport)
-    #define XMLPUBVAR __declspec(dllexport)
-  #else
-    #define XMLPUBFUN
-    #if !defined(LIBXML_STATIC)
-      #define XMLPUBVAR __declspec(dllimport) extern
-    #else
-      #define XMLPUBVAR extern
-    #endif
-  #endif
-  #if defined(LIBXML_FASTCALL)
-    #define XMLCALL __fastcall
-  #else
-    #define XMLCALL __cdecl
-  #endif
-  #define XMLCDECL __cdecl
-#endif
+/*
+ * XMLPUBFUN:
+ *
+ * Macro which declares an exportable function
+ */
+#define XMLPUBFUN XMLPUBLIC
 
-/* Windows platform with Borland compiler */
-#if defined(_WIN32) && defined(__BORLANDC__)
-  #undef XMLPUBFUN
-  #undef XMLPUBVAR
-  #undef XMLCALL
-  #undef XMLCDECL
-  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
-    #define XMLPUBFUN __declspec(dllexport)
-    #define XMLPUBVAR __declspec(dllexport) extern
-  #else
-    #define XMLPUBFUN
-    #if !defined(LIBXML_STATIC)
-      #define XMLPUBVAR __declspec(dllimport) extern
-    #else
-      #define XMLPUBVAR extern
-    #endif
-  #endif
-  #define XMLCALL __cdecl
-  #define XMLCDECL __cdecl
-#endif
-
-/* Windows platform with GNU compiler (Mingw) */
-#if defined(_WIN32) && defined(__MINGW32__)
-  #undef XMLPUBFUN
-  #undef XMLPUBVAR
-  #undef XMLCALL
-  #undef XMLCDECL
-  /*
-   * if defined(IN_LIBXML) this raises problems on mingw with msys
-   * _imp__xmlFree listed as missing. Try to workaround the problem
-   * by also making that declaration when compiling client code.
-   */
-  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
-    #define XMLPUBFUN __declspec(dllexport)
-    #define XMLPUBVAR __declspec(dllexport) extern
-  #else
-    #define XMLPUBFUN
-    #if !defined(LIBXML_STATIC)
-      #define XMLPUBVAR __declspec(dllimport) extern
-    #else
-      #define XMLPUBVAR extern
-    #endif
-  #endif
-  #define XMLCALL __cdecl
-  #define XMLCDECL __cdecl
-#endif
-
-/* Cygwin platform (does not define _WIN32), GNU compiler */
-#if defined(__CYGWIN__)
-  #undef XMLPUBFUN
-  #undef XMLPUBVAR
-  #undef XMLCALL
-  #undef XMLCDECL
-  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
-    #define XMLPUBFUN __declspec(dllexport)
-    #define XMLPUBVAR __declspec(dllexport)
-  #else
-    #define XMLPUBFUN
-    #if !defined(LIBXML_STATIC)
-      #define XMLPUBVAR __declspec(dllimport) extern
-    #else
-      #define XMLPUBVAR extern
-    #endif
-  #endif
-  #define XMLCALL __cdecl
-  #define XMLCDECL __cdecl
-#endif
+/**
+ * XMLPUBVAR:
+ *
+ * Macro which declares an exportable variable
+ */
+#define XMLPUBVAR XMLPUBLIC extern
 
 /* Compatibility */
 #if !defined(LIBXML_DLL_IMPORT)
diff --git a/src/include/libxml/xpath.h b/src/include/libxml/xpath.h
index a4303ff..539593f 100644
--- a/src/include/libxml/xpath.h
+++ b/src/include/libxml/xpath.h
@@ -359,8 +359,6 @@
     unsigned long opLimit;
     unsigned long opCount;
     int depth;
-    int maxDepth;
-    int maxParserDepth;
 };
 
 /*
diff --git a/src/libxml2-config.cmake.cmake.in b/src/libxml2-config.cmake.cmake.in
new file mode 100644
index 0000000..27586aa
--- /dev/null
+++ b/src/libxml2-config.cmake.cmake.in
@@ -0,0 +1,136 @@
+# libxml2-config.cmake
+# --------------------
+#
+# Libxml2 cmake module.
+# This module sets the following variables:
+#
+# ::
+#
+#   LIBXML2_INCLUDE_DIR        - Directory where LibXml2 headers are located.
+#   LIBXML2_INCLUDE_DIRS       - list of the include directories needed to use LibXml2.
+#   LIBXML2_LIBRARY            - path to the LibXml2 library.
+#   LIBXML2_LIBRARIES          - xml2 libraries to link against.
+#   LIBXML2_DEFINITIONS        - the compiler switches required for using LibXml2.
+#   LIBXML2_VERSION_MAJOR      - The major version of libxml2.
+#   LIBXML2_VERSION_MINOR      - The minor version of libxml2.
+#   LIBXML2_VERSION_PATCH      - The patch version of libxml2.
+#   LIBXML2_VERSION_STRING     - version number as a string (ex: "2.3.4")
+#   LIBXML2_MODULES            - whether libxml2 has dso support
+#   LIBXML2_XMLLINT_EXECUTABLE - path to the XML checking tool xmllint coming with LibXml2
+
+include("${CMAKE_CURRENT_LIST_DIR}/libxml2-export.cmake")
+
+@PACKAGE_INIT@
+
+set(LIBXML2_VERSION_MAJOR  @LIBXML_MAJOR_VERSION@)
+set(LIBXML2_VERSION_MINOR  @LIBXML_MINOR_VERSION@)
+set(LIBXML2_VERSION_PATCH  @LIBXML_MICRO_VERSION@)
+set(LIBXML2_VERSION_STRING "@VERSION@")
+set(LIBXML2_INSTALL_PREFIX ${PACKAGE_PREFIX_DIR})
+set(LIBXML2_INCLUDE_DIR    ${PACKAGE_PREFIX_DIR}/@CMAKE_INSTALL_INCLUDEDIR@/libxml2)
+set(LIBXML2_LIBRARY_DIR    ${PACKAGE_PREFIX_DIR}/@CMAKE_INSTALL_LIBDIR@)
+
+macro(select_library_location target basename)
+  if(TARGET ${target})
+    foreach(property IN ITEMS IMPORTED_LOCATION IMPORTED_IMPLIB)
+      get_target_property(${basename}_${property}_DEBUG ${target} ${property}_DEBUG)
+      get_target_property(${basename}_${property}_MINSIZEREL ${target} ${property}_MINSIZEREL)
+      get_target_property(${basename}_${property}_RELEASE ${target} ${property}_RELEASE)
+      get_target_property(${basename}_${property}_RELWITHDEBINFO ${target} ${property}_RELWITHDEBINFO)
+
+      if(${basename}_${property}_DEBUG AND ${basename}_${property}_RELEASE)
+        set(${basename}_LIBRARY debug ${${basename}_${property}_DEBUG} optimized ${${basename}_${property}_RELEASE})
+      elseif(${basename}_${property}_DEBUG AND ${basename}_${property}_RELWITHDEBINFO)
+        set(${basename}_LIBRARY debug ${${basename}_${property}_DEBUG} optimized ${${basename}_${property}_RELWITHDEBINFO})
+      elseif(${basename}_${property}_DEBUG AND ${basename}_${property}_MINSIZEREL)
+        set(${basename}_LIBRARY debug ${${basename}_${property}_DEBUG} optimized ${${basename}_${property}_MINSIZEREL})
+      elseif(${basename}_${property}_RELEASE)
+        set(${basename}_LIBRARY ${${basename}_${property}_RELEASE})
+      elseif(${basename}_${property}_RELWITHDEBINFO)
+        set(${basename}_LIBRARY ${${basename}_${property}_RELWITHDEBINFO})
+      elseif(${basename}_${property}_MINSIZEREL)
+        set(${basename}_LIBRARY ${${basename}_${property}_MINSIZEREL})
+      elseif(${basename}_${property}_DEBUG)
+        set(${basename}_LIBRARY ${${basename}_${property}_DEBUG})
+      endif()
+    endforeach()
+  endif()
+endmacro()
+
+macro(select_executable_location target basename)
+  if(TARGET ${target})
+    get_target_property(${basename}_IMPORTED_LOCATION_DEBUG ${target} IMPORTED_LOCATION_DEBUG)
+    get_target_property(${basename}_IMPORTED_LOCATION_MINSIZEREL ${target} IMPORTED_LOCATION_MINSIZEREL)
+    get_target_property(${basename}_IMPORTED_LOCATION_RELEASE ${target} IMPORTED_LOCATION_RELEASE)
+    get_target_property(${basename}_IMPORTED_LOCATION_RELWITHDEBINFO ${target} IMPORTED_LOCATION_RELWITHDEBINFO)
+
+    if(${basename}_IMPORTED_LOCATION_RELEASE)
+      set(${basename}_EXECUTABLE ${${basename}_IMPORTED_LOCATION_RELEASE})
+    elseif(${basename}_IMPORTED_LOCATION_RELWITHDEBINFO)
+      set(${basename}_EXECUTABLE ${${basename}_IMPORTED_LOCATION_RELWITHDEBINFO})
+    elseif(${basename}_IMPORTED_LOCATION_MINSIZEREL)
+      set(${basename}_EXECUTABLE ${${basename}_IMPORTED_LOCATION_MINSIZEREL})
+    elseif(${basename}_IMPORTED_LOCATION_DEBUG)
+      set(${basename}_EXECUTABLE ${${basename}_IMPORTED_LOCATION_DEBUG})
+    endif()
+  endif()
+endmacro()
+
+select_library_location(LibXml2::LibXml2 LIBXML2)
+select_executable_location(LibXml2::xmlcatalog LIBXML2_XMLCATALOG)
+select_executable_location(LibXml2::xmllint LIBXML2_XMLLINT)
+
+set(LIBXML2_LIBRARIES ${LIBXML2_LIBRARY})
+set(LIBXML2_INCLUDE_DIRS ${LIBXML2_INCLUDE_DIR})
+
+include(CMakeFindDependencyMacro)
+
+set(LIBXML2_SHARED @BUILD_SHARED_LIBS@)
+set(LIBXML2_WITH_ICONV @LIBXML2_WITH_ICONV@)
+set(LIBXML2_WITH_THREADS @LIBXML2_WITH_THREADS@)
+set(LIBXML2_WITH_ICU @LIBXML2_WITH_ICU@)
+set(LIBXML2_WITH_LZMA @LIBXML2_WITH_LZMA@)
+set(LIBXML2_WITH_ZLIB @LIBXML2_WITH_ZLIB@)
+
+if(LIBXML2_WITH_ICONV)
+  find_dependency(Iconv)
+  list(APPEND LIBXML2_LIBRARIES    ${Iconv_LIBRARIES})
+  list(APPEND LIBXML2_INCLUDE_DIRS ${Iconv_INCLUDE_DIRS})
+endif()
+
+if(NOT LIBXML2_SHARED)
+  set(LIBXML2_DEFINITIONS -DLIBXML_STATIC)
+
+  if(LIBXML2_WITH_THREADS)
+    find_dependency(Threads)
+    list(APPEND LIBXML2_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
+  endif()
+
+  if(LIBXML2_WITH_ICU)
+    find_dependency(ICU COMPONENTS data i18n uc)
+    list(APPEND LIBXML2_LIBRARIES    ${ICU_LIBRARIES})
+  endif()
+
+  if(LIBXML2_WITH_LZMA)
+    find_dependency(LibLZMA)
+    list(APPEND LIBXML2_LIBRARIES    ${LIBLZMA_LIBRARIES})
+  endif()
+
+  if(LIBXML2_WITH_ZLIB)
+    find_dependency(ZLIB)
+    list(APPEND LIBXML2_LIBRARIES    ${ZLIB_LIBRARIES})
+  endif()
+
+  if(UNIX)
+    list(APPEND LIBXML2_LIBRARIES m)
+  endif()
+
+  if(WIN32)
+    list(APPEND LIBXML2_LIBRARIES ws2_32)
+  endif()
+endif()
+
+# whether libxml2 has dso support
+set(LIBXML2_MODULES @LIBXML2_WITH_MODULES@)
+
+mark_as_advanced(LIBXML2_LIBRARY LIBXML2_XMLCATALOG_EXECUTABLE LIBXML2_XMLLINT_EXECUTABLE)
diff --git a/src/libxml2-config.cmake.in b/src/libxml2-config.cmake.in
index 6b16fc2..4989690 100644
--- a/src/libxml2-config.cmake.in
+++ b/src/libxml2-config.cmake.in
@@ -2,17 +2,26 @@
 # --------------------
 #
 # Libxml2 cmake module.
-# THis module sets the following variables:
+# This module sets the following variables:
 #
 # ::
 #
-#   LIBXML2_INCLUDE_DIRS      - Directory where libxml2 headers are located.
-#   LIBXML2_LIBRARIES         - xml2 libraries to link against.
-#   LIBXML2_VERSION_MAJOR     - The major version of libxml2.
-#   LIBXML2_VERSION_MINOR     - The minor version of libxml2.
-#   LIBXML2_VERSION_PATCH     - The patch version of libxml2.
-#   LIBXML2_VERSION_STRING    - version number as a string (ex: "2.3.4")
-#   LIBXML2_MODULES           - whether libxml2 as dso support
+#   LIBXML2_INCLUDE_DIR        - Directory where LibXml2 headers are located.
+#   LIBXML2_INCLUDE_DIRS       - list of the include directories needed to use LibXml2.
+#   LIBXML2_LIBRARY            - path to the LibXml2 library.
+#   LIBXML2_LIBRARIES          - xml2 libraries to link against.
+#   LIBXML2_DEFINITIONS        - the compiler switches required for using LibXml2.
+#   LIBXML2_VERSION_MAJOR      - The major version of libxml2.
+#   LIBXML2_VERSION_MINOR      - The minor version of libxml2.
+#   LIBXML2_VERSION_PATCH      - The patch version of libxml2.
+#   LIBXML2_VERSION_STRING     - version number as a string (ex: "2.3.4")
+#   LIBXML2_MODULES            - whether libxml2 has dso support
+#   LIBXML2_XMLLINT_EXECUTABLE - path to the XML checking tool xmllint coming with LibXml2
+#
+# The following targets are defined:
+#
+#   LibXml2::LibXml2          - the LibXml2 library
+#   LibXml2::xmllint          - the xmllint command-line executable
 
 get_filename_component(_libxml2_rootdir ${CMAKE_CURRENT_LIST_DIR}/../../../ ABSOLUTE)
 
@@ -20,31 +29,87 @@
 set(LIBXML2_VERSION_MINOR  @LIBXML_MINOR_VERSION@)
 set(LIBXML2_VERSION_MICRO  @LIBXML_MICRO_VERSION@)
 set(LIBXML2_VERSION_STRING "@VERSION@")
+set(LIBXML2_DEFINITIONS    "@XML_CFLAGS@")
 set(LIBXML2_INSTALL_PREFIX ${_libxml2_rootdir})
-set(LIBXML2_INCLUDE_DIRS   ${_libxml2_rootdir}/include ${_libxml2_rootdir}/include/libxml2)
+set(LIBXML2_INCLUDE_DIR    ${_libxml2_rootdir}/include/libxml2)
 set(LIBXML2_LIBRARY_DIR    ${_libxml2_rootdir}/lib)
-set(LIBXML2_LIBRARIES      -L${LIBXML2_LIBRARY_DIR} -lxml2)
 
-if(@WITH_THREADS@)
-  find_package(Threads REQUIRED)
-  list(APPEND LIBXML2_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
+find_library(LIBXML2_LIBRARY NAMES xml2 HINTS ${LIBXML2_LIBRARY_DIR} NO_DEFAULT_PATH)
+find_program(LIBXML2_XMLCATALOG_EXECUTABLE NAMES xmlcatalog HINTS ${_libxml2_rootdir}/bin NO_DEFAULT_PATH)
+find_program(LIBXML2_XMLLINT_EXECUTABLE NAMES xmllint HINTS ${_libxml2_rootdir}/bin NO_DEFAULT_PATH)
+
+set(LIBXML2_LIBRARIES ${LIBXML2_LIBRARY})
+set(LIBXML2_INCLUDE_DIRS ${LIBXML2_INCLUDE_DIR})
+unset(LIBXML2_INTERFACE_LINK_LIBRARIES)
+
+include(CMakeFindDependencyMacro)
+
+set(LIBXML2_WITH_ICONV @WITH_ICONV@)
+set(LIBXML2_WITH_THREADS @WITH_THREADS@)
+set(LIBXML2_WITH_ICU @WITH_ICU@)
+set(LIBXML2_WITH_LZMA @WITH_LZMA@)
+set(LIBXML2_WITH_ZLIB @WITH_ZLIB@)
+
+if(LIBXML2_WITH_ICONV)
+  find_dependency(Iconv)
+  list(APPEND LIBXML2_LIBRARIES    ${Iconv_LIBRARIES})
+  list(APPEND LIBXML2_INCLUDE_DIRS ${Iconv_INCLUDE_DIRS})
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "Iconv::Iconv")
 endif()
 
-if(@WITH_LZMA@)
-  find_package(LibLZMA REQUIRED)
+if(LIBXML2_WITH_THREADS)
+  find_dependency(Threads)
+  list(APPEND LIBXML2_LIBRARIES    ${CMAKE_THREAD_LIBS_INIT})
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:Threads::Threads>")
+endif()
+
+if(LIBXML2_WITH_ICU)
+  find_dependency(ICU COMPONENTS data i18n uc)
+  list(APPEND LIBXML2_LIBRARIES    ${ICU_LIBRARIES})
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:ICU::data>;\$<LINK_ONLY:ICU::i18n>;\$<LINK_ONLY:ICU::uc>")
+endif()
+
+if(LIBXML2_WITH_LZMA)
+  find_dependency(LibLZMA)
   list(APPEND LIBXML2_LIBRARIES    ${LIBLZMA_LIBRARIES})
-  list(APPEND LIBXML2_INCLUDE_DIRS ${LIBLZMA_INCLUDE_DIRS})
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:LibLZMA::LibLZMA>")
 endif()
 
-if(@WITH_ZLIB@)
-  find_package(ZLIB REQUIRED)
+if(LIBXML2_WITH_ZLIB)
+  find_dependency(ZLIB)
   list(APPEND LIBXML2_LIBRARIES    ${ZLIB_LIBRARIES})
-  list(APPEND LIBXML2_INCLUDE_DIRS ${ZLIB_INCLUDE_DIRS})
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:ZLIB::ZLIB>")
 endif()
 
-list(APPEND LIBXML2_LIBRARIES @ICU_LIBS@ @ICONV_LIBS@ @M_LIBS@ @WIN32_EXTRA_LIBADD@ @LIBS@)
+if(UNIX)
+  list(APPEND LIBXML2_LIBRARIES    m)
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:m>")
+endif()
+
+if(WIN32)
+  list(APPEND LIBXML2_LIBRARIES    ws2_32)
+  list(APPEND LIBXML2_INTERFACE_LINK_LIBRARIES "\$<LINK_ONLY:ws2_32>")
+endif()
 
 # whether libxml2 has dso support
 set(LIBXML2_MODULES @WITH_MODULES@)
 
-mark_as_advanced( LIBXML2_INCLUDE_DIRS LIBXML2_LIBRARIES )
+mark_as_advanced(LIBXML2_LIBRARY LIBXML2_XMLCATALOG_EXECUTABLE LIBXML2_XMLLINT_EXECUTABLE)
+
+if(NOT TARGET LibXml2::LibXml2 AND DEFINED LIBXML2_LIBRARY AND DEFINED LIBXML2_INCLUDE_DIRS)
+  add_library(LibXml2::LibXml2 UNKNOWN IMPORTED)
+  set_target_properties(LibXml2::LibXml2 PROPERTIES IMPORTED_LOCATION "${LIBXML2_LIBRARY}")
+  set_target_properties(LibXml2::LibXml2 PROPERTIES INTERFACE_COMPILE_OPTIONS "${LIBXML2_DEFINITIONS}")
+  set_target_properties(LibXml2::LibXml2 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${LIBXML2_INCLUDE_DIRS}")
+  set_target_properties(LibXml2::LibXml2 PROPERTIES INTERFACE_LINK_LIBRARIES "${LIBXML2_INTERFACE_LINK_LIBRARIES}")
+endif()
+
+if(NOT TARGET LibXml2::xmlcatalog AND DEFINED LIBXML2_XMLCATALOG_EXECUTABLE)
+  add_executable(LibXml2::xmlcatalog IMPORTED)
+  set_target_properties(LibXml2::xmlcatalog PROPERTIES IMPORTED_LOCATION "${LIBXML2_XMLCATALOG_EXECUTABLE}")
+endif()
+
+if(NOT TARGET LibXml2::xmllint AND DEFINED LIBXML2_XMLLINT_EXECUTABLE)
+  add_executable(LibXml2::xmllint IMPORTED)
+  set_target_properties(LibXml2::xmllint PROPERTIES IMPORTED_LOCATION "${LIBXML2_XMLLINT_EXECUTABLE}")
+endif()
diff --git a/src/libxml2.spec b/src/libxml2.spec
index 6f6c1d0..626f900 100644
--- a/src/libxml2.spec
+++ b/src/libxml2.spec
@@ -204,6 +204,6 @@
 %endif # with_python3
 
 %changelog
-* Wed Oct  7 2020 Daniel Veillard <veillard@redhat.com>
+* Mon Feb  1 2021 Daniel Veillard <veillard@redhat.com>
 - upstream release 2.9.10 see http://xmlsoft.org/news.html
 
diff --git a/src/parser.c b/src/parser.c
index 5633e3e..3ac2ca6 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -4502,7 +4502,7 @@
             if (ctxt->instate == XML_PARSER_EOF)
 		return;
 	    in = ctxt->input->cur;
-	} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
+	} while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09) || (*in == 0x0a));
 	nbchar = 0;
     }
     ctxt->input->line = line;
@@ -4983,7 +4983,7 @@
 	    ctxt->input->col++;
 	    goto get_more;
 	}
-    } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09));
+    } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09) || (*in == 0x0a));
     xmlParseCommentComplex(ctxt, buf, len, size);
     ctxt->instate = state;
     return;
@@ -6078,14 +6078,20 @@
 	    NEXT;
 	    if (elem == NULL) {
 	        ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
-		if (ret == NULL) return(NULL);
+		if (ret == NULL) {
+		    xmlFreeDocElementContent(ctxt->myDoc, cur);
+                    return(NULL);
+                }
 		ret->c1 = cur;
 		if (cur != NULL)
 		    cur->parent = ret;
 		cur = ret;
 	    } else {
 	        n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
-		if (n == NULL) return(NULL);
+		if (n == NULL) {
+		    xmlFreeDocElementContent(ctxt->myDoc, ret);
+                    return(NULL);
+                }
 		n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
 		if (n->c1 != NULL)
 		    n->c1->parent = n;
@@ -7153,6 +7159,7 @@
 	    ent->checked |= 1;
 	if (ret == XML_ERR_ENTITY_LOOP) {
 	    xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
+            xmlHaltParser(ctxt);
 	    xmlFreeNodeList(list);
 	    return;
 	}
diff --git a/src/tree.c b/src/tree.c
index 64572d9..2130d55 100644
--- a/src/tree.c
+++ b/src/tree.c
@@ -1649,6 +1649,10 @@
 
     if (!xmlBufIsEmpty(buf)) {
 	node = xmlNewDocText(doc, NULL);
+        if (node == NULL) {
+            xmlBufFree(buf);
+            return(NULL);
+        }
 	node->content = xmlBufDetach(buf);
 
 	if (last == NULL) {
diff --git a/src/uri.c b/src/uri.c
index 91c4619..8204825 100644
--- a/src/uri.c
+++ b/src/uri.c
@@ -11,6 +11,7 @@
 #define IN_LIBXML
 #include "libxml.h"
 
+#include <limits.h>
 #include <string.h>
 
 #include <libxml/xmlmemory.h>
@@ -329,9 +330,14 @@
 
     if (ISA_DIGIT(cur)) {
 	while (ISA_DIGIT(cur)) {
-	    port = port * 10 + (*cur - '0');
-            if (port > 99999999)
-                port = 99999999;
+            int digit = *cur - '0';
+
+            if (port > INT_MAX / 10)
+                return(1);
+            port *= 10;
+            if (port > INT_MAX - digit)
+                return(1);
+	    port += digit;
 
 	    cur++;
 	}
@@ -1748,11 +1754,6 @@
     xmlURIPtr uri;
     int ret2;
 
-#define NULLCHK(p) if(!p) { \
-         xmlURIErrMemory("escaping URI value\n"); \
-         xmlFreeURI(uri); \
-         return NULL; } \
-
     if (str == NULL)
         return (NULL);
 
@@ -1774,6 +1775,12 @@
 
     ret = NULL;
 
+#define NULLCHK(p) if(!p) { \
+         xmlURIErrMemory("escaping URI value\n"); \
+         xmlFreeURI(uri); \
+         xmlFree(ret); \
+         return NULL; } \
+
     if (uri->scheme) {
         segment = xmlURIEscapeStr(BAD_CAST uri->scheme, BAD_CAST "+-.");
         NULLCHK(segment)
@@ -1794,7 +1801,7 @@
     if (uri->user) {
         segment = xmlURIEscapeStr(BAD_CAST uri->user, BAD_CAST ";:&=+$,");
         NULLCHK(segment)
-		ret = xmlStrcat(ret,BAD_CAST "//");
+        ret = xmlStrcat(ret,BAD_CAST "//");
         ret = xmlStrcat(ret, segment);
         ret = xmlStrcat(ret, BAD_CAST "@");
         xmlFree(segment);
@@ -1803,8 +1810,8 @@
     if (uri->server) {
         segment = xmlURIEscapeStr(BAD_CAST uri->server, BAD_CAST "/?;:@");
         NULLCHK(segment)
-		if (uri->user == NULL)
-		ret = xmlStrcat(ret, BAD_CAST "//");
+        if (uri->user == NULL)
+            ret = xmlStrcat(ret, BAD_CAST "//");
         ret = xmlStrcat(ret, segment);
         xmlFree(segment);
     }
diff --git a/src/xmlreader.c b/src/xmlreader.c
index 01adf74..72e40b0 100644
--- a/src/xmlreader.c
+++ b/src/xmlreader.c
@@ -1585,7 +1585,8 @@
     /*
      * Handle XInclude if asked for
      */
-    if ((reader->xinclude) && (reader->node != NULL) &&
+    if ((reader->xinclude) && (reader->in_xinclude == 0) &&
+        (reader->node != NULL) &&
 	(reader->node->type == XML_ELEMENT_NODE) &&
 	(reader->node->ns != NULL) &&
 	((xmlStrEqual(reader->node->ns->href, XINCLUDE_NS)) ||